EncodingRs. Encoder
(encoding_rs v0.5.0)
Copy Markdown
Stateful streaming encoder for converting UTF-8 byte streams to legacy or UTF-8 encodings.
Use this module when encoding chunked text streams such as File.stream!/3
or transcoding pipelines. Unlike repeated one-shot EncodingRs.encode/3
calls, a streaming encoder:
- Preserves encoder shift state across chunks for stateful encodings such as
ISO-2022-JP, emitting only one final return-to-ASCII sequence at EOF. - Buffers incomplete multi-byte UTF-8 sequences split across raw byte chunk boundaries until the next chunk completes the code point.
Usage
Stream pipelines
File.stream!("utf8.txt", [], 64 * 1024)
|> EncodingRs.Encoder.stream!("shift_jis")
|> Stream.into(File.stream!("sjis.txt"))
|> Stream.run()
File.stream!("utf8.txt", [], 64 * 1024)
|> EncodingRs.Encoder.stream("windows-1252", on_error: :error)
|> Enum.reduce_while([], fn
{:ok, chunk}, acc -> {:cont, [chunk | acc]}
{:error, reason}, _acc -> {:halt, {:error, reason}}
end)Manual chunk loops
{:ok, encoder} = EncodingRs.Encoder.new("iso-2022-jp")
{:ok, out1, false} = EncodingRs.Encoder.encode_chunk(encoder, "こん", false)
{:ok, out2, false} = EncodingRs.Encoder.encode_chunk(encoder, "にちは", true)
result = out1 <> out2Important notes
- Pass
is_last: trueon the final chunk so stateful encodings flush their closing escape sequence and trailing incomplete UTF-8 bytes are validated. Callingencode_chunk/3afteris_last: truereturns{:error, :encoder_finished}. - Decode-only labels (
"utf-16le","utf-16be","replacement") return{:error, :encoder_unavailable}. - Each encoder holds mutable state. Use one encoder per stream and avoid sharing it across concurrent processes.
Summary
Types
Error reasons returned while encoding a chunk.
Result of encoding one chunk.
Error reasons returned when creating an encoder.
Error reasons emitted by non-bang encoder streams.
Functions
Encodes one UTF-8 chunk using the stateful encoder.
Encodes one UTF-8 chunk, returning {binary, had_errors} or raising on error.
Creates a stateful encoder for the requested output encoding.
Creates a stateful encoder, raising ArgumentError if the encoding is unknown
or decode-only.
Returns a non-raising stream that encodes UTF-8 chunks to tagged binary results.
Returns a stream that encodes UTF-8 chunks to binaries, raising on error.
Returns a non-raising stream that encodes UTF-8 chunks and reports unmappable-character replacements.
Returns a stream that encodes UTF-8 chunks to {binary, had_errors} tuples,
raising on error.
Types
@type chunk_error() ::
:input_too_large
| :invalid_utf8
| :unmappable_character
| :encoder_finished
| :allocation_failed
| :lock_poisoned
Error reasons returned while encoding a chunk.
@type encode_result() :: {:ok, binary(), had_errors :: boolean()} | {:error, chunk_error()}
Result of encoding one chunk.
@type new_error() :: :unknown_encoding | :encoder_unavailable
Error reasons returned when creating an encoder.
@type stream_error() :: new_error() | chunk_error()
Error reasons emitted by non-bang encoder streams.
@opaque t()
Functions
@spec encode_chunk(t(), binary(), boolean()) :: encode_result()
Encodes one UTF-8 chunk using the stateful encoder.
Incomplete multi-byte UTF-8 sequences at the end of chunk are buffered when
is_last is false. Pass is_last: true on the final chunk to flush shift
state and validate that no incomplete UTF-8 sequence remains.
Examples
iex> {:ok, encoder} = EncodingRs.Encoder.new("shift_jis")
iex> <<b1, b2, b3>> = "あ"
iex> {:ok, out1, false} = EncodingRs.Encoder.encode_chunk(encoder, <<b1, b2>>, false)
iex> {:ok, out2, false} = EncodingRs.Encoder.encode_chunk(encoder, <<b3>>, true)
iex> out1 <> out2
<<0x82, 0xA0>>
@spec encode_chunk(t(), binary(), boolean(), EncodingRs.options()) :: encode_result()
Encodes one UTF-8 chunk, returning {binary, had_errors} or raising on error.
Examples
iex> encoder = EncodingRs.Encoder.new!("windows-1252")
iex> EncodingRs.Encoder.encode_chunk!(encoder, "hello", true)
{"hello", false}
@spec new(EncodingRs.encoding(), EncodingRs.encode_options()) :: {:ok, t()} | {:error, new_error()}
Creates a stateful encoder for the requested output encoding.
Accepts :dirty_threshold, :max_input_size, and :on_error (:replace or
:error). Options passed to new/2 are validated once and reused for every
encode_chunk/3 call.
Returns {:error, :encoder_unavailable} for decode-only labels ("utf-16le",
"utf-16be", "replacement").
Examples
iex> {:ok, encoder} = EncodingRs.Encoder.new("shift_jis")
iex> EncodingRs.Encoder.encode_chunk(encoder, "あ", true)
{:ok, <<0x82, 0xA0>>, false}
iex> EncodingRs.Encoder.new("utf-16le")
{:error, :encoder_unavailable}
iex> EncodingRs.Encoder.new("invalid-encoding")
{:error, :unknown_encoding}
@spec new!(EncodingRs.encoding(), EncodingRs.encode_options()) :: t()
Creates a stateful encoder, raising ArgumentError if the encoding is unknown
or decode-only.
Examples
iex> encoder = EncodingRs.Encoder.new!("shift_jis")
iex> EncodingRs.Encoder.encode_chunk!(encoder, "あ", true)
{<<0x82, 0xA0>>, false}
iex> EncodingRs.Encoder.new!("utf-16le")
** (ArgumentError) encoding is decode-only: utf-16le
@spec stream(Enumerable.t(), EncodingRs.encoding(), EncodingRs.encode_options()) :: Enumerable.t()
Returns a non-raising stream that encodes UTF-8 chunks to tagged binary results.
Each emitted element is {:ok, binary} or {:error, reason}. If the
encoding is unknown or decode-only, the stream emits one {:error, reason}
tuple without reading from chunks. Invalid option keys or values raise
ArgumentError immediately.
Use stream!/3 when you want plain binaries and exceptions on error.
Examples
iex> ["こん", "にちは"] |> EncodingRs.Encoder.stream("shift_jis") |> Enum.to_list()
[{:ok, <<130, 177, 130, 241>>}, {:ok, <<130, 201, 130, 191, 130, 205>>}]
iex> ["hello"] |> EncodingRs.Encoder.stream("utf-16le") |> Enum.to_list()
[{:error, :encoder_unavailable}]
@spec stream!(Enumerable.t(), EncodingRs.encoding(), EncodingRs.encode_options()) :: Enumerable.t()
Returns a stream that encodes UTF-8 chunks to binaries, raising on error.
Examples
iex> ["こん", "にちは"] |> EncodingRs.Encoder.stream!("shift_jis") |> Enum.into(<<>>)
<<130, 177, 130, 241, 130, 201, 130, 191, 130, 205>>
@spec stream_with_errors( Enumerable.t(), EncodingRs.encoding(), EncodingRs.encode_options() ) :: Enumerable.t()
Returns a non-raising stream that encodes UTF-8 chunks and reports unmappable-character replacements.
Each emitted element is {:ok, binary, had_errors} or {:error, reason}.
Examples
iex> ["Hello", "🎉"] |> EncodingRs.Encoder.stream_with_errors("windows-1252") |> Enum.to_list()
[{:ok, "Hello", false}, {:ok, "🎉", true}]
@spec stream_with_errors!( Enumerable.t(), EncodingRs.encoding(), EncodingRs.encode_options() ) :: Enumerable.t()
Returns a stream that encodes UTF-8 chunks to {binary, had_errors} tuples,
raising on error.
Examples
iex> ["Hello", "🎉"] |> EncodingRs.Encoder.stream_with_errors!("windows-1252") |> Enum.to_list()
[{"Hello", false}, {"🎉", true}]