Raxol.Protocols.Serializable protocol (Raxol v2.0.1)

View Source

Protocol for serializing and deserializing data structures.

This protocol provides a unified interface for converting data structures to and from various formats like JSON, TOML, and binary formats.

Examples

defimpl Raxol.Protocols.Serializable, for: MyStruct do
  def serialize(data, :json) do
    data
    |> Map.from_struct()
    |> Jason.encode!()
  end

  def deserialize(data, :json, MyStruct) do
    data
    |> Jason.decode!()
    |> then(&struct(MyStruct, &1))
  end

  def serializable?(data, format) do
    format in [:json, :toml]
  end
end

Summary

Types

t()

All the types that implement this protocol.

Functions

Checks if the data can be serialized to the given format.

Serializes data to the specified format.

Types

format()

@type format() :: :json | :toml | :binary | :erlang_term | atom()

t()

@type t() :: term()

All the types that implement this protocol.

Functions

serializable?(data, format)

@spec serializable?(t(), format()) :: boolean()

Checks if the data can be serialized to the given format.

Returns

true if the data can be serialized to the format, false otherwise.

serialize(data, format \\ :json)

@spec serialize(t(), format()) :: binary() | {:error, term()}

Serializes data to the specified format.

Formats

  • :json - JSON string using Jason
  • :toml - TOML string
  • :binary - Binary format using :erlang.term_to_binary
  • :erlang_term - Erlang external term format

Returns

A string or binary containing the serialized data, or {:error, reason}.