|
1 | 1 | defmodule Msgpack.StreamEncoder do |
| 2 | + @moduledoc """ |
| 3 | + Lazily encodes a stream of Elixir terms into a stream of MessagePack binaries. |
| 4 | +
|
| 5 | + This module is the counterpart to `Msgpack.StreamDecoder`. It processes an |
| 6 | + enumerable item by item, making it memory-efficient for encoding large |
| 7 | + collections or infinite streams without loading the entire dataset into |
| 8 | + memory. |
| 9 | +
|
| 10 | + Each item in the output stream is a result tuple, either `{:ok, binary}` for |
| 11 | + a successful encoding or `{:error, reason}` if an individual term could |
| 12 | + not be encoded. |
| 13 | + """ |
| 14 | + |
2 | 15 | @doc """ |
3 | | - Encodes a stream of Elixir terms into a stream of MessagePack binaries. |
| 16 | + Lazily encodes an enumerable of Elixir terms into a stream of result tuples. |
| 17 | +
|
| 18 | + ## Parameters |
| 19 | +
|
| 20 | + * `enumerable`: An `Enumerable` that yields Elixir terms to be encoded. |
| 21 | + * `opts`: A keyword list of options passed to the underlying encoder for each term. |
| 22 | +
|
| 23 | + ## Return Value |
| 24 | +
|
| 25 | + Returns a lazy `Stream` that emits result tuples. For each term in the |
| 26 | + input enumerable, the stream will contain either: |
| 27 | + * `{:ok, binary}` - On successful encoding. |
| 28 | + * `{:error, reason}` - If the term cannot be encoded. |
| 29 | +
|
| 30 | + ## Options |
| 31 | +
|
| 32 | + This function accepts the same options as `Msgpack.encode/2`. See the |
| 33 | + documentation for `Msgpack.encode/2` for a full list. |
| 34 | +
|
| 35 | + ## Examples |
| 36 | +
|
| 37 | + ### Standard Usage |
| 38 | +
|
| 39 | + ```elixir |
| 40 | + iex> terms = [1, "elixir"] |
| 41 | + iex> Msgpack.StreamEncoder.encode(terms) |> Enum.to_list() |
| 42 | + [ |
| 43 | + {:ok, <<1>>}, |
| 44 | + {:ok, <<166, 101, 108, 105, 120, 105, 114>>} |
| 45 | + ] |
| 46 | + ``` |
| 47 | +
|
| 48 | + ### Handling Unencodable Terms |
| 49 | +
|
| 50 | + ```elixir |
| 51 | + iex> terms = [1, :elixir, 4] |
| 52 | + iex> Msgpack.StreamEncoder.encode(terms, atoms: :error) |> Enum.to_list() |
| 53 | + [ |
| 54 | + {:ok, <<1>>}, |
| 55 | + {:error, {:unsupported_atom, :elixir}}, |
| 56 | + {:ok, <<4>>} |
| 57 | + ] |
| 58 | + ``` |
4 | 59 | """ |
5 | 60 | def encode(enumerable, opts \\ []) do |
6 | 61 | Stream.map(enumerable, &Msgpack.encode(&1, opts)) |
|
0 commit comments