diff --git a/src/tnetstrings.erl b/src/tnetstrings.erl index 1e2249c..f09fc81 100644 --- a/src/tnetstrings.erl +++ b/src/tnetstrings.erl @@ -24,6 +24,12 @@ encode(Z, Option) -> reverse(L) when is_list(L) -> list_to_binary(lists:reverse(L)); reverse(L) -> L. +encodel({struct, Props}, _Option) when is_list(Props) -> + [$} | with_size(lists:reverse(lists:foldl( + fun({K, V}, Acc) -> + %FIXME assert K is string + [reverse(encodel(V, _Option)), reverse(encodel(K, _Option)) | Acc] + end, [], Props)))]; encodel(B, _Option) when B == true -> <<"4:true!">>; encodel(false, _Option) -> <<"5:false!">>; encodel(null, _Option) -> <<"0:~">>; @@ -36,20 +42,12 @@ encodel(S, _Option) when is_binary(S) -> [$, | with_size(binary_to_list(S))]; encodel(A, _Option) when is_atom(A) -> [$, | with_size(atom_to_list(A))]; -encodel([{_K, _V}| _Remains] = Props, _Option) -> - [$} | with_size(lists:reverse(lists:foldl( - fun({K, V}, Acc) -> - %FIXME assert K is string - [reverse(encodel(V, _Option)), reverse(encodel(K, _Option)) | Acc] - end, [], Props)))]; encodel(L, _Option) when is_list(L) -> LL = lists:foldl( fun(I, Acc) -> [reverse(encodel(I, _Option)) | Acc] end, [], L), - [$\] | with_size(lists:reverse(LL))]; -encodel({struct, Props}, _Option) when is_list(Props) -> - encodel(Props, _Option). + [$\] | with_size(lists:reverse(LL))]. % Decoding diff --git a/test/tnetstrings_tests.erl b/test/tnetstrings_tests.erl index 00aae6e..332704d 100644 --- a/test/tnetstrings_tests.erl +++ b/test/tnetstrings_tests.erl @@ -27,13 +27,14 @@ null_test() -> list_test() -> ?assertEqual(<<"15:1:1#1:a,4:true!]">>, tnetstrings:encode([1, <<"a">>, true])), - ?assertEqual([1, <<"a">>, true], tnetstrings:decode(<<"15:1:1#1:a,4:true!]">>)). + ?assertEqual([1, <<"a">>, true], tnetstrings:decode(<<"15:1:1#1:a,4:true!]">>)), + + ?assertEqual(<<"22:8:1:a,1:b,}8:1:c,1:d,}]">>, tnetstrings:encode([{struct, [{a, <<"b">>}]}, + {struct, [{c, <<"d">>}]}])), + ?assertEqual([{struct, [{<<"a">>, <<"b">>}]}, + {struct, [{<<"c">>, <<"d">>}]}], tnetstrings:decode(<<"22:8:1:a,1:b,}8:1:c,1:d,}]">>)). struct_test() -> - ?assertEqual(<<"27:3:age,2:42#4:name,6:Robert,}">>, tnetstrings:encode([ - {age, 42}, - {name, <<"Robert">>} - ])), ?assertEqual(<<"27:3:age,2:42#4:name,6:Robert,}">>, tnetstrings:encode({struct, [ {age, 42}, {name, <<"Robert">>}