# `ToonEx.Btoon.Encode`
[🔗](https://github.com/ohhi-vn/toon_ex/blob/v1.6.0/lib/toon_ex/btoon/encode/encode.ex#L1)

BTOON encoder.

Encodes the BTOON data model (`ToonEx.Btoon.Types.encodable/0`) into the binary
wire format defined by the BTOON specification:

  * Envelope: `"BTON"` magic, version, flags, reserved, optional string
    table, optional embedded schema, then an 8-byte-aligned body.
  * Value tags (`Btoon.Constants`) with inline `SmallInt` for integers in
    `-32..95` and fixed-width little-endian integers/floats otherwise.
  * Strings deduplicated against a session dictionary and a per-message
    string table via `StringRef`.
  * Homogeneous numeric lists encoded as `TypedArray` and homogeneous
    object lists as columnar `ObjectTable`, both with alignment padding
    for zero-copy decoders.
  * Optional schema mode emitting `SchemaID` + tagless fixed-width values.

## Determinism

Every input maps to exactly one byte sequence: map keys are sorted, strings
are added to the per-message table in first-encounter order, and numeric
lists use `Btoon.ElementType.detect_type/1` to pick a single legal type.

## API

    iex> Btoon.Encode.encode!(%{"name" => "Alice", "age" => 30})
    <<66, 84, 79, 78, 1, 4, 0, 0, 3, 0, 0, 0, 3, 0, 0, 0, 97, 103, 101, 4, 0,
      0, 0, 110, 97, 109, 101, 5, 0, 0, 0, 65, 108, 105, 99, 101, 0, 0, 0, 0, 10,
      2, 0, 0, 0, 11, 64, 94, 11, 65, 11, 66>>

# `encode`

```elixir
@spec encode(
  ToonEx.Btoon.Types.encodable(),
  keyword()
) :: {:ok, binary()} | {:error, ToonEx.Btoon.EncodeError.t()}
```

Encodes data to the BTOON binary format.

Returns `{:ok, binary}` or `{:error, Btoon.EncodeError.t()}`.

# `encode!`

```elixir
@spec encode!(
  ToonEx.Btoon.Types.encodable(),
  keyword()
) :: binary()
```

Encodes data to the BTOON binary format, raising on error.

# `encode_to_iodata!`

```elixir
@spec encode_to_iodata!(
  ToonEx.Btoon.Types.encodable(),
  keyword()
) :: iodata()
```

Encodes data to BTOON iodata without flattening to a single binary.

# `encode_validated`

```elixir
@spec encode_validated(
  ToonEx.Btoon.Types.encodable(),
  ToonEx.Btoon.Encode.Options.validated()
) :: {:ok, binary()} | {:error, ToonEx.Btoon.EncodeError.t()}
```

Encodes data to the BTOON binary format using pre-validated options.

Returns `{:ok, binary}` or `{:error, Btoon.EncodeError.t()}`.

This avoids re-validating options on each call, improving performance for
repeated encoding with the same options.

# `encode_validated!`

```elixir
@spec encode_validated!(
  ToonEx.Btoon.Types.encodable(),
  ToonEx.Btoon.Encode.Options.validated()
) :: binary()
```

Encodes data to the BTOON binary format using pre-validated options, raising on error.

This avoids re-validating options on each call, improving performance for
repeated encoding with the same options.

---

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