ExCodecs.Codec behaviour (ex_codecs v0.1.0)

Copy Markdown View Source

Behaviour definition for ExCodecs codecs.

Every codec implementation must conform to this behaviour, providing encode/2 and decode/2 callbacks that operate on binaries with optional keyword-list configuration.

Implementing a Codec

 defmodule ExCodecs.Compression.Zstd do
   @behaviour ExCodecs.Codec

   @impl true
   def encode(data, opts) do
     level = Keyword.get(opts, :level, 3)
     with :ok <- validate_level(level) do
       ExCodecs.NIF.wrap(:zstd, ExCodecs.Native.zstd_compress(data, level))
     end
   end

   @impl true
   def decode(data, _opts) do
     ExCodecs.NIF.wrap(:zstd, ExCodecs.Native.zstd_decompress(data))
   end
 end

Codec Metadata

Codec modules should also export a __codec_info__/0 function that returns metadata about the codec for the registry:

 def __codec_info__ do
   %ExCodecs.Codec{
     name: :zstd,
     category: :compression,
     native?: true,
     streaming?: true,
     configurable?: true,
     version: "1.5.x"
   }
 end

Summary

Callbacks

Decodes (decompresses, etc.) the given binary data.

Encodes (compresses, hashes, etc.) the given binary data.

Functions

Validates that a module implements the ExCodecs.Codec behaviour.

Types

decode_result()

@type decode_result() :: {:ok, binary()} | {:error, ExCodecs.Error.t()}

encode_result()

@type encode_result() :: {:ok, binary()} | {:error, ExCodecs.Error.t()}

t()

@type t() :: %ExCodecs.Codec{
  category: atom(),
  configurable?: boolean(),
  module: module() | nil,
  name: atom(),
  native?: boolean(),
  streaming?: boolean(),
  version: String.t() | nil
}

Callbacks

decode(data, opts)

@callback decode(data :: binary(), opts :: keyword()) :: decode_result()

Decodes (decompresses, etc.) the given binary data.

Arguments

  • data - The binary data to decode
  • opts - Codec-specific options as a keyword list

Returns

  • {:ok, decoded_binary} - Successfully decoded data
  • {:error, %ExCodecs.Error{}} - Decoding failed

encode(data, opts)

@callback encode(data :: binary(), opts :: keyword()) :: encode_result()

Encodes (compresses, hashes, etc.) the given binary data.

Arguments

  • data - The binary data to encode
  • opts - Codec-specific options as a keyword list

Returns

  • {:ok, encoded_binary} - Successfully encoded data
  • {:error, %ExCodecs.Error{}} - Encoding failed

Functions

validates?(module)

@spec validates?(module()) :: boolean()

Validates that a module implements the ExCodecs.Codec behaviour.