Taskcore
Encode and decode UTF-8
Also called UTF-8 encoder, UTF-8 decoder, utf8 encode, utf8 decode, validate UTF-8, overlong encoding, replacement character.
Turn a code point into its 1 to 4 UTF-8 bytes, and turn bytes back into a code point, with a rejection of each sequence that is not well formed.
- Evidence
- Code in 10 languages
Task
Encode a code point to UTF-8, and decode UTF-8 to a code point. The function encode_utf8(cp) returns the bytes of cp. For example, encode_utf8(0xE9) is [195, 169], and encode_utf8(0x1F642) is [240, 159, 153, 130]. The function decode_utf8(b) returns the code point of the one sequence in b, or -1 if b is not exactly one well-formed sequence.
The number of bytes comes from the code point:
| Code points | Bytes | Form |
|---|---|---|
| 0 to 0x7F | 1 | 0xxxxxxx |
| 0x80 to 0x7FF | 2 | 110xxxxx 10xxxxxx |
| 0x800 to 0xFFFF | 3 | 1110xxxx 10xxxxxx 10xxxxxx |
| 0x10000 to 0x10FFFF | 4 | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx |
"The definition of UTF-8 prohibits encoding character numbers between U+D800 and U+DFFF"1, so a surrogate is not a valid input or output. A decoder must also reject an overlong form, which uses more bytes than the table gives. To get the bytes of a whole string with a library, see Convert a string to bytes.
Solutions
| Language | Encode | Decode, with errors |
|---|---|---|
| Python | chr(cp).encode("utf-8") |
bytes(b).decode("utf-8") |
| JavaScript, TypeScript | new TextEncoder().encode(String.fromCodePoint(cp)) |
new TextDecoder("utf-8", { fatal: true }) |
| Java | Character.toString(cp).getBytes(UTF_8) |
a CharsetDecoder with CodingErrorAction.REPORT |
| C# | new UTF8Encoding(false, true).GetBytes |
new UTF8Encoding(false, true).GetString |
| Go | utf8.AppendRune(nil, cp) |
utf8.DecodeRune(b) |
| Rust | char::encode_utf8 |
std::str::from_utf8 |
| C, C++, Bash | the bit operations of the table | the bit operations, and the checks below |
The decoder in C, C++ and Bash does these checks:
- The first byte gives the length: below 0x80, from 0xC0, from 0xE0 or from 0xF0. A byte from 0x80 to 0xBF cannot start a sequence.
- The input has exactly that number of bytes, and each byte after the first has the form
10xxxxxx. - The code point is not below the smallest code point of its length, so an overlong form fails.
- The code point is not a surrogate and not above 0x10FFFF.
- Python. For
bytes.decode, "If 'strict' (the default), a UnicodeError exception is raised"2. - Go. For
DecodeRune, "An encoding is invalid if it is incorrect UTF-8, encodes a rune that is out of range, or is not the shortest possible UTF-8 encoding for the value"3. For an invalid input, "it returns (RuneError, 1)"3.
Edge cases
The encoder cases are in cases/basic.jsonl and cases/edge.jsonl, and the decoder cases are in cases/decode.jsonl.
one-byte-maxandtwo-byte-min: 0x7F is 1 byte, and 0x80 is 2 bytes. Each boundary of the table has a case on each side.max: 0x10FFFF is[244, 143, 191, 191], andabove-max,[244, 144, 128, 128], gives -1.replacement:[239, 191, 189]is a valid U+FFFD. It is not an error.overlong-twoandoverlong-three:[192, 129]and[224, 128, 128]use too many bytes, so they give -1.surrogate:[237, 160, 128]is U+D800, so it gives -1.stray-continuation,truncatedandbad-continuation: a sequence that starts with 0x80, ends too soon or has a wrong second byte gives -1.emptyandtwo-sequences: the input must be exactly one sequence.
Pitfalls
- Python errors="replace" hides bad input. The handler gives U+FFFD for each bad byte, so the error is lost. Use the default, "strict":
bad = b"\xff"
print(hex(ord(bad.decode("utf-8", errors="replace"))))
try:
bad.decode("utf-8")
except UnicodeDecodeError as e:
print(type(e).__name__)
0xfffd
UnicodeDecodeError
- JavaScript TextDecoder does not throw by default. The
fataloption "defaults to false, which means that the decoder will substitute malformed data with a replacement character"4:
const bad = new Uint8Array([0xc1, 0x81]);
const text = new TextDecoder().decode(bad);
console.log(Array.from(text, (c) => c.codePointAt(0).toString(16)).join(" "));
try {
new TextDecoder("utf-8", { fatal: true }).decode(bad);
} catch (e) {
console.log(e.name);
}
fffd fffd
TypeError
- Java new String(bytes, UTF_8) does not throw. "This method always replaces malformed-input and unmappable-character sequences with this charset's default replacement string"5. In the example, the 3 surrogate bytes become one U+FFFD. Use a
CharsetDecoderto get an error:
import java.nio.charset.StandardCharsets;
public class Main {
public static void main(String[] args) {
byte[] bad = {(byte) 0xed, (byte) 0xa0, (byte) 0x80};
String s = new String(bad, StandardCharsets.UTF_8);
StringBuilder out = new StringBuilder();
s.codePoints().forEach(c -> out.append(Integer.toHexString(c)).append(' '));
System.out.println(out.toString().trim());
}
}
fffd
- C# Encoding.UTF8 does not throw. In the example, it gives U+FFFD for a truncated sequence. The
UTF8Encodingconstructor has a parameter that controls "whether to throw an exception when an invalid encoding is detected"6:
using System;
using System.Text;
byte[] bad = { 0xC3 };
Console.WriteLine(((int)Encoding.UTF8.GetString(bad)[0]).ToString("X"));
try
{
new UTF8Encoding(false, true).GetString(bad);
}
catch (DecoderFallbackException e)
{
Console.WriteLine(e.GetType().Name);
}
FFFD
DecoderFallbackException
- Go string(b) does not check the bytes. The example makes a string from bytes that are not UTF-8, and no error occurs. A range loop then gives U+FFFD for the bad byte, and the code cannot tell it from a real U+FFFD. Use
utf8.Validorutf8.ValidString:
package main
import (
"fmt"
"strings"
"unicode/utf8"
)
func main() {
s := string([]byte{0x61, 0xff})
fmt.Println(len(s), utf8.ValidString(s))
var points []string
for _, r := range s {
points = append(points, fmt.Sprintf("%U", r))
}
fmt.Println(strings.Join(points, " "))
}
2 false
U+0061 U+FFFD
- Rust: the end of a buffer is not always an error.
Utf8Error::error_lengivesNonewhen "the end of the input was reached unexpectedly"7. In a stream, keep those bytes and add the next block.Some(1)is a real error:
fn main() {
let cut: &[u8] = &[0x61, 0xe2, 0x82];
let bad: &[u8] = &[0x61, 0xff, 0x62];
for b in [cut, bad] {
if let Err(e) = std::str::from_utf8(b) {
println!("{} {:?}", e.valid_up_to(), e.error_len());
}
}
}
1 None
1 Some(1)
- C: a decoder without the overlong check. "Implementations of the decoding algorithm above MUST protect against decoding invalid sequences"1. The naive decoder reads
C1 81as 65, the letterA. A filter that looks forAin the bytes does not find it:
#include <stdio.h>
// naive_decode reads a 2-byte sequence, but it does not check for an overlong form.
static unsigned naive_decode(const unsigned char *b) {
return ((b[0] & 0x1fu) << 6) | (b[1] & 0x3fu);
}
int main(void) {
const unsigned char overlong[] = {0xc1, 0x81};
unsigned cp = naive_decode(overlong);
printf("%u %s\n", cp, cp < 0x80 ? "overlong" : "ok");
return 0;
}
65 overlong
- C++ a cast to char is not an encoder.
static_cast<char>(0xE9)gives the 1 byte 0xE9, and a byte from 0xE0 starts a 3-byte sequence. Encode the code point to its 2 bytes:
#include <iostream>
#include <string>
int main() {
char32_t cp = U'\u00e9';
std::string cast(1, static_cast<char>(cp));
std::string utf8;
utf8 += static_cast<char>(0xc0 | (cp >> 6));
utf8 += static_cast<char>(0x80 | (cp & 0x3f));
std::cout << cast.size() << " " << static_cast<int>(static_cast<unsigned char>(cast[0])) << "\n";
std::cout << utf8.size() << " " << static_cast<int>(static_cast<unsigned char>(utf8[0])) << " "
<< static_cast<int>(static_cast<unsigned char>(utf8[1])) << "\n";
}
1 233
2 195 169
- Bash: a leading 0 is octal. "Constants with a leading 0 are interpreted as octal numbers"8. Byte values with a leading 0, for example from a 3-digit format, give wrong numbers. Use the
10#prefix:
b=010
echo "$((b)) $((10#$b))"
8 10
Related tasks
- Convert a string to bytes: the UTF-8 bytes of a whole string, with the library.
- Get the code point of a character: the code point of the first character of a string.
- Iterate over the characters of a string: decode each code point of a string in order.
- Find the length of a string: the number of bytes and the number of code points.
- UTF-8: the concept page of the UTF-8 encoding form.
Code
The build runs the native tests of each language in a pinned toolchain.
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/encode-and-decode-utf-8/.
def encode_utf8(cp: int) -> list[int]:
"""Return the UTF-8 bytes of the code point cp."""
return list(chr(cp).encode("utf-8"))
def decode_utf8(b: list[int]) -> int:
"""Return the code point of the one UTF-8 sequence in b, or -1.
The "strict" error handler raises UnicodeDecodeError for each sequence
that is not well formed, so overlong forms and surrogates give -1.
"""
try:
text = bytes(b).decode("utf-8", errors="strict")
except UnicodeDecodeError:
return -1
return ord(text) if len(text) == 1 else -1
test_utf8.py 51 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/encode-and-decode-utf-8/.
import pytest
from utf8 import decode_utf8, encode_utf8
# Each byte is a number from 0 to 255. A decode result of -1 means that the bytes are not one well-formed sequence.
ENCODE = {
"ascii-a": (0x41, [65]),
"euro": (0x20AC, [226, 130, 172]),
"emoji": (0x1F642, [240, 159, 153, 130]),
"nul": (0x0, [0]),
"one-byte-max": (0x7F, [127]),
"two-byte-min": (0x80, [194, 128]),
"two-byte": (0xE9, [195, 169]),
"two-byte-max": (0x7FF, [223, 191]),
"three-byte-min": (0x800, [224, 160, 128]),
"three-byte-max": (0xFFFF, [239, 191, 191]),
"four-byte-min": (0x10000, [240, 144, 128, 128]),
"max": (0x10FFFF, [244, 143, 191, 191]),
}
DECODE = {
"ascii-a": ([65], 65),
"e-acute": ([195, 169], 233),
"emoji": ([240, 159, 153, 130], 128578),
"max": ([244, 143, 191, 191], 1114111),
"replacement": ([239, 191, 189], 65533),
"empty": ([], -1),
"stray-continuation": ([128], -1),
"truncated": ([195], -1),
"bad-continuation": ([195, 40], -1),
"overlong-two": ([192, 129], -1),
"overlong-three": ([224, 128, 128], -1),
"surrogate": ([237, 160, 128], -1),
"above-max": ([244, 144, 128, 128], -1),
"two-sequences": ([65, 66], -1),
}
@pytest.mark.parametrize("name", ENCODE)
def test_encode_utf8(name):
cp, want = ENCODE[name]
assert encode_utf8(cp) == want
@pytest.mark.parametrize("name", DECODE)
def test_decode_utf8(name):
b, want = DECODE[name]
assert decode_utf8(b) == want
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/encode-and-decode-utf-8/.
#include "utf8.hpp"
std::vector<std::uint8_t> encode_utf8(std::uint32_t cp) {
auto u8 = [](std::uint32_t v) { return static_cast<std::uint8_t>(v); };
if (cp < 0x80) {
return {u8(cp)};
}
if (cp < 0x800) {
return {u8(0xc0 | (cp >> 6)), u8(0x80 | (cp & 0x3f))};
}
if (cp < 0x10000) {
return {u8(0xe0 | (cp >> 12)), u8(0x80 | ((cp >> 6) & 0x3f)), u8(0x80 | (cp & 0x3f))};
}
return {u8(0xf0 | (cp >> 18)), u8(0x80 | ((cp >> 12) & 0x3f)), u8(0x80 | ((cp >> 6) & 0x3f)),
u8(0x80 | (cp & 0x3f))};
}
// The first byte gives the length and the high bits. Each continuation byte
// must have the form 10xxxxxx. The result must be at least the smallest code
// point of its length, so an overlong form fails, and it must not be a
// surrogate or above 0x10FFFF.
long decode_utf8(const std::vector<std::uint8_t> &b) {
if (b.empty()) {
return -1;
}
std::uint8_t first = b[0];
std::size_t len = first < 0x80 ? 1 : first < 0xc0 ? 0 : first < 0xe0 ? 2 : first < 0xf0 ? 3 : first < 0xf8 ? 4 : 0;
if (len == 0 || b.size() != len) {
return -1;
}
constexpr std::uint32_t mins[] = {0, 0, 0x80, 0x800, 0x10000};
std::uint32_t cp = len == 1 ? first : first & (0x7fu >> len);
for (std::size_t i = 1; i < len; i++) {
if ((b[i] & 0xc0) != 0x80) {
return -1;
}
cp = (cp << 6) | (b[i] & 0x3fu);
}
if (cp < mins[len] || cp > 0x10ffff || (cp >= 0xd800 && cp <= 0xdfff)) {
return -1;
}
return static_cast<long>(cp);
}
utf8.hpp 14 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/encode-and-decode-utf-8/.
#pragma once
#include <cstdint>
#include <vector>
// encode_utf8 returns the 1 to 4 UTF-8 bytes of the code point cp. cp must be
// a Unicode scalar value.
std::vector<std::uint8_t> encode_utf8(std::uint32_t cp);
// decode_utf8 returns the code point of the one UTF-8 sequence in b, or -1 if
// b is not exactly one well-formed sequence.
long decode_utf8(const std::vector<std::uint8_t> &b);
test_utf8.cpp 60 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/encode-and-decode-utf-8/.
#include "utf8.hpp"
#include <cstdint>
#include <iostream>
#include <string_view>
#include <vector>
static int failures = 0;
static void check_encode(std::string_view name, std::uint32_t cp, const std::vector<std::uint8_t> &want) {
if (encode_utf8(cp) != want) {
std::cerr << "encode " << name << " fails\n";
failures++;
}
}
static void check_decode(std::string_view name, const std::vector<std::uint8_t> &b, long want) {
if (decode_utf8(b) != want) {
std::cerr << "decode " << name << " fails\n";
failures++;
}
}
// Each byte is a number from 0 to 255. A decode result of -1 means that the bytes are not one well-formed sequence.
int main() {
check_encode("ascii-a", 0x41, {65});
check_encode("euro", 0x20AC, {226, 130, 172});
check_encode("emoji", 0x1F642, {240, 159, 153, 130});
check_encode("nul", 0x0, {0});
check_encode("one-byte-max", 0x7F, {127});
check_encode("two-byte-min", 0x80, {194, 128});
check_encode("two-byte", 0xE9, {195, 169});
check_encode("two-byte-max", 0x7FF, {223, 191});
check_encode("three-byte-min", 0x800, {224, 160, 128});
check_encode("three-byte-max", 0xFFFF, {239, 191, 191});
check_encode("four-byte-min", 0x10000, {240, 144, 128, 128});
check_encode("max", 0x10FFFF, {244, 143, 191, 191});
check_decode("ascii-a", {65}, 65);
check_decode("e-acute", {195, 169}, 233);
check_decode("emoji", {240, 159, 153, 130}, 128578);
check_decode("max", {244, 143, 191, 191}, 1114111);
check_decode("replacement", {239, 191, 189}, 65533);
check_decode("empty", {}, -1);
check_decode("stray-continuation", {128}, -1);
check_decode("truncated", {195}, -1);
check_decode("bad-continuation", {195, 40}, -1);
check_decode("overlong-two", {192, 129}, -1);
check_decode("overlong-three", {224, 128, 128}, -1);
check_decode("surrogate", {237, 160, 128}, -1);
check_decode("above-max", {244, 144, 128, 128}, -1);
check_decode("two-sequences", {65, 66}, -1);
if (failures > 0) {
return 1;
}
std::cout << "all cases pass\n";
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/encode-and-decode-utf-8/.
import java.nio.ByteBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CodingErrorAction;
import java.nio.charset.StandardCharsets;
final class Utf8 {
private Utf8() {}
// encodeUtf8 returns the UTF-8 bytes of the code point cp, from 0 to 255.
static int[] encodeUtf8(int cp) {
byte[] b = Character.toString(cp).getBytes(StandardCharsets.UTF_8);
int[] out = new int[b.length];
for (int i = 0; i < b.length; i++) {
out[i] = b[i] & 0xff;
}
return out;
}
// decodeUtf8 returns the code point of the one UTF-8 sequence in b, or -1.
// new String(bytes, UTF_8) would replace bad input with U+FFFD, so the
// decoder reports each error instead.
static int decodeUtf8(int[] b) {
byte[] raw = new byte[b.length];
for (int i = 0; i < b.length; i++) {
raw[i] = (byte) b[i];
}
CharsetDecoder decoder =
StandardCharsets.UTF_8
.newDecoder()
.onMalformedInput(CodingErrorAction.REPORT)
.onUnmappableCharacter(CodingErrorAction.REPORT);
String s;
try {
s = decoder.decode(ByteBuffer.wrap(raw)).toString();
} catch (CharacterCodingException e) {
return -1;
}
return s.codePointCount(0, s.length()) == 1 ? s.codePointAt(0) : -1;
}
}
Utf8Test.java 59 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/encode-and-decode-utf-8/.
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
class Utf8Test {
// Each byte is a number from 0 to 255. A decode result of -1 means that the bytes are not one well-formed sequence.
static Stream<Arguments> encodeCases() {
return Stream.of(
Arguments.of("ascii-a", 0x41, new int[] {65}),
Arguments.of("euro", 0x20AC, new int[] {226, 130, 172}),
Arguments.of("emoji", 0x1F642, new int[] {240, 159, 153, 130}),
Arguments.of("nul", 0x0, new int[] {0}),
Arguments.of("one-byte-max", 0x7F, new int[] {127}),
Arguments.of("two-byte-min", 0x80, new int[] {194, 128}),
Arguments.of("two-byte", 0xE9, new int[] {195, 169}),
Arguments.of("two-byte-max", 0x7FF, new int[] {223, 191}),
Arguments.of("three-byte-min", 0x800, new int[] {224, 160, 128}),
Arguments.of("three-byte-max", 0xFFFF, new int[] {239, 191, 191}),
Arguments.of("four-byte-min", 0x10000, new int[] {240, 144, 128, 128}),
Arguments.of("max", 0x10FFFF, new int[] {244, 143, 191, 191}));
}
static Stream<Arguments> decodeCases() {
return Stream.of(
Arguments.of("ascii-a", new int[] {65}, 65),
Arguments.of("e-acute", new int[] {195, 169}, 233),
Arguments.of("emoji", new int[] {240, 159, 153, 130}, 128578),
Arguments.of("max", new int[] {244, 143, 191, 191}, 1114111),
Arguments.of("replacement", new int[] {239, 191, 189}, 65533),
Arguments.of("empty", new int[] {}, -1),
Arguments.of("stray-continuation", new int[] {128}, -1),
Arguments.of("truncated", new int[] {195}, -1),
Arguments.of("bad-continuation", new int[] {195, 40}, -1),
Arguments.of("overlong-two", new int[] {192, 129}, -1),
Arguments.of("overlong-three", new int[] {224, 128, 128}, -1),
Arguments.of("surrogate", new int[] {237, 160, 128}, -1),
Arguments.of("above-max", new int[] {244, 144, 128, 128}, -1),
Arguments.of("two-sequences", new int[] {65, 66}, -1));
}
@ParameterizedTest(name = "{0}")
@MethodSource("encodeCases")
void encodeUtf8(String name, int cp, int[] want) {
assertArrayEquals(want, Utf8.encodeUtf8(cp));
}
@ParameterizedTest(name = "{0}")
@MethodSource("decodeCases")
void decodeUtf8(String name, int[] b, int want) {
assertEquals(want, Utf8.decodeUtf8(b));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/encode-and-decode-utf-8/.
#include "utf8.h"
size_t encode_utf8(uint32_t cp, unsigned char out[4]) {
if (cp < 0x80) {
out[0] = (unsigned char)cp;
return 1;
}
if (cp < 0x800) {
out[0] = (unsigned char)(0xc0 | (cp >> 6));
out[1] = (unsigned char)(0x80 | (cp & 0x3f));
return 2;
}
if (cp < 0x10000) {
out[0] = (unsigned char)(0xe0 | (cp >> 12));
out[1] = (unsigned char)(0x80 | ((cp >> 6) & 0x3f));
out[2] = (unsigned char)(0x80 | (cp & 0x3f));
return 3;
}
out[0] = (unsigned char)(0xf0 | (cp >> 18));
out[1] = (unsigned char)(0x80 | ((cp >> 12) & 0x3f));
out[2] = (unsigned char)(0x80 | ((cp >> 6) & 0x3f));
out[3] = (unsigned char)(0x80 | (cp & 0x3f));
return 4;
}
// The first byte gives the length and the high bits. Each continuation byte
// must have the form 10xxxxxx. The result must be at least the smallest code
// point of its length, so an overlong form fails, and it must not be a
// surrogate or above 0x10FFFF.
long decode_utf8(const unsigned char *b, size_t n) {
if (n == 0) {
return -1;
}
size_t len;
uint32_t cp;
uint32_t min;
if (b[0] < 0x80) {
len = 1, cp = b[0], min = 0;
} else if (b[0] >= 0xc0 && b[0] < 0xe0) {
len = 2, cp = b[0] & 0x1f, min = 0x80;
} else if (b[0] >= 0xe0 && b[0] < 0xf0) {
len = 3, cp = b[0] & 0x0f, min = 0x800;
} else if (b[0] >= 0xf0 && b[0] < 0xf8) {
len = 4, cp = b[0] & 0x07, min = 0x10000;
} else {
return -1;
}
if (n != len) {
return -1;
}
for (size_t i = 1; i < len; i++) {
if ((b[i] & 0xc0) != 0x80) {
return -1;
}
cp = (cp << 6) | (b[i] & 0x3f);
}
if (cp < min || cp > 0x10ffff || (cp >= 0xd800 && cp <= 0xdfff)) {
return -1;
}
return (long)cp;
}
utf8.h 17 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/encode-and-decode-utf-8/.
#ifndef UTF8_H
#define UTF8_H
#include <stddef.h>
#include <stdint.h>
// encode_utf8 writes the 1 to 4 UTF-8 bytes of the code point cp to out, and
// returns the number of bytes. cp must be a Unicode scalar value.
size_t encode_utf8(uint32_t cp, unsigned char out[4]);
// decode_utf8 returns the code point of the one UTF-8 sequence in the n bytes
// of b, or -1 if the bytes are not exactly one well-formed sequence.
long decode_utf8(const unsigned char *b, size_t n);
#endif
test_utf8.c 61 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/encode-and-decode-utf-8/.
#include "utf8.h"
#include <stdio.h>
#include <string.h>
static int failures = 0;
static void check_encode(const char *name, uint32_t cp, const unsigned char *want, size_t n) {
unsigned char out[4];
size_t k = encode_utf8(cp, out);
if (k != n || memcmp(out, want, n) != 0) {
fprintf(stderr, "encode %s: got %zu bytes, want %zu\n", name, k, n);
failures++;
}
}
static void check_decode(const char *name, const unsigned char *b, size_t n, long want) {
long got = decode_utf8(b, n);
if (got != want) {
fprintf(stderr, "decode %s: got %ld, want %ld\n", name, got, want);
failures++;
}
}
// Each byte is a number from 0 to 255. A decode result of -1 means that the bytes are not one well-formed sequence.
int main(void) {
check_encode("ascii-a", 0x41, (const unsigned char[]){65}, 1);
check_encode("euro", 0x20AC, (const unsigned char[]){226, 130, 172}, 3);
check_encode("emoji", 0x1F642, (const unsigned char[]){240, 159, 153, 130}, 4);
check_encode("nul", 0x0, (const unsigned char[]){0}, 1);
check_encode("one-byte-max", 0x7F, (const unsigned char[]){127}, 1);
check_encode("two-byte-min", 0x80, (const unsigned char[]){194, 128}, 2);
check_encode("two-byte", 0xE9, (const unsigned char[]){195, 169}, 2);
check_encode("two-byte-max", 0x7FF, (const unsigned char[]){223, 191}, 2);
check_encode("three-byte-min", 0x800, (const unsigned char[]){224, 160, 128}, 3);
check_encode("three-byte-max", 0xFFFF, (const unsigned char[]){239, 191, 191}, 3);
check_encode("four-byte-min", 0x10000, (const unsigned char[]){240, 144, 128, 128}, 4);
check_encode("max", 0x10FFFF, (const unsigned char[]){244, 143, 191, 191}, 4);
check_decode("ascii-a", (const unsigned char[]){65}, 1, 65);
check_decode("e-acute", (const unsigned char[]){195, 169}, 2, 233);
check_decode("emoji", (const unsigned char[]){240, 159, 153, 130}, 4, 128578);
check_decode("max", (const unsigned char[]){244, 143, 191, 191}, 4, 1114111);
check_decode("replacement", (const unsigned char[]){239, 191, 189}, 3, 65533);
check_decode("empty", NULL, 0, -1);
check_decode("stray-continuation", (const unsigned char[]){128}, 1, -1);
check_decode("truncated", (const unsigned char[]){195}, 1, -1);
check_decode("bad-continuation", (const unsigned char[]){195, 40}, 2, -1);
check_decode("overlong-two", (const unsigned char[]){192, 129}, 2, -1);
check_decode("overlong-three", (const unsigned char[]){224, 128, 128}, 3, -1);
check_decode("surrogate", (const unsigned char[]){237, 160, 128}, 3, -1);
check_decode("above-max", (const unsigned char[]){244, 144, 128, 128}, 4, -1);
check_decode("two-sequences", (const unsigned char[]){65, 66}, 2, -1);
if (failures > 0) {
return 1;
}
printf("all cases pass\n");
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/encode-and-decode-utf-8/.
using System.Text;
public static class Utf8
{
// The second argument makes the decoder throw for bytes that are not
// well-formed UTF-8. Encoding.UTF8 would replace them with U+FFFD.
private static readonly UTF8Encoding Strict = new(false, true);
// EncodeUtf8 returns the UTF-8 bytes of the code point cp.
public static byte[] EncodeUtf8(int cp)
{
return Strict.GetBytes(char.ConvertFromUtf32(cp));
}
// DecodeUtf8 returns the code point of the one UTF-8 sequence in b, or -1.
public static int DecodeUtf8(byte[] b)
{
string s;
try
{
s = Strict.GetString(b);
}
catch (DecoderFallbackException)
{
return -1;
}
int count = 0;
int cp = -1;
foreach (Rune r in s.EnumerateRunes())
{
count++;
cp = r.Value;
}
return count == 1 ? cp : -1;
}
}
Utf8Tests.cs 58 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/encode-and-decode-utf-8/.
using Xunit;
public sealed class Utf8Tests
{
// Each byte is a number from 0 to 255. A decode result of -1 means that the bytes are not one well-formed sequence.
public static TheoryData<string, int, byte[]> EncodeCases => new()
{
{ "ascii-a", 0x41, new byte[] { 65 } },
{ "euro", 0x20AC, new byte[] { 226, 130, 172 } },
{ "emoji", 0x1F642, new byte[] { 240, 159, 153, 130 } },
{ "nul", 0x0, new byte[] { 0 } },
{ "one-byte-max", 0x7F, new byte[] { 127 } },
{ "two-byte-min", 0x80, new byte[] { 194, 128 } },
{ "two-byte", 0xE9, new byte[] { 195, 169 } },
{ "two-byte-max", 0x7FF, new byte[] { 223, 191 } },
{ "three-byte-min", 0x800, new byte[] { 224, 160, 128 } },
{ "three-byte-max", 0xFFFF, new byte[] { 239, 191, 191 } },
{ "four-byte-min", 0x10000, new byte[] { 240, 144, 128, 128 } },
{ "max", 0x10FFFF, new byte[] { 244, 143, 191, 191 } },
};
public static TheoryData<string, byte[], int> DecodeCases => new()
{
{ "ascii-a", new byte[] { 65 }, 65 },
{ "e-acute", new byte[] { 195, 169 }, 233 },
{ "emoji", new byte[] { 240, 159, 153, 130 }, 128578 },
{ "max", new byte[] { 244, 143, 191, 191 }, 1114111 },
{ "replacement", new byte[] { 239, 191, 189 }, 65533 },
{ "empty", new byte[] { }, -1 },
{ "stray-continuation", new byte[] { 128 }, -1 },
{ "truncated", new byte[] { 195 }, -1 },
{ "bad-continuation", new byte[] { 195, 40 }, -1 },
{ "overlong-two", new byte[] { 192, 129 }, -1 },
{ "overlong-three", new byte[] { 224, 128, 128 }, -1 },
{ "surrogate", new byte[] { 237, 160, 128 }, -1 },
{ "above-max", new byte[] { 244, 144, 128, 128 }, -1 },
{ "two-sequences", new byte[] { 65, 66 }, -1 },
};
[Theory]
[MemberData(nameof(EncodeCases))]
public void EncodeUtf8(string name, int cp, byte[] want)
{
Assert.NotNull(name);
Assert.Equal(want, Utf8.EncodeUtf8(cp));
}
[Theory]
[MemberData(nameof(DecodeCases))]
public void DecodeUtf8(string name, byte[] b, int want)
{
Assert.NotNull(name);
Assert.Equal(want, Utf8.DecodeUtf8(b));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/encode-and-decode-utf-8/.
// fatal: true makes decode throw a TypeError for bytes that are not well-formed
// UTF-8. ignoreBOM: true keeps a leading U+FEFF in the result.
const decoder = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
// encodeUtf8 returns the UTF-8 bytes of the code point cp.
export function encodeUtf8(cp) {
return Array.from(new TextEncoder().encode(String.fromCodePoint(cp)));
}
// decodeUtf8 returns the code point of the one UTF-8 sequence in b, or -1.
export function decodeUtf8(b) {
let s;
try {
s = decoder.decode(new Uint8Array(b));
} catch {
return -1;
}
const points = Array.from(s);
return points.length === 1 ? points[0].codePointAt(0) : -1;
}
utf8.test.js 52 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/encode-and-decode-utf-8/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { decodeUtf8, encodeUtf8 } from "./utf8.js";
// Each byte is a number from 0 to 255. A decode result of -1 means that the bytes are not one well-formed sequence.
const encodeCases = [
["ascii-a", 0x41, [65]],
["euro", 0x20AC, [226, 130, 172]],
["emoji", 0x1F642, [240, 159, 153, 130]],
["nul", 0x0, [0]],
["one-byte-max", 0x7F, [127]],
["two-byte-min", 0x80, [194, 128]],
["two-byte", 0xE9, [195, 169]],
["two-byte-max", 0x7FF, [223, 191]],
["three-byte-min", 0x800, [224, 160, 128]],
["three-byte-max", 0xFFFF, [239, 191, 191]],
["four-byte-min", 0x10000, [240, 144, 128, 128]],
["max", 0x10FFFF, [244, 143, 191, 191]],
];
const decodeCases = [
["ascii-a", [65], 65],
["e-acute", [195, 169], 233],
["emoji", [240, 159, 153, 130], 128578],
["max", [244, 143, 191, 191], 1114111],
["replacement", [239, 191, 189], 65533],
["empty", [], -1],
["stray-continuation", [128], -1],
["truncated", [195], -1],
["bad-continuation", [195, 40], -1],
["overlong-two", [192, 129], -1],
["overlong-three", [224, 128, 128], -1],
["surrogate", [237, 160, 128], -1],
["above-max", [244, 144, 128, 128], -1],
["two-sequences", [65, 66], -1],
];
for (const [name, cp, want] of encodeCases) {
test(`encode ${name}`, () => {
assert.deepEqual(encodeUtf8(cp), want);
});
}
for (const [name, b, want] of decodeCases) {
test(`decode ${name}`, () => {
assert.equal(decodeUtf8(b), want);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/encode-and-decode-utf-8/.
// fatal: true makes decode throw a TypeError for bytes that are not well-formed
// UTF-8. ignoreBOM: true keeps a leading U+FEFF in the result.
const decoder = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
// encodeUtf8 returns the UTF-8 bytes of the code point cp.
export function encodeUtf8(cp: number): number[] {
return Array.from(new TextEncoder().encode(String.fromCodePoint(cp)));
}
// decodeUtf8 returns the code point of the one UTF-8 sequence in b, or -1.
export function decodeUtf8(b: number[]): number {
let s;
try {
s = decoder.decode(new Uint8Array(b));
} catch {
return -1;
}
const points = Array.from(s);
return points.length === 1 ? points[0].codePointAt(0)! : -1;
}
utf8.test.ts 52 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/encode-and-decode-utf-8/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { decodeUtf8, encodeUtf8 } from "./utf8.ts";
// Each byte is a number from 0 to 255. A decode result of -1 means that the bytes are not one well-formed sequence.
const encodeCases: [string, number, number[]][] = [
["ascii-a", 0x41, [65]],
["euro", 0x20AC, [226, 130, 172]],
["emoji", 0x1F642, [240, 159, 153, 130]],
["nul", 0x0, [0]],
["one-byte-max", 0x7F, [127]],
["two-byte-min", 0x80, [194, 128]],
["two-byte", 0xE9, [195, 169]],
["two-byte-max", 0x7FF, [223, 191]],
["three-byte-min", 0x800, [224, 160, 128]],
["three-byte-max", 0xFFFF, [239, 191, 191]],
["four-byte-min", 0x10000, [240, 144, 128, 128]],
["max", 0x10FFFF, [244, 143, 191, 191]],
];
const decodeCases: [string, number[], number][] = [
["ascii-a", [65], 65],
["e-acute", [195, 169], 233],
["emoji", [240, 159, 153, 130], 128578],
["max", [244, 143, 191, 191], 1114111],
["replacement", [239, 191, 189], 65533],
["empty", [], -1],
["stray-continuation", [128], -1],
["truncated", [195], -1],
["bad-continuation", [195, 40], -1],
["overlong-two", [192, 129], -1],
["overlong-three", [224, 128, 128], -1],
["surrogate", [237, 160, 128], -1],
["above-max", [244, 144, 128, 128], -1],
["two-sequences", [65, 66], -1],
];
for (const [name, cp, want] of encodeCases) {
test(`encode ${name}`, () => {
assert.deepEqual(encodeUtf8(cp), want);
});
}
for (const [name, b, want] of decodeCases) {
test(`decode ${name}`, () => {
assert.equal(decodeUtf8(b), want);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/encode-and-decode-utf-8/.
// Package utf8codec encodes and decodes one UTF-8 sequence.
package utf8codec
import "unicode/utf8"
// EncodeUTF8 returns the UTF-8 bytes of the code point cp.
func EncodeUTF8(cp rune) []byte {
return utf8.AppendRune(nil, cp)
}
// DecodeUTF8 returns the code point of the one UTF-8 sequence in b, or -1.
// For bad input, utf8.DecodeRune returns (RuneError, 1). The bytes EF BF BD
// are a valid U+FFFD with the size 3, so the size tells the two cases apart.
func DecodeUTF8(b []byte) rune {
r, size := utf8.DecodeRune(b)
if size == 0 || size != len(b) || (r == utf8.RuneError && size == 1) {
return -1
}
return r
}
utf8_test.go 66 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/encode-and-decode-utf-8/.
package utf8codec
import (
"bytes"
"testing"
)
// Each byte is a number from 0 to 255. A decode result of -1 means that the bytes are not one well-formed sequence.
var encodeCases = []struct {
name string
cp rune
want []byte
}{
{"ascii-a", 0x41, []byte{65}},
{"euro", 0x20AC, []byte{226, 130, 172}},
{"emoji", 0x1F642, []byte{240, 159, 153, 130}},
{"nul", 0x0, []byte{0}},
{"one-byte-max", 0x7F, []byte{127}},
{"two-byte-min", 0x80, []byte{194, 128}},
{"two-byte", 0xE9, []byte{195, 169}},
{"two-byte-max", 0x7FF, []byte{223, 191}},
{"three-byte-min", 0x800, []byte{224, 160, 128}},
{"three-byte-max", 0xFFFF, []byte{239, 191, 191}},
{"four-byte-min", 0x10000, []byte{240, 144, 128, 128}},
{"max", 0x10FFFF, []byte{244, 143, 191, 191}},
}
var decodeCases = []struct {
name string
b []byte
want rune
}{
{"ascii-a", []byte{65}, 65},
{"e-acute", []byte{195, 169}, 233},
{"emoji", []byte{240, 159, 153, 130}, 128578},
{"max", []byte{244, 143, 191, 191}, 1114111},
{"replacement", []byte{239, 191, 189}, 65533},
{"empty", []byte{}, -1},
{"stray-continuation", []byte{128}, -1},
{"truncated", []byte{195}, -1},
{"bad-continuation", []byte{195, 40}, -1},
{"overlong-two", []byte{192, 129}, -1},
{"overlong-three", []byte{224, 128, 128}, -1},
{"surrogate", []byte{237, 160, 128}, -1},
{"above-max", []byte{244, 144, 128, 128}, -1},
{"two-sequences", []byte{65, 66}, -1},
}
func TestEncodeUTF8(t *testing.T) {
for _, c := range encodeCases {
if got := EncodeUTF8(c.cp); !bytes.Equal(got, c.want) {
t.Errorf("%s: got %v, want %v", c.name, got, c.want)
}
}
}
func TestDecodeUTF8(t *testing.T) {
for _, c := range decodeCases {
if got := DecodeUTF8(c.b); got != c.want {
t.Errorf("%s: got %d, want %d", c.name, got, c.want)
}
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/encode-and-decode-utf-8/.
/// Returns the UTF-8 bytes of the code point `cp`.
///
/// # Panics
///
/// Panics if `cp` is a surrogate or above 0x10FFFF.
pub fn encode_utf8(cp: u32) -> Vec<u8> {
let c = char::from_u32(cp).expect("a Unicode scalar value");
let mut buf = [0u8; 4];
c.encode_utf8(&mut buf).as_bytes().to_vec()
}
/// Returns the code point of the one UTF-8 sequence in `b`, or -1.
/// `std::str::from_utf8` returns an error for each sequence that is not well
/// formed.
pub fn decode_utf8(b: &[u8]) -> i64 {
let Ok(s) = std::str::from_utf8(b) else {
return -1;
};
let mut chars = s.chars();
match (chars.next(), chars.next()) {
(Some(c), None) => i64::from(u32::from(c)),
_ => -1,
}
}
tests/utf8_test.rs 49 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/encode-and-decode-utf-8/.
use algo_encode_and_decode_utf_8::{decode_utf8, encode_utf8};
// Each byte is a number from 0 to 255. A decode result of -1 means that the bytes are not one well-formed sequence.
#[test]
fn encode_cases() {
let cases: [(&str, u32, &[u8]); 12] = [
("ascii-a", 0x41, &[65]),
("euro", 0x20AC, &[226, 130, 172]),
("emoji", 0x1F642, &[240, 159, 153, 130]),
("nul", 0x0, &[0]),
("one-byte-max", 0x7F, &[127]),
("two-byte-min", 0x80, &[194, 128]),
("two-byte", 0xE9, &[195, 169]),
("two-byte-max", 0x7FF, &[223, 191]),
("three-byte-min", 0x800, &[224, 160, 128]),
("three-byte-max", 0xFFFF, &[239, 191, 191]),
("four-byte-min", 0x10000, &[240, 144, 128, 128]),
("max", 0x10FFFF, &[244, 143, 191, 191]),
];
for (name, cp, want) in cases {
assert_eq!(encode_utf8(cp), want, "{name}");
}
}
#[test]
fn decode_cases() {
let cases: [(&str, &[u8], i64); 14] = [
("ascii-a", &[65], 65),
("e-acute", &[195, 169], 233),
("emoji", &[240, 159, 153, 130], 128578),
("max", &[244, 143, 191, 191], 1114111),
("replacement", &[239, 191, 189], 65533),
("empty", &[], -1),
("stray-continuation", &[128], -1),
("truncated", &[195], -1),
("bad-continuation", &[195, 40], -1),
("overlong-two", &[192, 129], -1),
("overlong-three", &[224, 128, 128], -1),
("surrogate", &[237, 160, 128], -1),
("above-max", &[244, 144, 128, 128], -1),
("two-sequences", &[65, 66], -1),
];
for (name, b, want) in cases {
assert_eq!(decode_utf8(b), want, "{name}");
}
}
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/encode-and-decode-utf-8/.
# encode_utf8 CP: prints the UTF-8 bytes of the code point CP as decimal
# numbers, with one space between them.
encode_utf8() {
local cp=$(($1))
if ((cp < 0x80)); then
echo "$cp"
elif ((cp < 0x800)); then
echo "$((0xc0 | cp >> 6)) $((0x80 | (cp & 0x3f)))"
elif ((cp < 0x10000)); then
echo "$((0xe0 | cp >> 12)) $((0x80 | (cp >> 6 & 0x3f))) $((0x80 | (cp & 0x3f)))"
else
echo "$((0xf0 | cp >> 18)) $((0x80 | (cp >> 12 & 0x3f))) $((0x80 | (cp >> 6 & 0x3f))) $((0x80 | (cp & 0x3f)))"
fi
}
# decode_utf8 BYTE...: prints the code point of the one UTF-8 sequence in the
# arguments, or -1 if they are not exactly one well-formed sequence.
decode_utf8() {
local b0=${1:--1} len cp min i b
if ((b0 < 0)); then
echo -1
return
elif ((b0 < 0x80)); then
len=1 cp=$b0 min=0
elif ((b0 >= 0xc0 && b0 < 0xe0)); then
len=2 cp=$((b0 & 0x1f)) min=$((0x80))
elif ((b0 >= 0xe0 && b0 < 0xf0)); then
len=3 cp=$((b0 & 0x0f)) min=$((0x800))
elif ((b0 >= 0xf0 && b0 < 0xf8)); then
len=4 cp=$((b0 & 0x07)) min=$((0x10000))
else
echo -1
return
fi
if (($# != len)); then
echo -1
return
fi
shift
for b in "$@"; do
if (((b & 0xc0) != 0x80)); then
echo -1
return
fi
cp=$((cp << 6 | (b & 0x3f)))
done
if ((cp < min || cp > 0x10ffff || (cp >= 0xd800 && cp <= 0xdfff))); then
echo -1
return
fi
echo "$cp"
}
test_utf8.bats 50 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/encode-and-decode-utf-8/.
bats_require_minimum_version 1.5.0
setup() {
source "$BATS_TEST_DIRNAME/utf8.sh"
}
check_encode() { # check_encode CP WANT
run encode_utf8 "$1"
[ "$status" -eq 0 ]
[ "$output" = "$2" ]
}
check_decode() { # check_decode WANT BYTE...
local want=$1
shift
run decode_utf8 "$@"
[ "$status" -eq 0 ]
[ "$output" = "$want" ]
}
# The bytes are decimal numbers with one space between them.
@test "encode ascii-a" { check_encode 65 '65'; }
@test "encode euro" { check_encode 8364 '226 130 172'; }
@test "encode emoji" { check_encode 128578 '240 159 153 130'; }
@test "encode nul" { check_encode 0 '0'; }
@test "encode one-byte-max" { check_encode 127 '127'; }
@test "encode two-byte-min" { check_encode 128 '194 128'; }
@test "encode two-byte" { check_encode 233 '195 169'; }
@test "encode two-byte-max" { check_encode 2047 '223 191'; }
@test "encode three-byte-min" { check_encode 2048 '224 160 128'; }
@test "encode three-byte-max" { check_encode 65535 '239 191 191'; }
@test "encode four-byte-min" { check_encode 65536 '240 144 128 128'; }
@test "encode max" { check_encode 1114111 '244 143 191 191'; }
@test "decode ascii-a" { check_decode 65 65; }
@test "decode e-acute" { check_decode 233 195 169; }
@test "decode emoji" { check_decode 128578 240 159 153 130; }
@test "decode max" { check_decode 1114111 244 143 191 191; }
@test "decode replacement" { check_decode 65533 239 191 189; }
@test "decode empty" { check_decode -1; }
@test "decode stray-continuation" { check_decode -1 128; }
@test "decode truncated" { check_decode -1 195; }
@test "decode bad-continuation" { check_decode -1 195 40; }
@test "decode overlong-two" { check_decode -1 192 129; }
@test "decode overlong-three" { check_decode -1 224 128 128; }
@test "decode surrogate" { check_decode -1 237 160 128; }
@test "decode above-max" { check_decode -1 244 144 128 128; }
@test "decode two-sequences" { check_decode -1 65 66; }
References
- RFC 3629, UTF-8, a transformation format of ISO 10646, 3. UTF-8 definition; 10. Security Considerations
- The Python Standard Library, Built-in Types, bytes.decode
- Go standard library, package unicode/utf8, DecodeRune
- MDN Web Docs, TextDecoder() constructor, Parameters, fatal
- Java SE 25 API, Class String, String(byte[], Charset)
- .NET API reference, UTF8Encoding constructors, Overloads
- Rust standard library, struct std::str::Utf8Error, error_len
- Bash Reference Manual, 6.5 Shell Arithmetic
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (bash) | I0 not checked yet |
|
| Code (c) | I0 not checked yet |
|
| Code (cpp) | I0 not checked yet |
|
| Code (csharp) | I0 not checked yet |
|
| Code (go) | I0 not checked yet |
|
| Code (java) | I0 not checked yet |
|
| Code (javascript) | I0 not checked yet |
|
| Code (python) | I0 not checked yet |
|
| Code (rust) | I0 not checked yet |
|
| Code (typescript) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag 8PZDZM Edit this page History Report an error Markdown