Skip to content

Commit

Permalink
encoding command from dedicated maps
Browse files Browse the repository at this point in the history
  • Loading branch information
Dreat committed Apr 23, 2017
1 parent 1d64594 commit 41929f3
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 1 deletion.
9 changes: 8 additions & 1 deletion zmq_ex/lib/zmq_ex.ex
@@ -1,5 +1,4 @@
defmodule ZmqEx do defmodule ZmqEx do
use Bitwise


def encode(%{flags: flags = %{type: _, long: :short, more: _}, size: size, body: <<body>>}) do def encode(%{flags: flags = %{type: _, long: :short, more: _}, size: size, body: <<body>>}) do
<<encode_flags(flags), size :: size(8), body>> <<encode_flags(flags), size :: size(8), body>>
Expand All @@ -14,6 +13,14 @@ defmodule ZmqEx do
|> decode(rest) |> decode(rest)
end 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
end

defp decode(flags = %{type: _, long: :short, more: _}, <<size :: size(8), body :: binary>>) do defp decode(flags = %{type: _, long: :short, more: _}, <<size :: size(8), body :: binary>>) do
%{flags: flags, size: size, body: body} %{flags: flags, size: size, body: body}
end end
Expand Down
10 changes: 10 additions & 0 deletions zmq_ex/test/zmq_ex_test.exs
Expand Up @@ -42,4 +42,14 @@ defmodule ZmqExTest do
result = ZmqEx.encode(%{flags: %{type: :command, long: :short, more: false}, size: 1, body: <<3>>}) result = ZmqEx.encode(%{flags: %{type: :command, long: :short, more: false}, size: 1, body: <<3>>})
assert result == (<<4, 1, 3>>) assert result == (<<4, 1, 3>>)
end end

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

test "encode long command" 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
end end

0 comments on commit 41929f3

Please sign in to comment.