From 41929f3570c3c4450d5ffef3a5d824d103b8f606 Mon Sep 17 00:00:00 2001 From: dreat Date: Sun, 23 Apr 2017 22:27:06 +0200 Subject: [PATCH] encoding command from dedicated maps --- zmq_ex/lib/zmq_ex.ex | 9 ++++++++- zmq_ex/test/zmq_ex_test.exs | 10 ++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/zmq_ex/lib/zmq_ex.ex b/zmq_ex/lib/zmq_ex.ex index d2ec243..0cc8496 100644 --- a/zmq_ex/lib/zmq_ex.ex +++ b/zmq_ex/lib/zmq_ex.ex @@ -1,5 +1,4 @@ defmodule ZmqEx do - use Bitwise def encode(%{flags: flags = %{type: _, long: :short, more: _}, size: size, body: <>}) do <> @@ -14,6 +13,14 @@ defmodule ZmqEx do |> decode(rest) end + def encode_command(%{name: name, size: size, data: <>}) 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: _}, <>) do %{flags: flags, size: size, body: body} end diff --git a/zmq_ex/test/zmq_ex_test.exs b/zmq_ex/test/zmq_ex_test.exs index d38b50d..1ea3250 100644 --- a/zmq_ex/test/zmq_ex_test.exs +++ b/zmq_ex/test/zmq_ex_test.exs @@ -42,4 +42,14 @@ defmodule ZmqExTest do result = ZmqEx.encode(%{flags: %{type: :command, long: :short, more: false}, size: 1, body: <<3>>}) assert result == (<<4, 1, 3>>) 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 \ No newline at end of file