ToonEx.Btoon.Encoder protocol (toon_ex v1.3.1)

Copy Markdown View Source

Protocol for encoding custom data structures to BTOON format.

This protocol allows you to define how your custom structs should be encoded to BTOON binary format, similar to ToonEx.Encoder for TOON text and Jason.Encoder for JSON.

Deriving

The protocol leverages Elixir's @derive feature. Accepted options are:

  • :only - encodes only values of specified keys.
  • :except - encodes all struct fields except specified keys.

By default all keys except the :__struct__ key are encoded.

The generated implementation pre-computes key encoding at compile time for maximum runtime efficiency (inspired by Jason.Encoder). The encoded struct becomes a BTOON object with the resulting fields, which the encoder recursively encodes using the normal BTOON dispatch (keys are sorted, etc.).

Example

defmodule User do
  @derive {ToonEx.Btoon.Encoder, only: [:name, :email]}
  defstruct [:id, :name, :email, :password_hash]
end

iex> bin = Btoon.encode!(%User{id: 1, name: "Alice", email: "a@example.com"})
iex> Btoon.decode!(bin)
%{"name" => "Alice", "email" => "a@example.com"}

Or implement the protocol manually:

defimpl ToonEx.Btoon.Encoder, for: User do
  def encode(user, _opts) do
    %{
      "name" => user.name,
      "email" => user.email
    }
  end
end

Summary

Types

t()

All the types that implement this protocol.

Functions

Encodes the given value to a BTOON-encodable form.

Types

t()

@type t() :: term()

All the types that implement this protocol.

Functions

encode(value, opts)

@spec encode(
  t(),
  keyword()
) :: term()

Encodes the given value to a BTOON-encodable form.

Returns a map (or otherwise encodable term) that is then encoded to the BTOON binary format by the encoder.