encoding-rs-kotlin

encoding-rs-kotlin is an idiomatic, high-performance, 100% pure Kotlin Multiplatform implementation of the WHATWG Encoding Standard, ported line-by-line from Henri Sivonen's upstream Rust crate encoding_rs.
encoding_rs is the battle-tested character encoding library developed for Mozilla Gecko and used in Firefox since version 56. This Kotlin port faithfully reproduces its algorithms, lookup tables, streaming state machines, and in-memory text manipulation utilities across all modern Kotlin targets without native C dependencies or JNI overhead.
Table of Contents
Installation
Add the dependency to your project:
Gradle (Kotlin DSL)
repositories {
mavenCentral()
}
dependencies {
implementation("io.github.kotlinmania:encoding-rs-kotlin:0.1.2")
}
Gradle Version Catalog (libs.versions.toml)
[versions]
encoding-rs = "0.1.2"
[libraries]
encoding-rs = { module = "io.github.kotlinmania:encoding-rs-kotlin", version.ref = "encoding-rs" }
Supported Platforms
encoding-rs-kotlin compiles and runs natively across all Tier-1 and Tier-2 Kotlin Multiplatform targets:
Key Features
The WHATWG Encoding Standard in Kotlin
The WHATWG Encoding Standard defines the exact set of legacy character encodings required for compatibility with the World Wide Web.
Unlike generic charset libraries that attempt to expose hundreds of platform-specific or historical code pages with loose round-tripping rules, this library follows the strict, deterministic security and error-handling requirements mandated by the web platform:
- Security-First Error Handling: Malformed byte sequences are replaced with the Unicode Replacement Character (
\uFFFD / ``) using WHATWG's maximal subpart replacement algorithm.
- Deterministic Label Matching: Case-insensitive and whitespace-trimmed lookup matching standard web labels (, , , , etc.).
Kotlin API Guide & Translations
All types reside in the package:
package io.github.kotlinmania.encodingrs
Core Types & Rust-to-Kotlin Mapping
Non-Streaming Decoding
The non-streaming API processes an entire ByteArray at once:
val encoding = Encoding.forLabel("windows-1252") ?: Encoding.UTF_8
val (text, actualEncoding, hadErrors) = encoding.decode(bytes)
val (textWithoutBom, hadErrors) = encoding.decodeWithBomRemoval(bytes)
val (rawText, hadErrors) = encoding.decodeWithoutBomHandling(bytes)
val strictText: String? = encoding.decodeWithoutBomHandlingAndWithoutReplacement(bytes)
Non-Streaming Encoding
The non-streaming API encodes a Kotlin String or CharArray into a ByteArray:
val encoding = Encoding.SHIFT_JIS
val (bytes, actualEncoding, hadErrors) = encoding.encode("こんにちは")
val (bytesFromChars, _, _) = encoding.encodeFromUtf16(charArrayOf('h', 'e', 'l', 'l', 'o'))
Streaming Decoding with Decoder
For streaming IO (files, sockets, HTTP response bodies), create a stateful Decoder:
val decoder = Encoding.UTF_8.newDecoder()
val bomStrippingDecoder = Encoding.UTF_8.newDecoderWithBomRemoval()
val rawDecoder = Encoding.UTF_8.newDecoderWithoutBomHandling()
Chunked Decoding to UTF-8 (String):
val decoder = Encoding.WINDOWS_1252.newDecoder()
val chunk = byteArrayOf(0x48, 0x65, 0x6C, 0x6C, 0x6F)
val outputBuilder = StringBuilder()
val result: DecodeResult = decoder.decodeToString(chunk, outputBuilder, last = false)
Chunked Decoding to Raw Buffers:
val dstChars = CharArray(1024)
val (coderResult, bytesRead, charsWritten, hadErrors) =
decoder.decodeToUtf16(chunk, dstChars, last = false)
Strict Streaming Decoding (Reporting Errors):
val dstChars = CharArray(1024)
val (decoderResult, bytesRead, charsWritten) =
decoder.decodeToUtf16WithoutReplacement(chunk, dstChars, last = false)
when (decoderResult) {
is DecoderResult.InputEmpty -> { }
is DecoderResult.OutputFull -> { }
is DecoderResult.Malformed -> {
println("Malformed sequence of length ${decoderResult.length}")
}
}
Streaming Encoding with Encoder
For streaming output to legacy encodings:
val encoder = Encoding.GBK.newEncoder()
val dstBytes = ByteArray(1024)
result: EncodeResult = encoder.encodeFromUtf8(, dstBytes, last = )
(encoderResult, charsRead, bytesWritten) =
encoder.encodeFromUtf8WithoutReplacement(, dstBytes, last = )
(encoderResult) {
EncoderResult.InputEmpty -> { }
EncoderResult.OutputFull -> { }
EncoderResult.Unmappable -> {
println()
}
}
Label Lookup & BOM Sniffing
Label Resolution:
Matches standard labels per WHATWG specification:
val enc1 = Encoding.forLabel("utf-8")
val enc2 = Encoding.forLabel(" CSISO2022JP ")
val enc3 = Encoding.forLabel("x-sjis")
val enc4 = Encoding.forLabel("latin1")
BOM Sniffing:
Inspects the start of a byte buffer for UTF-8, UTF-16LE, or UTF-16BE BOMs:
val buffer = byteArrayOf(0xEF.toByte(), 0xBB.toByte(), 0xBF.toByte(), 0x61, 0x62)
val match = Encoding.forBom(buffer)
if (match != null) {
val (encoding, bomLength) = match
println("Detected BOM: ${encoding.name}, length: $bomLength bytes")
}
Fast Validation Utilities:
val asciiLength = Encoding.asciiValidUpTo(byteArray)
val utf8Length = Encoding.utf8ValidUpTo(byteArray)
The Mem Module — In-Memory Fast Text Operations
The Mem singleton object (io.github.kotlinmania.encodingrs.Mem) provides high-speed in-memory operations on text buffers:
1. Character Set & Bidirectional (Bidi) Checks
2. Fast Conversions
Mem.convertUtf8ToUtf16(src: ByteArray, dst: CharArray): Int: Converts UTF-8 to UTF-16, replacing invalid sequences.
3. Validation & In-Place Sanitization
Mem.utf16ValidUpTo(buffer: CharArray): Int: Finds the first unmatched surrogate code unit.
Mem.ensureUtf16Validity(buffer: CharArray): In-place replaces lone surrogates with \uFFFD.
Mem.copyAscii(src: ByteArray, dst: ByteArray): Int: Copies ASCII bytes up to the first non-ASCII byte.
Supported Character Encodings
All 39 encodings from the WHATWG Encoding Standard are available as constants on Encoding:
Unicode & Special Encodings
Encoding.UTF_8 ("UTF-8")
Encoding.UTF_16LE ("UTF-16LE")
Encoding.UTF_16BE ("UTF-16BE")
Encoding.REPLACEMENT ("replacement")
Legacy Windows Code Pages
ISO 8859 Family
East Asian Encodings (CJK)
- Japanese:
Encoding.SHIFT_JIS, Encoding.EUC_JP, Encoding.ISO_2022_JP
- : , (including GB18030-2022 support),
Historical & Miscellaneous Encodings
Encoding.KOI8_R, Encoding.KOI8_U (Cyrillic)
Encoding.IBM866 (DOS Cyrillic)
Encoding.MACINTOSH, Encoding.X_MAC_CYRILLIC (Classic Mac OS)
Encoding.X_USER_DEFINED (Byte-preserving 8-bit mapping into Unicode PUA)
Code Examples
1. Robust Web Content Decoding
import io.github.kotlinmania.encodingrs.Encoding
fun decodeWebContent(payload: ByteArray, contentTypeCharset: String?): String {
val baseEncoding = contentTypeCharset?.let { Encoding.forLabel(it) } ?: Encoding.WINDOWS_1252
(content, actualEncoding, hadErrors) = baseEncoding.decode(payload)
(hadErrors) {
println()
}
content
}
2. Encoding to Legacy Format with Error Detection
import io.github.kotlinmania.encodingrs.Encoding
fun exportToShiftJis(text: String): ByteArray {
val (bytes, encoding, hadErrors) = Encoding.SHIFT_JIS.encode(text)
if (hadErrors) {
println("Some characters could not be represented in Shift_JIS and were replaced.")
}
return bytes
}
3. Swift Export Interop
When targeting Apple platforms, Kotlin Multiplatform's Swift Export provides native Swift wrappers:
import IoGithubKotlinmaniaEncodingRsKotlin
let encoding = ExportedKotlinPackages.io.github.kotlinmania.encodingrs.Encoding.UTF_8
let isAscii = ExportedKotlinPackages.io.github.kotlinmania.encodingrs.Mem.isAscii(buffer: myData)
Performance & Design Notes
- Optimized Lookup Tables: Tables for multibyte character encodings (EUC-JP, Shift_JIS, Big5, EUC-KR, GB18030) are compressed and indexed for fast binary and direct lookups.
- Fast UTF-8 & ASCII Paths: Processing paths inspect chunks of data to fast-forward through pure ASCII or valid UTF-8 sequences.
- Memory Safety & Multiplatform Portability: All operations are 100% memory-safe Kotlin with bounds checking and without raw memory pointer arithmetic or unverified casts.
Building & Testing
Swift Export and its test harness require macOS 15 or newer. The Swift
workflow uses the current template’s macOS 26 runner for its Xcode SDK.
This project uses standard Gradle multiplatform builds:
./gradlew test
./gradlew build
Acknowledgments & Attribution
This library is a direct Kotlin Multiplatform transliteration of encoding_rs written by Henri Sivonen.
We express our deepest gratitude and credit to:
This Kotlin port aims to bring that same standard of correctness, performance, and Web compatibility to the Kotlin and multiplatform ecosystem.
Licensing
encoding-rs-kotlin is licensed under the same terms as upstream encoding_rs:
- Code: Dual-licensed under either Apache License, Version 2.0 (LICENSE) or MIT License.
- WHATWG Data Tables: Portions generated from WHATWG specifications are licensed under the BSD 3-Clause License.
- Tests: Upstream test fixtures and tests are dedicated to the public domain under .
Original Rust implementation: Copyright (c) Henri Sivonen and Mozilla Corporation.
Kotlin Multiplatform port: Copyright (c) 2026 Sydney Renee and The Solace Project.