Skip to content

Commit c0587bb

Browse files
author
Garrett Smith
committed
Utility module (used in examples)
1 parent cdf4408 commit c0587bb

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed

src/erlzmq_util.erl

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
-module(erlzmq_util).
2+
3+
-export([dump/1]).
4+
5+
%%--------------------------------------------------------------------
6+
%% @doc Reads available messages from Socket, printing them to stdout.
7+
%% @spec dump(Socket) -> any()
8+
%% Socket = erlzmq_socket()
9+
%% @end
10+
%%--------------------------------------------------------------------
11+
12+
dump(Socket) ->
13+
{ok, Msg} = erlzmq:recv(Socket),
14+
io:format("----------------------------------------~n"),
15+
dump_msg(Msg, Socket).
16+
17+
%%--------------------------------------------------------------------
18+
%% @doc Print a socket message, including subsequent parts.
19+
%% @spec dump_msg(Msg, Socket) -> ok
20+
%% @end
21+
%%--------------------------------------------------------------------
22+
23+
dump_msg(Msg, Socket) ->
24+
io:format("[~3..0B] ", [size(Msg)]),
25+
Str = binary_to_list(Msg),
26+
case io_lib:printable_list(Str) of
27+
true -> io:format(Str);
28+
false -> io:format(bin_to_hex(Msg))
29+
end,
30+
io:format("~n"),
31+
case erlzmq:getsockopt(Socket, rcvmore) of
32+
{ok, true} ->
33+
{ok, Next} = erlzmq:recv(Socket),
34+
dump_msg(Next, Socket);
35+
{ok, false} ->
36+
ok
37+
end.
38+
39+
%%--------------------------------------------------------------------
40+
%% @doc Convert a binary to a hex string.
41+
%% @spec bin_to_hex(binary()) -> list()
42+
%% @end
43+
%%--------------------------------------------------------------------
44+
45+
bin_to_hex(B) when is_binary(B) ->
46+
lists:flatten(lists:map(fun int_to_hex/1, binary_to_list(B))).
47+
48+
%%--------------------------------------------------------------------
49+
%% @doc Convert an int to a two char hex string.
50+
%% @spec int_to_hex(integer()) -> string()
51+
%% @end
52+
%%--------------------------------------------------------------------
53+
54+
int_to_hex(N) when N < 256 ->
55+
[hex(N div 16), hex(N rem 16)].
56+
57+
%%--------------------------------------------------------------------
58+
%% @doc Converts an integer to a hex char.
59+
%% @spec hex(integer()) -> char()
60+
%% @end
61+
%%--------------------------------------------------------------------
62+
63+
hex(N) when N < 10 -> $0 + N;
64+
hex(N) when N >= 10, N < 16 -> $a + (N - 10).

0 commit comments

Comments
 (0)