# `Macaw.Live.Stream.Frame`
[🔗](https://github.com/dcoai/macaw_live/blob/v0.1.0/lib/macaw/live/stream/frame.ex#L1)

One binary frame of the stream (spec/05 §9.2): a header naming the cell instance, the
drawing token, the segment key, the frame's sequence and the length of the bytes, then
the segment's raw bytes, never base64.

    <<ilen::8, instance::binary-size(ilen),
      tlen::8, token::binary-size(tlen),
      klen::8, key::binary-size(klen),
      seq::32, length::32,
      bytes::binary-size(length)>>

Every integer is unsigned and big-endian; the instance, the token and the key are UTF-8
strings of 1 to 255 bytes; `seq` counts the instance's frames on its page from 1, so a
later frame of one key replaces an earlier one. The live module reads the same layout
from an `ArrayBuffer` (spec/05 §9.4).

# `t`

```elixir
@type t() :: %{
  instance: String.t(),
  token: String.t(),
  key: String.t(),
  seq: non_neg_integer(),
  bytes: binary()
}
```

A frame read back: what its header names and its bytes.

# `decode`

```elixir
@spec decode(term()) :: {:ok, t()} | {:error, [Macaw.Base.Fault.t(), ...]}
```

A frame read back from its bytes (spec/05 §9.2), as the live module reads it: `{:ok,
frame}`, or `{:error, [{[], reason}]}`, `reason` `{:type, :binary}` for anything but a
binary, `:truncated` for a header or bytes shorter than it says and `:trailing` for
bytes past its length.

    iex> Macaw.Live.Stream.Frame.decode(<<1, "i", 1, "t", 1, "k", 0, 0, 0, 2, 0, 0, 0, 1, 9>>)
    {:ok, %{instance: "i", token: "t", key: "k", seq: 2, bytes: <<9>>}}

# `encode`

```elixir
@spec encode(String.t(), String.t(), String.t(), non_neg_integer(), iodata()) ::
  {:ok, iodata()} | {:error, [Macaw.Base.Fault.t(), ...]}
```

The frame of one segment as iodata, its header first and the segment's bytes after it
unchanged (spec/05 §9.2): `{:ok, iodata}`, or `{:error, faults}`: `{[field], {:type,
:string}}` for an instance, token or key that is no non-empty string,
`{[field], {:too_long, 255}}` for one over 255 bytes, `{[:seq], {:type, :u32}}` for a
sequence that is no integer from 0 to 4,294,967,295 and `{[:bytes], {:type, :iodata}}`
for bytes that are no iodata or longer than that.

    iex> {:ok, frame} = Macaw.Live.Stream.Frame.encode("s-grid", "7", "c0", 1, <<1, 2, 3>>)
    iex> IO.iodata_to_binary(frame)
    <<6, "s-grid", 1, "7", 2, "c0", 0, 0, 0, 1, 0, 0, 0, 3, 1, 2, 3>>

---

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