This is how i would build the encoder. Mainly so that I dont have to include the type tagging<br>pairs when the erlang terms already have types of their own.<br><br>bencode(List) when is_list(List) -><br> [$l, [bencode(Item) || Item <- List], $e];
<br>bencode(Int) when is_integer(Int) -><br> [$i, integer_to_list(Int), $e];<br>bencode(Bin) when is_binary(Bin) -><br> [integer_to_list(size(Bin)), $:, Bin];<br>bencode(Dict) when element(1, Dict) == dict ->
<br> Sorter = fun({Key1, _}, {Key2, _}) -> Key1 < Key2 end,<br> Pairs = [[bencode(Key), bencode(Value)] || {Key, Value} <- lists:sort(Sorter, dict:to_list(Dict))],<br> [$d, Pairs, $e].<br><br>
<br>Dict = dict:store(<<"foo">>, 3, dict:new()).<br>Terms = [1,2, <<"How's this?">>, Dict].<br><br>Encoded = bencode:bencode(Terms).<br><br>If you want this as a string you can do "binary_to_list(list_to_binary(Encoded))." and get
<br>"li1ei2e11:How's this?d3:fooi3eee"<br><br>But the value of Encoded itself is useable, it is known as the type iolist(), sometimes <br>even string() in documentation. <br>You can send iolist() over sockets so pre-flattening them is not necessary.
<br><br>It appears that dict keys must be strings, the encoder should probably crash if a key<br>is not. In all my whole dict encoding part suffer some code smell. Maybe someone<br>else has a better alternative?<br><br><div>
<span class="gmail_quote">On 5/17/06, <b class="gmail_sendername">Steve Smith</b> <<a href="mailto:ssmith@vislab.usyd.edu.au">ssmith@vislab.usyd.edu.au</a>> wrote:</span><blockquote class="gmail_quote" style="border-left: 1px solid rgb(204, 204, 204); margin: 0pt 0pt 0pt 0.8ex; padding-left: 1ex;">
Hi,<br><br>As a preliminary exercise in learning Erlang I've implemented a basic<br>bencoding library (bencoding being the serialisation system used in the<br>bittorrent protocol). The darcs repository is available here:
<br><br> <a href="http://people.vislab.usyd.edu.au/~ssmith/erlang/bencode">http://people.vislab.usyd.edu.au/~ssmith/erlang/bencode</a><br><br>As this is my first go at declarative programming comments and<br>corrections are welcome.
<br><br>Cheers,<br>Steve<br><br></blockquote></div><br>