View Source Bento.Encoder protocol (bento v1.0.0)

Protocol and implementations to encode Elixir data structures into their Bencoded forms.

examples

Examples

iex> Bento.Encoder.encode("foo") |> IO.iodata_to_binary()
"3:foo"

iex> Bento.Encoder.encode([1, "two", [3]]) |> IO.iodata_to_binary()
"li1e3:twoli4eee"

types-what-available-or-unavailable

Types what available or unavailable

Available types: Atom, BitString, Integer, List, Map, Range, Stream and Struct (as a Map).

Unavailable types: Float, Function, PID, Port and Reference.

You can, and we recommend, implement Bento.Encoder for a specific Struct according to your needs.

The Unavailable types will raise an Bento.EncodeError when you try to encode them. However, implementing Bento.Encoder for an unavailable type is also available, but it is not recommended.

implement-for-custom-structs

Implement for Custom Structs

For the sake of security and logical integrity, we already implement the Bento.Encoder any types (but some not supported type will raise an error), and of course, including Struct.

However, if you want to implement the Bento.Encoder for a specific Struct instead of using the default implementation (convert to Map by Map.from_struct/1), you can do it like this:

defimpl Bento.Encoder, for: MyStruct do
  def encode(struct) do
    # do something
  end
end

Here we have a specific example about a Struct that "always be true":

defmodule Truly do
  defstruct be: true

  defimpl Bento.Encoder do
    def encode(_), do: "4:true"
  end
end

iex> %Truly{be: false} |> Bento.Encoder.encode() |> IO.iodata_to_binary()
"4:true"

Link to this section Summary

Functions

Encode an Elixir value into its Bencoded form.

Link to this section Types

@type bencodable() :: atom() | Bento.Parser.t() | Enumerable.t()
@type encode_err() :: {:invalid, term()}
@type t() :: iodata()

Link to this section Functions

@spec encode(bencodable()) :: t() | no_return()

Encode an Elixir value into its Bencoded form.