Repository navigation
Struct example
Juan Hurtado edited this page May 16, 2020
·
1 revision
defmodule Book do
@behaviour XDR.Declaration
defstruct file_name: XDR.String, file_size: XDR.Int
@type t :: %Book{file_name: XDR.String.t(), file_size: XDR.Int.t()}
def new(file_name, file_size) do
%Book{file_name: file_name, file_size: file_size}
end
@impl XDR.Declaration
def encode_xdr(struct_file) do
component_keyword = struct_file |> Map.from_struct() |> Map.to_list()
XDR.Struct.new(component_keyword)
|> XDR.Struct.encode_xdr()
end
@impl XDR.Declaration
def encode_xdr!(struct_file) do
encode_xdr(struct_file) |> elem(1)
end
@impl XDR.Declaration
def decode_xdr(bytes, opts \\ nil)
def decode_xdr(bytes, _opts) do
component_keyword = Book.__struct__() |> Map.from_struct() |> Map.to_list()
XDR.Struct.decode_xdr!(bytes, %{components: component_keyword})
|> perform_struct()
end
@impl XDR.Declaration
@spec decode_xdr!(bytes :: binary, struct :: map()) :: {t(), binary()}
def decode_xdr!(bytes, struct), do: decode_xdr(bytes, struct) |> elem(1)
defp perform_struct({components, rest}) do
struct_components = components.components
struct = Book.new(struct_components[:file_name], struct_components[:file_size])
{:ok, {struct, rest}}
end
end