@@ -12,8 +12,10 @@ types.
1212## Features
1313
1414- ** Specification Compliance:** Implements the complete MessagePack type system.
15- - ** Elixir Struct Support:** Encodes and decodes ` DateTime ` and ` NaiveDateTime `
16- structs via the Timestamp extension type.
15+ - ** Extensible Struct Support:**
16+ - Natively encodes and decodes ` DateTime ` and ` NaiveDateTime ` structs via the
17+ Timestamp extension type.
18+ - Allows any custom struct to be encoded via the ` Msgpack.Encodable ` protocol.
1719- ** Configurable Validation:** Provides an option to bypass UTF-8 validation on
1820 strings for performance-critical paths.
1921- ** Resource Limiting:** Includes configurable ` :max_depth ` and ` :max_byte_size `
@@ -30,7 +32,7 @@ Add `msgpack_elixir` to your list of dependencies in `mix.exs`:
3032
3133``` elixir
3234def deps do
33- [{:msgpack_elixir , " ~> 1 .0.0" }]
35+ [{:msgpack_elixir , " ~> 2 .0.0" }]
3436end
3537```
3638
@@ -104,6 +106,38 @@ determinism is not required, you can disable it:
104106Msgpack .encode (map, deterministic: false )
105107```
106108
109+ ### Custom Struct Serialization
110+
111+ You can add custom encoding logic for your own Elixir structs by implementing
112+ the ` Msgpack.Encodable ` protocol. This allows ` Msgpack.encode/2 ` to accept your
113+ structs directly, centralizing conversion logic within the protocol
114+ implementation.
115+
116+
117+ ``` elixir
118+ # 1. Define your application's struct
119+ defmodule Product do
120+ defstruct [:id , :name ]
121+ end
122+
123+ # 2. Implement the `Msgpack.Encodable` protocol for that struct
124+ defimpl Msgpack .Encodable , for: Product do
125+
126+ # 3. Inside the protocol's `encode/1` function, transform your struct into a basic
127+ # Elixir term that MessagePack can encode (e.g., a map or a list).
128+ def encode (%Product {id: id, name: name}) do
129+ {:ok , %{" id" => id, " name" => name}}
130+ end
131+ end
132+
133+ iex> product = %Product {id: 1 , name: " Elixir" }
134+ iex> {:ok , binary} = Msgpack .encode (product)
135+ << 130 , 162 , 105 , 100 , 1 , 164 , 110 , 97 , 109 , 101 , 166 , 69 , 108 , 105 , 120 , 105 , 114 >>
136+
137+ iex> Msgpack .decode (binary)
138+ {:ok , %{" id" => 1 , " name" => " Elixir" }}
139+ ```
140+
107141## Full Documentation
108142
109143For detailed information on all features, options, and functions, see the [ full
0 commit comments