protobuf v0.8.0-beta.1 Protobuf behaviour

protoc should always be used to generate code instead of wrting 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

Functions

It's preferable to use message's decode function, like

It's preferable to use message's encode function, like

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

Link to this section Functions

Link to this function

decode(data, mod)
decode(binary(), module()) :: struct()

It's preferable to use message's decode function, like

Foo.decode(bin)
Link to this function

encode(struct)
encode(struct()) :: binary()

It's preferable to use message's encode function, like

Foo.encode(foo)

Link to this section Callbacks

Link to this callback

decode(binary)
decode(binary()) :: struct()

Decode a protobuf binary to a struct.

Errors may be raised if there's something wrong in the binary.

Link to this callback

encode(struct)
encode(struct()) :: binary()

Encode the struct to a protobuf binary.

Errors may be raised if there's something wrong in the 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.

Link to this callback

new(arg0)
new(Enum.t()) :: struct()

Build and update the struct with passed fields.

Link to this callback

new!(arg0)
new!(Enum.t()) :: struct()

Similar to new/1, but use struct!/2 to build the struct, so errors will be raised if unknown keys are passed.