Bincode v0.3.0 Bincode.Structs View Source
Module defining macros related to structs and enums.
Link to this section Summary
Functions
Declares a new enum. This macro generates a module for the enum, plus a struct for each variant with serialization and deserialization methods according to the given fields.
Declares a new struct. This macro generates a struct with serialization and deserialization methods according to the given fields.
Link to this section Functions
Declares a new enum. This macro generates a module for the enum, plus a struct for each variant with serialization and deserialization methods according to the given fields.
Options
absolute- When set to true, the given struct name is interpreted as the absolute module name. When set to false, the given struct name is appended to the caller's module. Defaults to false.
Example
defmodule MyEnums do
import Bincode.Structs
declare_enum(IpAddr,
V4: [tuple: {:u8, :u8, :u8, :u8}],
V6: [addr: :string]
)
end
alias MyEnums.IpAddr
ip_v4 = %IpAddr.V4{tuple: {127, 0, 0, 1}}
{:ok, <<0, 0, 0, 0, 127, 0, 0, 1>>} = Bincode.serialize(ip_v4, IpAddr)
ip_v6 = %IpAddr.V6{addr: "::1"}
{:ok, <<1, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 58, 58, 49>>} = Bincode.serialize(ip_v6, IpAddr)It's also possible to call serialize and deserialize from the struct module directly.
{:ok, {%IpAddr.V4{tuple: {127, 0, 0, 1}}, ""}} = IpAddr.deserialize(<<0, 0, 0, 0, 127, 0, 0, 1>>)
{:ok, {%IpAddr.V6{addr: "::1"}, ""}} = IpAddr.deserialize(<<1, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 58, 58, 49>>)Enums can be nested and contain structs. See Bincode.Structs.declare_struct/3.
Declares a new struct. This macro generates a struct with serialization and deserialization methods according to the given fields.
Options
absolute- When set to true, the given struct name is interpreted as the absolute module name. When set to false, the given struct name is appended to the caller's module. Defaults to false.
Example
defmodule MyStructs do
import Bincode.Structs
declare_struct(Person,
first_name: :string,
last_name: :string,
age: :u8
)
end
alias MyStructs.Person
person = %Person{first_name: "John", last_name: "Doe", age: 44}
{:ok, <<4, 0, 0, 0, 0, 0, 0, 0, 74, 111, 104, 110, 3, 0, 0, 0, 0, 0, 0, 0, 68, 111, 101, 44>>} = Bincode.serialize(person, Person)It's also possible to call serialize and deserialize from the struct module directly.
{:ok, {%Person{age: 44, first_name: "John", last_name: "Doe"}, ""}} = Person.deserialize(<<4, 0, 0, 0, 0, 0, 0, 0, 74, 111, 104, 110, 3, 0, 0, 0, 0, 0, 0, 0, 68, 111, 101, 44>>)Structs and enums can be nested. In this case the type is the fully qualified module. For example:
defmodule MyStructs do
import Bincode.Structs
declare_struct(Person,
first_name: :string,
last_name: :string,
age: :u8
)
declare_struct(Employee,
employee_number: :u64,
person: MyStructs.Person,
job_title: :string,
)
end