Small Erlang bencode library

Steve Smith ssmith@REDACTED
Thu May 18 02:00:29 CEST 2006


On Wed, 2006-05-17 at 09:58 +0200, Christian S wrote:
> This is how i would build the encoder. Mainly so that I dont have to
> include the type tagging
> pairs when the erlang terms already have types of their own.
> 
> bencode(List) when is_list(List) ->
>         [$l, [bencode(Item) || Item <- List], $e]; 
> bencode(Int) when is_integer(Int) ->
>         [$i, integer_to_list(Int), $e];
> bencode(Bin) when is_binary(Bin) ->
>         [integer_to_list(size(Bin)), $:, Bin];
> bencode(Dict) when element(1, Dict) == dict -> 
>         Sorter = fun({Key1, _}, {Key2, _}) -> Key1 < Key2 end,
>         Pairs = [[bencode(Key), bencode(Value)] || {Key, Value} <-
> lists:sort(Sorter, dict:to_list(Dict))],
>         [$d, Pairs, $e].

> 
> Dict = dict:store(<<"foo">>, 3, dict:new()).
> Terms = [1,2, <<"How's this?">>, Dict].
> 
> Encoded = bencode:bencode(Terms).
> 
> If you want this as a string you can do
> "binary_to_list(list_to_binary(Encoded))." and get 
> "li1ei2e11:How's this?d3:fooi3eee"
> 
> But the value of Encoded itself is useable, it is known as the type
> iolist(), sometimes 
> even string() in documentation. 
> You can send iolist() over sockets so pre-flattening them is not
> necessary. 
> 
> It appears that dict keys must be strings, the encoder should probably
> crash if a key
> is not. In all my whole dict encoding part suffer some code smell.
> Maybe someone
> else has a better alternative?
> 
> On 5/17/06, Steve Smith <ssmith@REDACTED> wrote:
>         Hi,
>         
>         As a preliminary exercise in learning Erlang I've implemented
>         a basic
>         bencoding library (bencoding being the serialisation system
>         used in the
>         bittorrent protocol).  The darcs repository is available
>         here: 
>         
>             http://people.vislab.usyd.edu.au/~ssmith/erlang/bencode
>         
>         As this is my first go at declarative programming comments and
>         corrections are welcome. 
>         
>         Cheers,
>         Steve
>         
> 




More information about the erlang-questions mailing list