ExBencode (ex_bencode v2.0.2) View Source
Documentation for ExBencode.
Link to this section Summary
Link to this section Functions
Decode the bencoded binary value.
Examples
Decoding integers
iex> ExBencode.decode("i10e")
{:ok, 10}
iex> ExBencode.decode("i-10e")
{:ok, -10}
Doubles and scientific notation is not supported
iex> ExBencode.decode("i4.2e")
{:error, :invalid_integer}
iex> ExBencode.decode("i1.5e7e")
{:error, :invalid_integer}
Decoding strings
iex> ExBencode.decode("4:spam")
{:ok, "spam"}
iex> ExBencode.decode("4:too much spam")
{:error, :unexpected_content, %{index: 6, unexpected: "much spam"}}
Bytes are handled using the string type, with the preceding number representing the byte size, not the string length.
iex> ExBencode.decode(<<?3, ?:, 1, 2, 3>>)
{:ok, <<1, 2, 3>>}
iex> ExBencode.decode("7:hełło")
{:ok, "hełło"}
iex> ExBencode.decode("5:hełło")
{:error, :unexpected_content, %{index: 7, unexpected: <<130, 111>>}}
Decoding lists
iex> ExBencode.decode("le")
{:ok, []}
iex> ExBencode.decode("l4:spam4:eggse")
{:ok, ["spam", "eggs"]}
Decoding Dictionaries
iex> ExBencode.decode("de")
{:ok, %{}}
iex> ExBencode.decode("d3:cow3:mooe")
{:ok, %{"cow" => "moo"}}
iex> ExBencode.decode("d8:shoppingl4:eggs4:milkee")
{:ok, %{"shopping" => ["eggs", "milk"]}}
Encode an erlang term.
Examples
iex> ExBencode.encode(1)
{:ok, "i1e"}
iex> ExBencode.encode("hi!")
{:ok, "3:hi!"}
iex> ExBencode.encode([])
{:ok, "le"}
iex> ExBencode.encode([1])
{:ok, "li1ee"}
iex> ExBencode.encode(%{})
{:ok, "de"}
iex> ExBencode.encode(%{"cow" => "moo"})
{:ok, "d3:cow3:mooe"}
Note that a keyword list counts as a list of lists, so convert keyword lists to maps before encoding. Otherwise, an empty keyword list could either be encoded as an empty list or an empty dict, and the library avoids making that kind of arbitrary decision.
iex> ExBencode.encode([cow: "moo"])
{:ok, "ll3:cow3:mooee"}
Use Enum.into/2
to convert a keyword list into a map
iex> Enum.into [cow: "moo"], %{}
%{cow: "moo"}
iex> ExBencode.encode(%{cow: "moo"})
{:ok, "d3:cow3:mooe"}