Formata.Codec behaviour (formata v0.1.0)

Copy Markdown View Source

Behaviour for format adapters and the portable value domain they share.

Built-in codecs:

FormatModuleDecoderEncoder
:jsonFormata.Codec.JSONFormata.JasonFormata.Jason
:tomlFormata.Codec.TOMLFormata.Toml (gsmlg_toml)Formata.Codec.TOML.Encoder
:yamlFormata.Codec.YAMLFormata.YamlElixirFormata.Ymlr

A custom codec is any module implementing this behaviour; pass the module wherever a format atom is accepted.

Portable value domain

Decoders return ordinary Elixir terms:

ValueElixir representation
nullnil
booleantrue / false
integerinteger
floatfloat
+infinity / -infinity / NaN:infinity / :negative_infinity / :nan
stringUTF-8 binary
array / sequencelist
object / table / mappingmap with string keys
local date / local timeDate / Time
local date-timeNaiveDateTime
offset date-timeDateTime

Keys from documents stay strings; Formata never creates atoms from document content. A field that is absent is absent from the map; an explicit null is present with the value nil.

Each encoder accepts only the subset its format can represent and rejects everything else with an :encode error (:unrepresentable, :invalid_key, :invalid_root, :out_of_range). Nothing is dropped, stringified, or rounded implicitly; use Formata.Transform for explicit conversions.

Summary

Callbacks

Decodes a complete document.

Encodes a term as a complete document.

Returns the format name used in errors.

Functions

Resolves a format atom or codec module to a codec module.

The built-in format names.

Types

format()

@type format() :: :json | :toml | :yaml | module()

result(t)

@type result(t) :: {:ok, t} | {:error, [Formata.Error.t(), ...]}

Callbacks

decode(input, opts)

@callback decode(input :: binary(), opts :: keyword()) :: result(term())

Decodes a complete document.

encode(data, opts)

@callback encode(data :: term(), opts :: keyword()) :: result(binary())

Encodes a term as a complete document.

format()

@callback format() :: atom()

Returns the format name used in errors.

Functions

fetch(format)

@spec fetch(format()) :: {:ok, module()} | {:error, [Formata.Error.t(), ...]}

Resolves a format atom or codec module to a codec module.

iex> Formata.Codec.fetch(:json)
{:ok, Formata.Codec.JSON}

iex> {:error, [%Formata.Error{kind: :unsupported, code: :unknown_format}]} = Formata.Codec.fetch(:xml)

formats()

@spec formats() :: [atom()]

The built-in format names.