Protobuf behaviour (protobuf v0.8.0) View Source
protoc
should always be used to generate code instead of writing the code by hand.
By use
this module, macros defined in Protobuf.DSL
will be injected. Most of thee macros
are equal to definition in .proto files.
defmodule Foo do
use Protobuf, syntax: :proto3
defstruct [:a, :b]
field :a, 1, type: :int32
field :b, 2, type: :string
end
Your Protobuf message(module) is just a normal Elixir struct. Some useful functions are also injected, see "Callbacks" for details. Examples:
foo1 = Foo.new!(%{a: 1})
foo1.b == ""
bin = Foo.encode(foo1)
foo1 == Foo.decode(bin)
Except functions in "Callbacks", some other functions may be defined:
- Extension functions when your Protobuf message use extensions. See
Protobuf.Extension
for details.put_extension(struct, extension_mod, field, value)
get_extension(struct, extension_mod, field, default \ nil)
Link to this section Summary
Callbacks
Decode a protobuf binary to a struct.
Encode the struct to a protobuf binary.
Build a blank struct with default values. This and other "new" functions are
preferred than raw building struct method like %Foo{}
.
Build and update the struct with passed fields.
Similar to new/1
, but use struct!/2
to build the struct, so
errors will be raised if unknown keys are passed.
Returns nil
or a transformer module that implements the Protobuf.TransformModule
behaviour.
Functions
It's preferable to use message's decode
function, like
It's preferable to use message's encode
function, like
Loads extensions modules.
Link to this section Callbacks
Specs
Decode a protobuf binary to a struct.
Errors may be raised if there's something wrong in the binary.
Specs
Encode the struct to a protobuf binary.
Errors may be raised if there's something wrong in the struct.
Specs
new() :: struct()
Build a blank struct with default values. This and other "new" functions are
preferred than raw building struct method like %Foo{}
.
In proto3, the zero values are the default values.
Specs
Build and update the struct with passed fields.
Specs
Similar to new/1
, but use struct!/2
to build the struct, so
errors will be raised if unknown keys are passed.
Specs
transform_module() :: module() | nil
Returns nil
or a transformer module that implements the Protobuf.TransformModule
behaviour.
This function is overridable in your module.
Link to this section Functions
Specs
It's preferable to use message's decode
function, like:
Foo.decode(bin)
Specs
It's preferable to use message's encode
function, like:
Foo.encode(foo)
Specs
load_extensions() :: :ok
Loads extensions modules.
This function should be called in your application's start/2
callback,
as seen in the example below, if you wish to use extensions.
Example
def start(_type, _args) do
Protobuf.load_extensions()
Supervisor.start_link([], strategy: :one_for_one)
end