EncodingRs (encoding_rs v0.5.0)
Copy MarkdownCharacter encoding conversion and detection powered by Mozilla's encoding_rs
and chardetng crates.
This library decodes all 40 encodings in the WHATWG Encoding Standard (with over 200 label aliases), encodes their 37 output encodings, and detects unlabeled byte streams heuristically.
Features
- WHATWG conversion: Implements the WHATWG decoding and encoding algorithms used by Firefox.
- Dirty schedulers: Operations on inputs larger than
:dirty_threshold(default 64 KB) run on dirty CPU schedulers to keep normal schedulers free. - Strict and replacing error modes: Choose between WHATWG replacement
(
on_error: :replace, default) and strict failure (on_error: :error). - BOM handling: Control Byte Order Mark handling with
bom: :sniff(default),bom: :strip, orbom: :preserve. - Streaming APIs: Use
EncodingRs.DecoderandEncodingRs.Encoderfor chunked streams, andEncodingRs.Detectorfor incremental detection.
Operation options
All conversion and detection functions accept per-call options:
:dirty_threshold(default65_536): Byte count above which the call uses a dirty CPU scheduler. Must be a non-negative integer.:max_input_size(default104_857_600): Maximum allowed input size in bytes, or:infinityfor trusted inputs bounded elsewhere.:bom(decode functions only, default:sniff): Controls BOM handling::sniffswitches encodings on a leading UTF-8 or UTF-16 BOM and removes it,:stripremoves a BOM only when it matches the requested encoding, and:preservekeeps any leading BOM asU+FEFF.:on_error(encode and decode functions, default:replace)::replacereplaces malformed decode bytes withU+FFFDand unmappable encode characters with HTML decimal numeric character references (😀).:errorfails with{:error, :malformed_input}on decode or{:error, :unmappable_character}on encode.
Memory guardrail
Setting max_input_size: :infinity removes the built-in allocation limit.
Use it only when inputs are trusted and bounded by other means. For large
files or untrusted streams, use EncodingRs.Decoder or EncodingRs.Encoder
with bounded chunk sizes.
Supported encodings
- Unicode: UTF-8 (encode and decode); UTF-16LE and UTF-16BE (decode only;
use
:unicode.characters_to_binary/3for UTF-16 output) - Windows code pages: 874, 1250 through 1258, 949, 932
- ISO-8859 family: 2, 3, 4, 5, 6, 7, 8, 8-I, 10, 13, 14, 15, 16
- IBM866, KOI8-R, KOI8-U, macintosh, x-mac-cyrillic, x-user-defined
- East Asian: Shift_JIS, EUC-JP, ISO-2022-JP, EUC-KR, GBK, gb18030, Big5
Examples
iex> EncodingRs.encode("Hello", "windows-1252")
{:ok, "Hello"}
iex> EncodingRs.decode(<<72, 101, 108, 108, 111>>, "windows-1252")
{:ok, "Hello"}
iex> EncodingRs.encode!("¥₪ש", "windows-1255")
<<165, 164, 249>>
iex> EncodingRs.decode!(<<165, 164, 249>>, "windows-1255")
"¥₪ש"
iex> EncodingRs.encoding_exists?("utf-8")
true
iex> EncodingRs.can_encode?("utf-16le")
false
Summary
Types
Result item returned by batch operations.
BOM handling mode for decode operations.
Result of BOM detection: encoding name and BOM length in bytes.
Input item for batch decoding: {binary, encoding}.
Result item returned by decode_batch/2.
Detailed one-shot decode result, including BOM selection and replacements.
Error reason atoms returned by decode operations.
Options accepted by decode operations.
Input item for batch encoding: {string, encoding}.
Result item returned by encode_batch/2.
Detailed one-shot encode result, including replacement status.
Error reason atoms returned by encode operations.
Options accepted by encode operations.
An encoding label string such as "utf-8", "shift_jis", or "windows-1252".
Error reason atoms returned by encoding, decoding, and BOM functions.
Error handling mode for encode and decode operations.
Per-operation scheduler and input-size options.
Functions
Returns whether the native NIF is loaded and callable.
Returns whether an encoding label is recognized and supports encoding.
Returns the canonical WHATWG name for an encoding label or alias.
Decodes a binary from the requested encoding to a UTF-8 string.
Decodes a binary from the requested encoding to a UTF-8 string, raising
ArgumentError on failure.
Decodes multiple {binary, encoding} items in one NIF call.
Decodes multiple binaries while reporting each item's selected encoding and replacement status.
Decodes a complete binary and reports the encoding used and whether
malformed input was replaced with U+FFFD.
Detects the most likely WHATWG encoding of a binary.
Detects the most likely WHATWG encoding of a binary, raising ArgumentError
on failure.
Detects a leading BOM and removes it from the binary.
Detects the encoding from a Byte Order Mark (BOM) at the start of the binary.
Returns the byte threshold above which operations use dirty CPU schedulers.
Encodes a UTF-8 string to the requested encoding.
Encodes a UTF-8 string to the requested encoding, raising ArgumentError on
failure.
Encodes multiple {string, encoding} items in one NIF call.
Encodes multiple strings while reporting whether each item had unmappable characters replaced.
Encodes a UTF-8 string and reports whether any unmappable character was replaced with an HTML numeric character reference.
Returns whether an encoding label is recognized for decoding.
Returns all 40 canonical WHATWG encoding names supported for decoding, including decode-only encodings.
Returns all 37 canonical WHATWG encoding names supported for encoding.
Returns the maximum allowed input size in bytes.
Returns the WHATWG output encoding name for an encoding label.
Types
@type batch_result(t) :: {:ok, t} | {:error, decode_error() | encode_error()}
Result item returned by batch operations.
@type bom_mode() :: :sniff | :strip | :preserve
BOM handling mode for decode operations.
@type bom_result() :: {:ok, encoding(), bom_length :: non_neg_integer()} | {:error, :no_bom}
Result of BOM detection: encoding name and BOM length in bytes.
Input item for batch decoding: {binary, encoding}.
@type decode_batch_result() :: {:ok, String.t()} | {:error, decode_error()}
Result item returned by decode_batch/2.
@type decode_details_result() :: {:ok, String.t(), actual_encoding :: encoding(), had_errors :: boolean()} | {:error, decode_error()}
Detailed one-shot decode result, including BOM selection and replacements.
@type decode_error() ::
:unknown_encoding | :malformed_input | :input_too_large | :allocation_failed
Error reason atoms returned by decode operations.
@type decode_options() :: [ dirty_threshold: non_neg_integer(), max_input_size: non_neg_integer() | :infinity, bom: bom_mode(), on_error: on_error() ]
Options accepted by decode operations.
@type detect_options() :: [ dirty_threshold: non_neg_integer(), max_input_size: non_neg_integer() | :infinity, tld: String.t() | nil, allow_utf8: boolean(), allow_iso_2022_jp: boolean(), bom: boolean() ]
Input item for batch encoding: {string, encoding}.
@type encode_batch_result() :: {:ok, binary()} | {:error, encode_error()}
Result item returned by encode_batch/2.
@type encode_details_result() :: {:ok, binary(), had_errors :: boolean()} | {:error, encode_error()}
Detailed one-shot encode result, including replacement status.
@type encode_error() ::
:unknown_encoding
| :encoder_unavailable
| :invalid_utf8
| :unmappable_character
| :input_too_large
| :allocation_failed
Error reason atoms returned by encode operations.
@type encode_options() :: [ dirty_threshold: non_neg_integer(), max_input_size: non_neg_integer() | :infinity, on_error: on_error() ]
Options accepted by encode operations.
@type encoding() :: String.t()
An encoding label string such as "utf-8", "shift_jis", or "windows-1252".
Call list_encodings/0 for all canonical names, or see the
WHATWG Encoding Standard.
@type error_reason() :: decode_error() | encode_error() | :no_bom
Error reason atoms returned by encoding, decoding, and BOM functions.
@type on_error() :: :replace | :error
Error handling mode for encode and decode operations.
@type options() :: [ dirty_threshold: non_neg_integer(), max_input_size: non_neg_integer() | :infinity ]
Per-operation scheduler and input-size options.
Functions
@spec available?() :: boolean()
Returns whether the native NIF is loaded and callable.
Never raises when the NIF is missing, allowing callers to guard optional encoding paths.
Examples
iex> EncodingRs.available?()
true
Returns whether an encoding label is recognized and supports encoding.
Returns false for unknown labels and for decode-only WHATWG labels
("utf-16le", "utf-16be", and "replacement").
Examples
iex> EncodingRs.can_encode?("shift_jis")
true
iex> EncodingRs.can_encode?("utf-16le")
false
iex> EncodingRs.can_encode?("not-an-encoding")
false
Returns the canonical WHATWG name for an encoding label or alias.
Examples
iex> EncodingRs.canonical_name("latin1")
{:ok, "windows-1252"}
iex> EncodingRs.canonical_name("utf8")
{:ok, "UTF-8"}
iex> EncodingRs.canonical_name("invalid")
{:error, :unknown_encoding}
@spec decode(binary(), encoding()) :: {:ok, String.t()} | {:error, decode_error()}
Decodes a binary from the requested encoding to a UTF-8 string.
Returns {:ok, string} on success, or {:error, reason} on failure.
By default (bom: :sniff, on_error: :replace), a leading UTF-8 or UTF-16
BOM overrides the requested encoding and is removed, and malformed byte
sequences are replaced with U+FFFD. Pass :bom to control BOM handling,
pass on_error: :error to return {:error, :malformed_input} on invalid
bytes, or call decode_with_details/3 to observe BOM overrides and
replacements.
Examples
iex> EncodingRs.decode(<<72, 101, 108, 108, 111>>, "windows-1252")
{:ok, "Hello"}
iex> EncodingRs.decode(<<0xFF>>, "utf-8", on_error: :error)
{:error, :malformed_input}
iex> EncodingRs.decode(<<0xEF, 0xBB, 0xBF, "hi">>, "utf-8", bom: :preserve)
{:ok, "\uFEFFhi"}
iex> EncodingRs.decode(<<0xFF>>, "invalid-encoding")
{:error, :unknown_encoding}
@spec decode(binary(), encoding(), decode_options()) :: {:ok, String.t()} | {:error, decode_error()}
Decodes a binary from the requested encoding to a UTF-8 string, raising
ArgumentError on failure.
Examples
iex> EncodingRs.decode!(<<72, 101, 108, 108, 111>>, "windows-1252")
"Hello"
iex> EncodingRs.decode!(<<0xFF>>, "invalid-encoding")
** (ArgumentError) unknown encoding: invalid-encoding
@spec decode!(binary(), encoding(), decode_options()) :: String.t()
@spec decode_batch([decode_batch_item()]) :: [decode_batch_result()]
Decodes multiple {binary, encoding} items in one NIF call.
Returns results in input order. The combined byte size of valid items selects
whether the call runs on a normal or dirty CPU scheduler. Oversized items
return {:error, :input_too_large} individually without affecting other items.
Accepts the same options as decode/3, including :bom and :on_error.
Examples
iex> items = [{<<72, 101, 108, 108, 111>>, "windows-1252"}, {<<0x82, 0xA0>>, "shift_jis"}]
iex> EncodingRs.decode_batch(items)
[{:ok, "Hello"}, {:ok, "あ"}]
iex> EncodingRs.decode_batch([{<<72>>, "invalid-encoding"}])
[{:error, :unknown_encoding}]
@spec decode_batch([decode_batch_item()], decode_options()) :: [decode_batch_result()]
@spec decode_batch_with_details([decode_batch_item()]) :: [decode_details_result()]
Decodes multiple binaries while reporting each item's selected encoding and replacement status.
Results preserve input order. See decode_with_details/3 for the tuple
format.
Examples
iex> EncodingRs.decode_batch_with_details([{"hello", "utf-8"}, {<<0xFF>>, "utf-8"}])
[{:ok, "hello", "UTF-8", false}, {:ok, "�", "UTF-8", true}]
@spec decode_batch_with_details([decode_batch_item()], decode_options()) :: [ decode_details_result() ]
@spec decode_with_details(binary(), encoding()) :: decode_details_result()
Decodes a complete binary and reports the encoding used and whether
malformed input was replaced with U+FFFD.
When bom: :sniff (default), actual_encoding differs from the requested
label if a leading UTF-8 or UTF-16 BOM selects another encoding.
Examples
iex> EncodingRs.decode_with_details(<<0xFF>>, "utf-8")
{:ok, "�", "UTF-8", true}
iex> EncodingRs.decode_with_details(<<0xFF, 0xFE, 0x48, 0x00>>, "windows-1252")
{:ok, "H", "UTF-16LE", false}
iex> EncodingRs.decode_with_details(<<0xFF, 0xFE, 0x48, 0x00>>, "windows-1252", bom: :strip)
{:ok, "ÿþH\0", "windows-1252", false}
@spec decode_with_details(binary(), encoding(), decode_options()) :: decode_details_result()
Detects the most likely WHATWG encoding of a binary.
Checks for a leading UTF-8 or UTF-16 BOM first (unless bom: false), then
runs Mozilla's chardetng heuristic detector. For incremental detection over
large files or streams, use EncodingRs.Detector.
Options
:tld(defaultnil): Lowercase ASCII top-level domain label without dots (such as"jp","cn", or"ru"), or punycode for IDN TLDs, to bias ambiguous legacy text.:allow_utf8(defaulttrue): Set tofalseto disallow"UTF-8"as a heuristic result.:allow_iso_2022_jp(defaultfalse): Set totruewhen inspecting email or other inputs whereISO-2022-JPis expected.:bom(defaulttrue): Set tofalseto ignore leading BOMs.:dirty_thresholdand:max_input_size: Standard scheduler and size limits.
Examples
iex> EncodingRs.detect("こんにちは")
{:ok, "UTF-8"}
iex> {:ok, sjis} = EncodingRs.encode("こんにちは世界、日本語のテストです。", "shift_jis")
iex> EncodingRs.detect(sjis, tld: "jp")
{:ok, "Shift_JIS"}
iex> EncodingRs.detect(<<0xFF, 0xFE, 0x48, 0x00>>)
{:ok, "UTF-16LE"}
@spec detect(binary(), detect_options()) :: {:ok, encoding()} | {:error, :input_too_large}
Detects the most likely WHATWG encoding of a binary, raising ArgumentError
on failure.
See detect/2 for options.
Examples
iex> EncodingRs.detect!("こんにちは")
"UTF-8"
@spec detect!(binary(), detect_options()) :: encoding()
Detects a leading BOM and removes it from the binary.
Returns {:ok, encoding, data_without_bom} or {:error, :no_bom}.
Examples
iex> EncodingRs.detect_and_strip_bom(<<0xEF, 0xBB, 0xBF, "hello">>)
{:ok, "UTF-8", "hello"}
iex> EncodingRs.detect_and_strip_bom("hello")
{:error, :no_bom}
@spec detect_bom(binary()) :: bom_result()
Detects the encoding from a Byte Order Mark (BOM) at the start of the binary.
Supported BOMs:
- UTF-8:
<<0xEF, 0xBB, 0xBF>>(3 bytes) - UTF-16LE:
<<0xFF, 0xFE>>(2 bytes) - UTF-16BE:
<<0xFE, 0xFF>>(2 bytes)
Returns {:ok, encoding, bom_length} or {:error, :no_bom}.
Examples
iex> EncodingRs.detect_bom(<<0xEF, 0xBB, 0xBF, "hello">>)
{:ok, "UTF-8", 3}
iex> EncodingRs.detect_bom(<<0xFF, 0xFE, 0x48, 0x00>>)
{:ok, "UTF-16LE", 2}
iex> EncodingRs.detect_bom(<<0xFE, 0xFF, 0x00, 0x48>>)
{:ok, "UTF-16BE", 2}
iex> EncodingRs.detect_bom("hello")
{:error, :no_bom}
@spec dirty_threshold() :: non_neg_integer()
Returns the byte threshold above which operations use dirty CPU schedulers.
Defaults to 65_536 bytes (64 KB). Pass :dirty_threshold in opts to
validate an explicit override.
Examples
iex> EncodingRs.dirty_threshold()
65536
@spec dirty_threshold(options()) :: non_neg_integer()
@spec encode(binary(), encoding()) :: {:ok, binary()} | {:error, encode_error()}
Encodes a UTF-8 string to the requested encoding.
Returns {:ok, binary} on success, or {:error, reason} on failure.
By default (on_error: :replace), unmappable characters become WHATWG HTML
decimal numeric character references (for example, "🎉" encodes as
"🎉" in "windows-1252"). Pass on_error: :error to reject
unmappable characters with {:error, :unmappable_character}, or call
encode_with_details/3 to detect replacements without failing.
Invalid UTF-8 binaries return {:error, :invalid_utf8}.
UTF-16LE, UTF-16BE, and replacement are decode-only in the WHATWG Encoding
Standard and return {:error, :encoder_unavailable}. To produce UTF-16 bytes
in Elixir, use :unicode.characters_to_binary(string, :utf8, {:utf16, :little})
or {:utf16, :big}.
Examples
iex> EncodingRs.encode("Hello", "windows-1252")
{:ok, "Hello"}
iex> EncodingRs.encode("🎉", "windows-1252")
{:ok, "🎉"}
iex> EncodingRs.encode("🎉", "windows-1252", on_error: :error)
{:error, :unmappable_character}
iex> EncodingRs.encode(<<0xFF>>, "windows-1252")
{:error, :invalid_utf8}
iex> EncodingRs.encode("Hello", "invalid-encoding")
{:error, :unknown_encoding}
@spec encode(binary(), encoding(), encode_options()) :: {:ok, binary()} | {:error, encode_error()}
Encodes a UTF-8 string to the requested encoding, raising ArgumentError on
failure.
Examples
iex> EncodingRs.encode!("Hello", "windows-1252")
"Hello"
iex> EncodingRs.encode!("Hello", "invalid-encoding")
** (ArgumentError) unknown encoding: invalid-encoding
@spec encode!(binary(), encoding(), encode_options()) :: binary()
@spec encode_batch([encode_batch_item()]) :: [encode_batch_result()]
Encodes multiple {string, encoding} items in one NIF call.
Returns results in input order. Accepts the same options as encode/3,
including :on_error.
Examples
iex> items = [{"Hello", "windows-1252"}, {"あ", "shift_jis"}]
iex> EncodingRs.encode_batch(items)
[{:ok, "Hello"}, {:ok, <<130, 160>>}]
iex> EncodingRs.encode_batch([{"test", "invalid-encoding"}])
[{:error, :unknown_encoding}]
@spec encode_batch([encode_batch_item()], encode_options()) :: [encode_batch_result()]
@spec encode_batch_with_details([encode_batch_item()]) :: [encode_details_result()]
Encodes multiple strings while reporting whether each item had unmappable characters replaced.
Results preserve input order. See encode_with_details/3 for the tuple
format.
Examples
iex> EncodingRs.encode_batch_with_details([{"Hello", "windows-1252"}, {"🎉", "windows-1252"}])
[{:ok, "Hello", false}, {:ok, "🎉", true}]
@spec encode_batch_with_details([encode_batch_item()], encode_options()) :: [ encode_details_result() ]
@spec encode_with_details(binary(), encoding()) :: encode_details_result()
Encodes a UTF-8 string and reports whether any unmappable character was replaced with an HTML numeric character reference.
Returns {:ok, binary, had_errors} on success, or {:error, reason} on
failure.
Examples
iex> EncodingRs.encode_with_details("Hello", "windows-1252")
{:ok, "Hello", false}
iex> EncodingRs.encode_with_details("🎉", "windows-1252")
{:ok, "🎉", true}
iex> EncodingRs.encode_with_details("🎉", "windows-1252", on_error: :error)
{:error, :unmappable_character}
@spec encode_with_details(binary(), encoding(), encode_options()) :: encode_details_result()
Returns whether an encoding label is recognized for decoding.
Returns true for all 40 WHATWG encodings and their aliases, including
decode-only labels ("utf-16le", "utf-16be", "replacement"). Use
can_encode?/1 to test whether a label also supports encoding.
Examples
iex> EncodingRs.encoding_exists?("utf-8")
true
iex> EncodingRs.encoding_exists?("utf-16le")
true
iex> EncodingRs.encoding_exists?("not-an-encoding")
false
@spec list_encodings() :: [encoding()]
Returns all 40 canonical WHATWG encoding names supported for decoding, including decode-only encodings.
Examples
iex> "UTF-8" in EncodingRs.list_encodings()
true
iex> "UTF-16LE" in EncodingRs.list_encodings()
true
@spec list_output_encodings() :: [encoding()]
Returns all 37 canonical WHATWG encoding names supported for encoding.
Excludes decode-only encodings ("UTF-16LE", "UTF-16BE", and
"replacement").
Examples
iex> "Shift_JIS" in EncodingRs.list_output_encodings()
true
iex> "UTF-16LE" in EncodingRs.list_output_encodings()
false
@spec max_input_size() :: non_neg_integer() | :infinity
Returns the maximum allowed input size in bytes.
Defaults to 104_857_600 bytes (100 MB). Pass :max_input_size in opts to
validate an explicit override (non_neg_integer() or :infinity).
Examples
iex> EncodingRs.max_input_size()
104857600
@spec max_input_size(options()) :: non_neg_integer() | :infinity
Returns the WHATWG output encoding name for an encoding label.
Most encodings map to their own canonical name. Decode-only labels
("utf-16le", "utf-16be", "replacement") map to "UTF-8" per the
WHATWG Encoding Standard.
Examples
iex> EncodingRs.output_encoding("latin1")
{:ok, "windows-1252"}
iex> EncodingRs.output_encoding("utf-16le")
{:ok, "UTF-8"}
iex> EncodingRs.output_encoding("invalid")
{:error, :unknown_encoding}