Grove.Storage.Serializer (Grove v0.1.1)

View Source

Handles serialization and deserialization of CRDT states.

Uses Erlang's term_to_binary/2 with compression for efficient storage while preserving exact Elixir types (structs, MapSets, atoms).

Safety

Deserialization uses the :safe option to prevent atom table exhaustion attacks when loading untrusted data.

Compression

By default, compression is enabled using zlib (level 6). For small CRDTs (<1KB), the overhead may not be worth it. For large CRDTs (>10KB), compression typically saves 50-80%.

Summary

Functions

Deserializes a CRDT state from binary format.

Deserializes a CRDT state, raising on error.

Serializes a CRDT state to binary format.

Returns the size in bytes of the serialized CRDT.

Functions

decode(binary)

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

Deserializes a CRDT state from binary format.

Returns {:ok, crdt_state} on success, {:error, reason} on failure.

Safety

Uses :safe option to prevent atom creation from untrusted input.

Examples

iex> counter = Grove.Counter.GCounter.new(:a)
iex> binary = Grove.Storage.Serializer.encode(counter)
iex> {:ok, decoded} = Grove.Storage.Serializer.decode(binary)
iex> decoded == counter
true

decode!(binary)

@spec decode!(binary()) :: term()

Deserializes a CRDT state, raising on error.

Examples

iex> counter = Grove.Counter.GCounter.new(:a)
iex> binary = Grove.Storage.Serializer.encode(counter)
iex> decoded = Grove.Storage.Serializer.decode!(binary)
iex> decoded == counter
true

encode(crdt_state, opts \\ [])

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

Serializes a CRDT state to binary format.

Options

  • :compressed - Use zlib compression (default: true)

Examples

iex> counter = Grove.Counter.GCounter.new(:a) |> Grove.Counter.GCounter.increment(5)
iex> binary = Grove.Storage.Serializer.encode(counter)
iex> is_binary(binary)
true

encoded_size(crdt_state, opts \\ [])

@spec encoded_size(
  term(),
  keyword()
) :: non_neg_integer()

Returns the size in bytes of the serialized CRDT.

Useful for monitoring storage growth and debugging.

Examples

iex> counter = Grove.Counter.GCounter.new(:a)
iex> Grove.Storage.Serializer.encoded_size(counter) > 0
true