# `ToonEx.Encoder`
[🔗](https://github.com/ohhi-vn/toon_ex/blob/v1.1.0/lib/toon_ex/encoder.ex#L1)

Protocol for encoding custom data structures to TOON format.

This protocol allows you to define how your custom structs should be
encoded to TOON format, similar to `Jason.Encoder`.

## 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`).

## Example

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

Or implement the protocol manually:

    defimpl ToonEx.Encoder, for: User do
      def encode(user, opts) do
        %{
          "name" => user.name,
          "email" => user.email
        }
        |> ToonEx.Encode.encode!(opts)
      end
    end

# `t`

```elixir
@type t() :: term()
```

All the types that implement this protocol.

# `encode`

```elixir
@spec encode(
  t(),
  keyword()
) :: iodata() | map()
```

Encodes the given value to TOON format.

Returns IO data that can be converted to a string.

---

*Consult [api-reference.md](api-reference.md) for complete listing*
