Skip to content
Permalink
Browse files
added decoding command to something more structured
  • Loading branch information
Dreat committed Apr 30, 2017
1 parent 41929f3 commit e75c850094b394d51e60dd1712befa70e10d357f
Showing with 26 additions and 7 deletions.
  1. +16 −6 zmq_ex/lib/zmq_ex.ex
  2. +10 −1 zmq_ex/test/zmq_ex_test.exs
@@ -13,12 +13,22 @@ defmodule ZmqEx do
|> decode(rest)
end

def encode_command(%{name: name, size: size, data: <<data :: binary>>}) do
case size do
0 -> %{flags: %{type: :command, long: :short, more: false}, size: 8, body: name }
56 -> %{flags: %{type: :command, long: :long, more: false}, size: 64, body: name <> data}
_ -> {:error}
end
def encode_command(%{name: name, size: 0, data: <<_data :: binary>>}) do
%{flags: %{type: :command, long: :short, more: false}, size: 8, body: name }
end

def encode_command(%{name: name, size: 56, data: <<data :: binary>>}) do
%{flags: %{type: :command, long: :long, more: false}, size: 64, body: name <> data}
end

def decode_command(%{flags: %{type: :command, long: :short, more: false}, size: _size, body: body}) do
<<name::binary-size(8), command_body :: binary>> = body
%{name: name, size: 0, data: command_body}
end

def decode_command(%{flags: %{type: :command, long: _, more: false}, size: _size, body: body}) do
<<name::binary-size(8), command_body :: binary>> = body
%{name: name, size: 56, data: command_body}
end

defp decode(flags = %{type: _, long: :short, more: _}, <<size :: size(8), body :: binary>>) do
@@ -1,6 +1,5 @@
defmodule ZmqExTest do
use ExUnit.Case
import ZmqEx
doctest ZmqEx

test "decode basic message frame" do
@@ -52,4 +51,14 @@ defmodule ZmqExTest do
result = ZmqEx.encode_command(%{name: "command2", size: 56, data: "A command body"})
assert result == %{flags: %{type: :command, long: :long, more: false}, size: 64, body: <<"command2A command body">>}
end

test "decode short command" do
result = ZmqEx.decode_command(%{flags: %{type: :command, long: :short, more: false}, size: 8, body: "command1"})
assert result == %{name: "command1", size: 0, data: ""}
end

test "decode long command" do
result = ZmqEx.decode_command(%{flags: %{type: :command, long: :long, more: false}, size: 64, body: "command2A command body"})
assert result == %{name: "command2", size: 56, data: "A command body"}
end
end

0 comments on commit e75c850

Please sign in to comment.