summaryrefslogtreecommitdiff
path: root/bencode.erl
diff options
context:
space:
mode:
authorssmith2006-05-14 20:56:49 -0700
committerssmith2006-05-14 20:56:49 -0700
commit00622aaa2f0844920db2e34b08c96517dbdce41d (patch)
treedd7da8cd8fb2993baccac522595d836638f3c3f3 /bencode.erl
parentc4f4a55b60ccc5715437e8b3912efa780c765313 (diff)
Add dict encoder and basic test.
Diffstat (limited to 'bencode.erl')
-rw-r--r--bencode.erl20
1 files changed, 19 insertions, 1 deletions
diff --git a/bencode.erl b/bencode.erl
index a335ab9..96eb33f 100644
--- a/bencode.erl
+++ b/bencode.erl
@@ -7,6 +7,14 @@
%% %% %% %% %% %% %% %% Decoding %% %% %% %% %% %% %% %%
+keyenc(Key) when is_list(Key) ->
+ bencode({string, Key});
+keyenc(Key) when is_atom(Key) ->
+ bencode({string, atom_to_list(Key)});
+keyenc({string, _} = Key) ->
+ bencode(Key).
+
+
bencode({int, Val}) ->
"i" ++ integer_to_list(Val) ++ "e";
@@ -15,7 +23,17 @@ bencode({string, Val}) ->
bencode({list, Val}) ->
Fun = fun(A) -> bencode(A) end,
- "l" ++ lists:flatten(lists:map(Fun, Val)) ++ "e".
+ "l" ++ lists:flatten(lists:map(Fun, Val)) ++ "e";
+
+bencode({dict, Dict}) ->
+ SFun = fun({Key1, _}, {Key2, _}) ->
+ Key1 < Key2
+ end,
+ List = lists:sort(SFun, dict:to_list(Dict)),
+ MFun = fun({Key, Val}) ->
+ keyenc(Key) ++ bencode(Val)
+ end,
+ "d" ++ lists:flatten(lists:map(MFun, List)) ++ "e".
%% %% %% %% %% %% %% %% Decoding %% %% %% %% %% %% %% %%