Spectre.Canonical.Value (Spectre v0.3.0)

Copy Markdown View Source

Portable, deterministic value codec used by content-addressed Spectre data.

The format is independent from Erlang external-term encoding. Every value carries an explicit tag, map entries are ordered by the canonical bytes of their keys, and atoms are restored with String.to_existing_atom/1 only. Structs are rejected unless the caller supplies an explicit :allowed_structs list.

PIDs, ports, references, functions, improper lists, non-byte-aligned bitstrings, and non-finite floats are never encodable.

Summary

Functions

Decodes a canonical value without creating atoms.

Returns the lowercase SHA-256 digest of a canonical value.

Returns the digest or raises ArgumentError for a non-canonical value.

Returns the digest algorithm used by digest/2.

Encodes a value into the versioned canonical binary format.

Encodes a value or raises ArgumentError with the stable failure reason.

Checks whether a value can be represented by this codec.

Returns the canonicalization format version.

Types

reason()

@type reason() :: term()

Functions

decode(encoded, opts \\ [])

@spec decode(
  binary(),
  keyword()
) :: {:ok, term()} | {:error, reason()}

Decodes a canonical value without creating atoms.

The decoder rejects trailing data, non-canonical map order, unknown tags, unknown atoms, and structs outside the explicit :allowed_structs list.

digest(value, opts \\ [])

@spec digest(
  term(),
  keyword()
) :: {:ok, String.t()} | {:error, reason()}

Returns the lowercase SHA-256 digest of a canonical value.

digest!(value, opts \\ [])

@spec digest!(
  term(),
  keyword()
) :: String.t()

Returns the digest or raises ArgumentError for a non-canonical value.

digest_algorithm()

@spec digest_algorithm() :: :sha256

Returns the digest algorithm used by digest/2.

encode(value, opts \\ [])

@spec encode(
  term(),
  keyword()
) :: {:ok, binary()} | {:error, reason()}

Encodes a value into the versioned canonical binary format.

Options:

  • :allowed_structs - modules whose structs may be encoded and decoded;
  • :max_bytes - maximum encoded size, including the format header;
  • :max_depth - maximum nesting depth;
  • :max_collection_size - maximum entries in one collection.

encode!(value, opts \\ [])

@spec encode!(
  term(),
  keyword()
) :: binary()

Encodes a value or raises ArgumentError with the stable failure reason.

validate(value, opts \\ [])

@spec validate(
  term(),
  keyword()
) :: :ok | {:error, reason()}

Checks whether a value can be represented by this codec.

version()

@spec version() :: pos_integer()

Returns the canonicalization format version.