EncodingRs.Decoder (encoding_rs v0.5.0)

Copy Markdown

Stateful streaming decoder for converting encoded byte streams to UTF-8.

Use this module when decoding multibyte encodings (such as Shift_JIS, GBK, Big5, EUC-JP, or UTF-16) from chunked sources like File.stream!/3 or network sockets. Incomplete byte sequences at the end of a chunk stay buffered until the next chunk completes them.

Usage

Stream pipelines

Use stream/3 when you want error tuples instead of exceptions, or stream!/3 for pipelines that expect plain strings and raise on error:

File.stream!("data.txt", [], 64 * 1024)
|> EncodingRs.Decoder.stream!("shift_jis")
|> Enum.join()

File.stream!("data.txt", [], 64 * 1024)
|> EncodingRs.Decoder.stream("shift_jis", on_error: :error)
|> Enum.reduce_while([], fn
  {:ok, chunk}, acc -> {:cont, [chunk | acc]}
  {:error, reason}, _acc -> {:halt, {:error, reason}}
end)

Manual chunk loops

{:ok, decoder} = EncodingRs.Decoder.new("shift_jis")
{:ok, out1, false} = EncodingRs.Decoder.decode_chunk(decoder, chunk1, false)
{:ok, out2, false} = EncodingRs.Decoder.decode_chunk(decoder, chunk2, true)
result = out1 <> out2

Important notes

  • Pass is_last: true on the final chunk to flush buffered bytes. Calling decode_chunk/3 after is_last: true returns {:error, :decoder_finished}.
  • Each decoder holds mutable state. Use one decoder per stream and avoid sharing it across concurrent processes.
  • For complete binaries already in memory, prefer EncodingRs.decode/3.

Summary

Types

Error reasons returned while decoding a chunk.

Result of decoding one chunk.

Error reasons emitted by non-bang decoder streams.

t()

An opaque decoder created with new/1 or new/2.

Functions

Decodes one chunk of bytes using the stateful decoder.

Decodes one chunk, returning {output, had_errors} or raising on error.

Returns the decoder's active canonical encoding name.

Creates a stateful decoder for the requested encoding.

Creates a stateful decoder, raising ArgumentError if the encoding is unknown.

Returns a non-raising stream that decodes binary chunks to tagged UTF-8 results.

Returns a stream that decodes binary chunks to UTF-8 strings, raising on error.

Returns a non-raising stream that decodes binary chunks and reports replacement errors.

Returns a stream that decodes binary chunks to {string, had_errors} tuples, raising on error.

Types

chunk_error()

@type chunk_error() ::
  :input_too_large
  | :malformed_input
  | :decoder_finished
  | :allocation_failed
  | :lock_poisoned

Error reasons returned while decoding a chunk.

decode_result()

@type decode_result() ::
  {:ok, String.t(), had_errors :: boolean()} | {:error, chunk_error()}

Result of decoding one chunk.

stream_error()

@type stream_error() :: :unknown_encoding | chunk_error()

Error reasons emitted by non-bang decoder streams.

t()

@opaque t()

An opaque decoder created with new/1 or new/2.

Functions

decode_chunk(decoder, chunk, is_last \\ false)

@spec decode_chunk(t(), binary(), boolean()) :: decode_result()

Decodes one chunk of bytes using the stateful decoder.

Pass is_last: true on the final chunk to flush buffered bytes. Calling this function again after is_last: true (or after a strict-mode error) returns {:error, :decoder_finished}.

Examples

iex> {:ok, decoder} = EncodingRs.Decoder.new("shift_jis")
iex> {:ok, out1, false} = EncodingRs.Decoder.decode_chunk(decoder, <<0x82>>, false)
iex> {:ok, out2, false} = EncodingRs.Decoder.decode_chunk(decoder, <<0xA0>>, true)
iex> out1 <> out2
"あ"

decode_chunk(decoder, chunk, is_last, opts)

@spec decode_chunk(t(), binary(), boolean(), EncodingRs.options()) :: decode_result()

decode_chunk!(decoder, chunk, is_last \\ false)

@spec decode_chunk!(t(), binary(), boolean()) :: {String.t(), boolean()}

Decodes one chunk, returning {output, had_errors} or raising on error.

Examples

iex> decoder = EncodingRs.Decoder.new!("utf-8")
iex> EncodingRs.Decoder.decode_chunk!(decoder, "hello", true)
{"hello", false}

decode_chunk!(decoder, chunk, is_last, opts)

@spec decode_chunk!(t(), binary(), boolean(), EncodingRs.options()) ::
  {String.t(), boolean()}

encoding(decoder)

@spec encoding(t()) :: {:ok, EncodingRs.encoding()} | {:error, :lock_poisoned}

Returns the decoder's active canonical encoding name.

When the decoder uses bom: :sniff (default), this value updates after the first chunk if a leading UTF-8 or UTF-16 BOM switches the encoding.

Examples

iex> {:ok, decoder} = EncodingRs.Decoder.new("windows-1252")
iex> {:ok, "H", false} = EncodingRs.Decoder.decode_chunk(decoder, <<0xFF, 0xFE, 0x48, 0x00>>, true)
iex> EncodingRs.Decoder.encoding(decoder)
{:ok, "UTF-16LE"}

new(encoding, opts \\ [])

@spec new(EncodingRs.encoding(), EncodingRs.decode_options()) ::
  {:ok, t()} | {:error, :unknown_encoding}

Creates a stateful decoder for the requested encoding.

Accepts :dirty_threshold, :max_input_size, :bom (:sniff, :strip, or :preserve), and :on_error (:replace or :error). Options passed to new/2 are validated once and reused for every decode_chunk/3 call.

Examples

iex> {:ok, decoder} = EncodingRs.Decoder.new("shift_jis")
iex> EncodingRs.Decoder.decode_chunk(decoder, <<0x82, 0xA0>>, true)
{:ok, "あ", false}

iex> EncodingRs.Decoder.new("invalid-encoding")
{:error, :unknown_encoding}

iex> {:ok, decoder} = EncodingRs.Decoder.new("utf-8", max_input_size: 4)
iex> EncodingRs.Decoder.decode_chunk(decoder, "hello", true)
{:error, :input_too_large}

new!(encoding, opts \\ [])

Creates a stateful decoder, raising ArgumentError if the encoding is unknown.

Examples

iex> decoder = EncodingRs.Decoder.new!("shift_jis")
iex> EncodingRs.Decoder.decode_chunk!(decoder, <<0x82, 0xA0>>, true)
{"あ", false}

iex> EncodingRs.Decoder.new!("invalid-encoding")
** (ArgumentError) unknown encoding: invalid-encoding

stream(chunks, encoding, opts \\ [])

Returns a non-raising stream that decodes binary chunks to tagged UTF-8 results.

Each emitted element is {:ok, string} or {:error, reason}. If the encoding is unknown, the stream emits one {:error, :unknown_encoding} tuple without reading from chunks. If a chunk fails (for example :input_too_large or :malformed_input under on_error: :error), the stream emits one {:error, reason} tuple and stops. Invalid option keys or values still raise ArgumentError immediately.

Use stream!/3 when you want plain strings and exceptions on error.

Examples

iex> [<<0x82>>, <<0xA0>>] |> EncodingRs.Decoder.stream("shift_jis") |> Enum.to_list()
[{:ok, ""}, {:ok, "あ"}]

iex> ["hello"] |> EncodingRs.Decoder.stream("not-an-encoding") |> Enum.to_list()
[{:error, :unknown_encoding}]

stream!(chunks, encoding, opts \\ [])

Returns a stream that decodes binary chunks to UTF-8 strings, raising on error.

Emits one string per input chunk, plus one final flush element if buffered bytes remain at the end of the stream.

Examples

iex> [<<0x82>>, <<0xA0>>] |> EncodingRs.Decoder.stream!("shift_jis") |> Enum.join()
"あ"

stream_with_errors(chunks, encoding, opts \\ [])

@spec stream_with_errors(
  Enumerable.t(),
  EncodingRs.encoding(),
  EncodingRs.decode_options()
) ::
  Enumerable.t()

Returns a non-raising stream that decodes binary chunks and reports replacement errors.

Each emitted element is {:ok, string, had_errors} or {:error, reason}. On error, the stream emits one {:error, reason} tuple and stops.

Use stream_with_errors!/3 when you want {string, had_errors} tuples and exceptions on error.

Examples

iex> [<<"hello">>, <<0xFF>>] |> EncodingRs.Decoder.stream_with_errors("utf-8") |> Enum.to_list()
[{:ok, "hello", false}, {:ok, "�", true}]

stream_with_errors!(chunks, encoding, opts \\ [])

@spec stream_with_errors!(
  Enumerable.t(),
  EncodingRs.encoding(),
  EncodingRs.decode_options()
) ::
  Enumerable.t()

Returns a stream that decodes binary chunks to {string, had_errors} tuples, raising on error.

Examples

iex> [<<"hello">>, <<0xFF>>] |> EncodingRs.Decoder.stream_with_errors!("utf-8") |> Enum.to_list()
[{"hello", false}, {"�", true}]