ex_wire v0.1.1 ExWire.Message behaviour

Defines a behavior for messages so that they can be easily encoded and decoded.

Link to this section Summary

Functions

Decodes a message of given type based on the encoded data. Effectively reverses the decode/1 function

Encoded a message by concatting its message_id to the encoded data of the message itself

Link to this section Types

Link to this type message_id()
message_id() :: integer
Link to this type t()
t() :: module

Link to this section Functions

Link to this function decode(type, data)
decode(integer, binary) :: t

Decodes a message of given type based on the encoded data. Effectively reverses the decode/1 function.

Examples

iex> ExWire.Message.decode(0x01, <<210, 1, 199, 132, 1, 2, 3, 4, 128, 5, 199, 132, 5, 6, 7, 8, 6, 128, 4>>)
%ExWire.Message.Ping{
  version: 1,
  from: %ExWire.Struct.Endpoint{ip: [1, 2, 3, 4], tcp_port: 5, udp_port: nil},
  to: %ExWire.Struct.Endpoint{ip: [5, 6, 7, 8], tcp_port: nil, udp_port: 6},
  timestamp: 4
}

iex> ExWire.Message.decode(0x02, <<202, 199, 132, 5, 6, 7, 8, 6, 128, 2, 3>>)
%ExWire.Message.Pong{
to: %ExWire.Struct.Endpoint{ip: [5, 6, 7, 8], tcp_port: nil, udp_port: 6}, hash: <<2>>, timestamp: 3
}

iex> ExWire.Message.decode(0x99, <<>>)
** (ExWire.Message.UnknownMessageError) Unknown message type: 0x99
Link to this function encode(message)
encode(t) :: binary

Encoded a message by concatting its message_id to the encoded data of the message itself.

Examples

iex> ExWire.Message.encode(
...>   %ExWire.Message.Ping{
...>     version: 1,
...>     from: %ExWire.Struct.Endpoint{ip: [1, 2, 3, 4], tcp_port: 5, udp_port: nil},
...>     to: %ExWire.Struct.Endpoint{ip: [5, 6, 7, 8], tcp_port: nil, udp_port: 6},
...>     timestamp: 4
...>   }
...> )
<<1, 214, 1, 201, 132, 1, 2, 3, 4, 128, 130, 0, 5, 201, 132, 5, 6, 7, 8, 130, 0, 6, 128, 4>>

iex> ExWire.Message.encode(%ExWire.Message.Pong{to: %ExWire.Struct.Endpoint{ip: [5, 6, 7, 8], tcp_port: nil, udp_port: 6}, hash: <<2>>, timestamp: 3})
<<2, 204, 201, 132, 5, 6, 7, 8, 130, 0, 6, 128, 2, 3>>

Link to this section Callbacks

Link to this callback encode(t)
encode(t) :: binary
Link to this callback message_id()
message_id() :: message_id
Link to this callback to(t)
to(t) :: ExWire.Endpoint.t | nil