Smile.Encoder (SmileEx v0.2.0)
View SourceProvides functionality to encode Elixir terms into Smile binary format.
The encoder handles all JSON-compatible data types and provides optimization features such as back-references for field names and string values to reduce output size.
Supported Types
The encoder supports the following Elixir types:
nil- Encoded as Smile null tokentrue,false- Encoded as Smile boolean tokens- Integers - Encoded with variable-length encoding (small int, 32-bit, 64-bit)
- Floats - Encoded as 64-bit IEEE double precision
- Strings (binaries) - Encoded with length optimization (tiny, small, long)
- Lists - Encoded as Smile arrays
- Maps - Encoded as Smile objects
- Atoms - Converted to strings and encoded
Encoding Options
The encoder accepts the following options:
:shared_names(boolean, default:true) - Enable back-references for field names. When enabled, repeated object keys are stored once and referenced in subsequent occurrences, reducing output size.:shared_values(boolean, default:true) - Enable back-references for short string values (64 bytes or less). Similar to shared names, but for string values.:raw_binary(boolean, default:false) - Allow raw binary data in the output. When enabled, binary data can be included without escaping.
Examples
# Basic encoding
iex> Smile.Encoder.encode("hello")
{:ok, <<58, 41, 10, 3, ...>>}
# Encoding with options
iex> Smile.Encoder.encode(%{"key" => "value"}, shared_names: false)
{:ok, <<58, 41, 10, 0, ...>>}Implementation Details
The encoder implements the following optimizations:
- Small integers (-16 to +15) are encoded in a single byte
- Variable-length integer encoding (VInt) for efficient number representation
- ZigZag encoding for signed integers
- String encoding optimization based on length and character set (ASCII vs Unicode)
- Back-references for repeated field names and values
Summary
Functions
Encodes an Elixir term into Smile binary format.
Functions
Encodes an Elixir term into Smile binary format.
Options
:shared_names- Enable back references for field names (default: true):shared_values- Enable back references for string values (default: true):raw_binary- Allow raw binary values (default: false)
Examples
iex> Smile.Encoder.encode(%{"hello" => "world"})
{:ok, <<0x3A, 0x29, 0x0A, 0x03, 0xFA, ...>>}