Algorithm Search⌘K

Algorithmintro

UTF-8

Also called UTF-8 encoding.

Encode each scalar value in one to four bytes. The count of leading one bits in the first byte gives the length, and each continuation byte starts with the bits 10.

Time
Θ(n) worst · best
Space
O(1) extra
Where
n = the number of bytes of the encoded string
Properties
deterministiconlineiterative

UTF-8 is the encoding form of Unicode that writes each scalar value as a sequence of one to four bytes. The bytes 00 to 7F stand for themselves, so ASCII text is valid UTF-8 without change. In a longer sequence, the first byte says how many bytes follow, and every following byte has the form 10xxxxxx, so the code is a prefix code and a reader can find the start of a character from any position. UTF-8 is the encoding of most web pages and of the text files and APIs of most current systems.

In plain words

A computer stores text as bytes, and one byte holds only 256 values, but Unicode has more than a million code points. UTF-8 uses one byte for the common English letters, digits and signs, and two, three or four bytes for everything else.

Each byte says what role it plays. A byte that begins with the bit 0 is a whole character. A byte that begins with 110, 1110 or 11110 starts a character of two, three or four bytes. A byte that begins with 10 continues a character. The free bits of all the bytes, put together, give the number of the character.

Because the roles are visible in the bytes, a program can jump into the middle of a text and find the next character start, and a search for an English word never matches inside a longer character.

The problem

Encoding. The input is a scalar value cc, that is, an integer with 0≤c≤10FFFF0 \le c \le \mathtt{10FFFF} that is not in D800..DFFF. The output is its UTF-8 byte sequence.

Decoding. The input is a byte string BB of length nn. If BB is well-formed, the output is the sequence of scalar values that it encodes. If it is not, a strict decoder reports an error, and a replacing decoder writes U+FFFD REPLACEMENT CHARACTER for each bad piece and goes on.

Table 3-7 of the core specification lists all well-formed sequences. Each row is a product of byte ranges, and bytes after the second are always in 80..BF.

code points byte 1 byte 2 byte 3 byte 4
U+0000..U+007F 00..7F
U+0080..U+07FF C2..DF 80..BF
U+0800..U+0FFF E0 A0..BF 80..BF
U+1000..U+CFFF E1..EC 80..BF 80..BF
U+D000..U+D7FF ED 80..9F 80..BF
U+E000..U+FFFF EE..EF 80..BF 80..BF
U+10000..U+3FFFF F0 90..BF 80..BF 80..BF
U+40000..U+FFFFF F1..F3 80..BF 80..BF 80..BF
U+100000..U+10FFFF F4 80..8F 80..BF 80..BF

The bytes C0, C1 and F5..FF never occur. The narrow second byte ranges after E0, ED, F0 and F4 exclude the overlong forms, the surrogates and the values above 10FFFF.

The replacing decoder follows the practice of section 3.9.6: a maximal subpart (D93b) is the longest prefix of a well-formed sequence that starts at the current position, or a single byte if no well-formed sequence starts with that byte, and each maximal subpart becomes one U+FFFD. The standard recommends this practice but does not require it for conformance.

The algorithm

  1. UTF8-ENCODE(c)
  2. 1if c < 0x80 then return [c]
  3. 2if c < 0x800 then return [0xC0 OR (c >> 6), 0x80 OR (c AND 0x3F)]
  4. 3if c < 0x10000 then return [0xE0 OR (c >> 12), 0x80 OR ((c >> 6) AND 0x3F), 0x80 OR (c AND 0x3F)]
  5. 4return [0xF0 OR (c >> 18), 0x80 OR ((c >> 12) AND 0x3F), 0x80 OR ((c >> 6) AND 0x3F), 0x80 OR (c AND 0x3F)]
  6. UTF8-DECODE(B[0..n-1])
  7. 5out <- empty list; i <- 0
  8. 6while i < n do
  9. 7b <- B[i]
  10. 8if b < 0x80 then append b to out; i <- i + 1; continue
  11. 9(k, lo, hi) <- LEAD-INFO(b)
  12. 10if k = 0 then append 0xFFFD to out; i <- i + 1; continue
  13. 11c <- b AND (0x7F >> (k + 1)); j <- 1
  14. 12while j <= k do
  15. 13(lo2, hi2) <- (lo, hi) if j = 1 else (0x80, 0xBF)
  16. 14if i + j >= n or B[i + j] < lo2 or B[i + j] > hi2 then break
  17. 15c <- (c << 6) OR (B[i + j] AND 0x3F); j <- j + 1
  18. 16if j = k + 1 then append c to out else append 0xFFFD to out
  19. 17i <- i + j
  20. 18return out

LEAD-INFO(b)(b) reads Table 3-7. It returns the number kk of bytes that follow a first byte bb and the range lo..hilo..hi of the second byte, or k=0k = 0 if bb is in 80..C1 or F5..FF. Line L11 keeps the payload bits of the first byte: 5 bits for k=1k = 1, 4 for k=2k = 2 and 3 for k=3k = 3. Line L14 stops at the first byte that is missing or out of its range, and that byte is not consumed: it is read again as the start of the next sequence. A strict decoder raises an error at line L10 or in the else branch of line L16 instead of writing U+FFFD.

Example

Encode U+20AC EURO SIGN. It is at least 800 and below 10000, so line L3 applies. In binary, 20AC is 0010 000010 101100. The three bytes are 1110 0010, 10 000010 and 10 101100, that is, E2 82 AC.

text code points UTF-8 bytes
A U+0041 41
é U+00E9 C3 A9
€ U+20AC E2 82 AC
😀 U+1F600 F0 9F 98 80
U+10FFFF U+10FFFF F4 8F BF BF

Decode, with replacement, the 13 bytes 61 F1 80 80 E1 80 C2 62 80 63 80 BF 64.

bytes what happens output
61 ASCII U+0061
F1 80 80 F1 needs 3 more bytes, but E1 is not in 80..BF U+FFFD
E1 80 E1 needs 2 more bytes, but C2 is not in 80..BF U+FFFD
C2 C2 needs 1 more byte, but 62 is ASCII U+FFFD
62 ASCII U+0062
80 a continuation byte cannot start a sequence U+FFFD
63 ASCII U+0063
80 as above U+FFFD
BF as above U+FFFD
64 ASCII U+0064

The output is U+0061 U+FFFD U+FFFD U+FFFD U+0062 U+FFFD U+0063 U+FFFD U+FFFD U+0064, the same as Python's bytes.decode("utf-8", "replace"). The overlong form C0 AF of "/" gives two U+FFFD, because C0 starts no sequence, and the surrogate form ED A0 80 gives three, because A0 is out of range after ED.

Correctness

Each row of Table 3-7 is the set of encodings of one range of scalar values. Lines L1 to L4 put the payload bits of cc behind the fixed prefixes, and the range limits of the rows are the conditions that cc is in the range of its line, is not a surrogate and is at most 10FFFF. So encoding is a bijection from the scalar values onto the sequences of the table. No sequence is a proper prefix of another, because the first byte fixes the length. The decoder keeps the invariant that the bytes before ii have been turned into output and ii is the start of a sequence or of a maximal subpart. In each pass it either matches a whole row and writes the value of line L15, or stops at the first byte that cannot extend a prefix of a well-formed sequence. Because each row is a product of ranges, that prefix is the maximal subpart. Every pass moves ii forward by at least one byte. The full proof is in proofs/correctness.md.

Proof: UTF-8 encoding is a bijection onto Table 3-7, and the decoder replaces exactly the maximal subpartsfull

Claim. (a) For every Unicode scalar value cc, UTF8-ENCODE(c)(c) (lines L1 to L4) is a byte sequence of Table 3-7 of the core specification, and every sequence of the table is the encoding of exactly one scalar value. (b) For every byte string BB of length nn, UTF8-DECODE(B)(B) (lines L5 to L18) stops. If BB is well-formed UTF-8, the output is the sequence of scalar values that BB encodes. If not, the output has one U+FFFD for each maximal subpart (D93b) that the left-to-right scan meets, and the scalar values of the well-formed sequences between them.

Setup. Table 3-7 has nine rows. Each row is a product of byte ranges: a first byte range, a second byte range, and the range 0x80..0xBF for every later byte. The rows are 00..7F; C2..DF, 80..BF; E0, A0..BF, 80..BF; E1..EC, 80..BF, 80..BF; ED, 80..9F, 80..BF; EE..EF, 80..BF, 80..BF; F0, 90..BF, 80..BF, 80..BF; F1..F3, 80..BF, 80..BF, 80..BF; F4, 80..8F, 80..BF, 80..BF. The first byte ranges of the rows do not overlap, so the first byte fixes the row and the length. LEAD-INFO(b)(b) returns, for a first byte bb of a multi-byte row, the number kk of bytes after it and the range lo..hilo..hi of the second byte, and k=0k = 0 for the bytes 80..C1 and F5..FF, which start no row.

Lemma 1 (encoding). Let cc be a scalar value. Line L1 handles c<27c < 2^7 with one byte cc, which is in row 1. Line L2 handles 27≤c<2112^7 \le c < 2^{11}. The first byte is 110\mathtt{110} followed by the high 5 of the 11 bits of cc, and these 5 bits are at least 0001000010 because c≥27c \ge 2^7, so the first byte is in C2..DF. The second byte is 10\mathtt{10} followed by the low 6 bits. Line L3 handles 211≤c<2162^{11} \le c < 2^{16}, and the first byte is E0 plus the high 4 bits chc_h of the 16. If ch=0c_h = 0, then c≥211c \ge 2^{11} forces the next 6 bits to be at least 100000100000, so the second byte is in A0..BF. If ch=Dc_h = \mathtt{D}, then c<D800c < \mathtt{D800} (a scalar value is not a surrogate) forces those 6 bits below 100000100000, so the second byte is in 80..9F. Line L4 handles 216≤c≤10FFFF2^{16} \le c \le \mathtt{10FFFF}. The high 3 of the 21 bits are 0 to 4. If they are 0, then c≥216c \ge 2^{16} forces the next 6 bits to be at least 010000010000, so the second byte is in 90..BF. If they are 4, then c≤10FFFFc \le \mathtt{10FFFF} forces those 6 bits to be at most 001111001111, so the second byte is in 80..8F. In every case the bytes after the second are 10\mathtt{10} followed by 6 bits of cc. So the output is in the row for its length.

Conversely, a sequence of a row of length LL carries 77, 1111, 1616 or 2121 payload bits for L=1,2,3,4L = 1, 2, 3, 4, and the range limits of the row are exactly the conditions above in reverse. So its payload, read as a number, is a scalar value cc in the range of line L1, L2, L3 or L4, and that line writes the same bits back. Two different scalar values have different payload bits, so the map is injective, and by the converse it is onto. □\square

Lemma 2 (one step of the scan). Let 0≤i<n0 \le i < n and let b=B[i]b = B[i]. One iteration of the loop of line L6 does one of these things.

  1. b<80b < \mathtt{80} (line L8). B[i]B[i] alone is a sequence of row 1. The iteration outputs bb and sets i←i+1i \leftarrow i + 1.
  2. k=0k = 0 (line L10). bb is the first byte of no row, so no well-formed sequence starts at ii and the maximal subpart at ii is B[i]B[i] alone. The iteration outputs U+FFFD and sets i←i+1i \leftarrow i + 1.
  3. k≥1k \ge 1. The inner loop of lines L12 to L15 keeps this invariant: B[i…i+j−1]B[i \ldots i+j-1] is a prefix of a sequence of the row of bb, and cc holds its payload bits. Line L11 sets it up for j=1j = 1, and line L15 keeps it, because line L14 lets jj grow only when B[i+j]B[i+j] is in the range of position jj of the row. If the loop ends with j=k+1j = k + 1, the whole row matched, and by Lemma 1 the iteration outputs the scalar value that these k+1k + 1 bytes encode. If it ends at line L14 with j≤kj \le k, then B[i…i+j−1]B[i \ldots i+j-1] is a prefix of a well-formed sequence, and B[i…i+j]B[i \ldots i+j] is not, because byte i+ji + j is missing or out of range for its position. As each row is a product of ranges, any byte in the range is allowed whatever the earlier bytes are, so no longer prefix exists. So B[i…i+j−1]B[i \ldots i+j-1] is the maximal subpart at ii, and the iteration outputs one U+FFFD. In both cases line L17 sets i←i+ji \leftarrow i + j with j≥1j \ge 1.

Proof of (a). Lemma 1.

Proof of (b), termination. By Lemma 2, every iteration of the outer loop raises ii by at least 1, and the inner loop runs at most k≤3k \le 3 times. So the loop of line L6 runs at most nn times and the procedure stops at line L18.

Proof of (b), output. If BB is well-formed, it is a concatenation of sequences of the table. No sequence of the table is a proper prefix of another, because the first byte fixes the length. So by induction on the number of iterations, each iteration starts at the first byte of one of these sequences, and by case 1 or case 3 of Lemma 2 it outputs the scalar value of that sequence and moves to the next one. If BB is ill-formed, the same lemma shows that each iteration either outputs one whole well-formed sequence or one U+FFFD for the maximal subpart at the current position, and then resumes right after it. This is the practice of section 3.9.6, "U+FFFD Substitution of Maximal Subparts". In strict mode, the first case 2, or case 3 with j≤kj \le k, raises an error whose bounds are ii and i+ji + j, the bounds of that maximal subpart. ■\blacksquare

Corollary (order). For scalar values c<dc < d, the encoding of cc is smaller than the encoding of dd in the byte-wise lexicographic order. If the two encodings have the same length, their bytes hold the payload bits from high to low behind the same fixed prefixes, so the first byte that differs compares like cc and dd. If cc has the shorter encoding, its first byte is smaller, because the first byte ranges of rows of length 1, 2, 3, 4 are 00..7F, C2..DF, E0..EF and F0..F4, in this order.

Complexity

In the word-RAM model, with nn the number of bytes:

  • Encoding costs O(1)O(1) per code point, and the output has 1 to 4 bytes per code point.
  • Decoding reads each byte at most twice: once inside a sequence, and once more if it ended a failed sequence at line L14. So it takes Θ(n)\Theta(n) time, and the output has at most nn code points.
  • Space. Besides the output, both use O(1)O(1) space.
claim value
bytes per code point 1 for U+0000..U+007F, 2 up to U+07FF, 3 up to U+FFFF, 4 up to U+10FFFF
decoding time Θ(n)\Theta(n)
U+FFFD per maximal subpart exactly 1

Branch-free decoders that work on one byte at a time, and vectorized validators that check 16 to 64 bytes per step, have the same asymptotic cost with much smaller constants.

Properties

  • ASCII-compatible. The bytes 00..7F encode only U+0000..U+007F, and they never occur inside a longer sequence. A program that looks for "/" or for a zero byte works on UTF-8 without change.
  • Self-synchronizing. A continuation byte has the form 10xxxxxx and a first byte does not, so from any position at most 3 steps back reach the start of the code point. The function code_point_start does this, and the test test_code_point_start checks it.
  • Prefix code. No encoding is a prefix of another, so a byte search for a well-formed string finds only matches that start and end at character boundaries.
  • Order-preserving. Sorting UTF-8 strings byte by byte sorts them by code point. The test test_byte_order_is_code_point_order checks this. UTF-16 does not have this property.
  • No byte order. The unit is a byte, so there are no big-endian and little-endian forms. A leading EF BB BF (the encoding of U+FEFF) is allowed but carries no information.
  • Size. Text in Latin script takes little more than 1 byte per character, and Chinese, Japanese and Korean text 3 bytes per character, where UTF-16 needs 2.

Variants and improvements

  • Original UTF-8 (RFC 2279). It allowed sequences of up to 6 bytes for values up to 7FFFFFFF. RFC 3629 limited UTF-8 to 4 bytes and 10FFFF, the range of UTF-16.
  • Modified UTF-8. Java's serialization and JNI write U+0000 as C0 80 and code points above U+FFFF as two 3-byte sequences, one for each UTF-16 surrogate. It is not UTF-8, and a strict decoder rejects it.
  • CESU-8. The same treatment of supplementary code points as Modified UTF-8, but U+0000 is the byte 00.
  • WTF-8 and surrogatepass. They allow the 3-byte forms of lone surrogates, so that any sequence of 16-bit units, valid or not, survives a round trip. Python's error handler "surrogatepass" encodes U+D800 as ED A0 80.
  • DFA decoding. A deterministic finite automaton with 8 states and a reject state accepts exactly the well-formed byte strings. The states are "at a sequence start", "1, 2 or 3 bytes still needed", and the four states for the narrow second byte ranges after E0, ED, F0 and F4. A table-driven decoder runs it with one lookup per byte.
  • SIMD validation. The Keiser-Lemire validator checks the same rules with vector table lookups on nibbles.

When to use it

Use UTF-8 for files, network protocols and the storage of text unless an interface demands another form. It is the required encoding of JSON text exchanged between systems, and the default of HTML5, XML and most programming languages. Use UTF-16 when an API (Windows, Java, JavaScript) already holds text in it. Use UTF-32 inside a program when you need O(1)O(1) access to the iith code point, and remember that the iith code point is not the iith grapheme cluster. For domain names, which must be ASCII, use Punycode.

Pitfalls

  • Overlong forms. A lax decoder that only reads the payload bits accepts C0 AF as "/" and C0 AE as ".". RFC 3629 section 10 describes a check that rejects the bytes 2F 2E 2E 2F ("/../") but lets 2F C0 AE 2E 2F through, which such a decoder then reads as "/../". The rows of Table 3-7 forbid these forms, and the test test_replacement_check_values checks them.
  • Surrogates and large values. ED A0 80 (U+D800) and F4 90 80 80 (above 10FFFF) are ill-formed. A decoder that only counts the leading one bits lets them through.
  • Truncated input. A buffer can end inside a sequence. A streaming decoder must keep up to 3 bytes for the next buffer, not replace them with U+FFFD.
  • Different numbers of U+FFFD. Section 3.9.6 is not required for conformance, and other decoders write one U+FFFD per bad byte or per bad run. Do not compare replaced output between libraries.
  • Length in bytes is not length in characters. Cutting a UTF-8 string after a fixed number of bytes can split a code point. Move the cut back to a code point start, and better to a grapheme cluster boundary.
  • Encoding lone surrogates. A Python str can hold U+D800. encode("utf-8") raises an error for it, and the test test_surrogates_rejected_or_passed checks this and the "surrogatepass" form.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

utf_8.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/utf-8/. The authors are listed in prov/59B85A.jsonl.

"""UTF-8 encoding and decoding, as in The Unicode Standard 16.0.0, section 3.9 (D92, Table 3-7).

The decoder replaces each maximal subpart of an ill-formed sequence (D93b) with one
U+FFFD, the practice of section 3.9.6. Python's bytes.decode("utf-8", "replace") follows
the same practice, so the tests use it as the oracle.
"""

REPLACEMENT = 0xFFFD


class UTF8Error(ValueError):
    """Raised by strict decoding. start and end delimit the maximal subpart (bytes)."""

    def __init__(self, start: int, end: int) -> None:
        super().__init__(f"ill-formed UTF-8 at bytes {start}..{end - 1}")
        self.start = start
        self.end = end


def lead_info(b: int) -> tuple[int, int, int]:
    """Return (k, lo, hi) for a first byte b, from Table 3-7.

    k is the number of continuation bytes, and lo..hi is the range of the second byte.
    k = 0 means that b is not a legal first byte of a multi-byte sequence.
    """
    if 0xC2 <= b <= 0xDF:
        return 1, 0x80, 0xBF
    if b == 0xE0:
        return 2, 0xA0, 0xBF  # no overlong 3-byte forms
    if b == 0xED:
        return 2, 0x80, 0x9F  # no surrogates D800..DFFF
    if 0xE1 <= b <= 0xEF:
        return 2, 0x80, 0xBF
    if b == 0xF0:
        return 3, 0x90, 0xBF  # no overlong 4-byte forms
    if 0xF1 <= b <= 0xF3:
        return 3, 0x80, 0xBF
    if b == 0xF4:
        return 3, 0x80, 0x8F  # nothing above 10FFFF
    return 0, 0, 0  # 80..BF, C0, C1, F5..FF


def encode_code_point(c: int, allow_surrogates: bool = False) -> bytes:
    """Return the UTF-8 bytes of the scalar value c.

    With allow_surrogates, a surrogate code point gets the 3-byte form that the
    rest of the formula gives (ED A0 80 for D800). That is not UTF-8; it is what
    Python calls "surrogatepass".
    """
    if not 0 <= c <= 0x10FFFF:
        raise ValueError(f"{c:#x} is not a code point")
    if 0xD800 <= c <= 0xDFFF and not allow_surrogates:
        raise ValueError(f"U+{c:04X} is a surrogate, not a scalar value")
    if c < 0x80:  # @line L1
        return bytes([c])
    if c < 0x800:  # @line L2
        return bytes([0xC0 | (c >> 6), 0x80 | (c & 0x3F)])
    if c < 0x10000:  # @line L3
        return bytes([0xE0 | (c >> 12), 0x80 | ((c >> 6) & 0x3F), 0x80 | (c & 0x3F)])
    return bytes([0xF0 | (c >> 18), 0x80 | ((c >> 12) & 0x3F),  # @line L4
                  0x80 | ((c >> 6) & 0x3F), 0x80 | (c & 0x3F)])


def encode(s: str, allow_surrogates: bool = False) -> bytes:
    """Encode a Python str (a sequence of code points) as UTF-8."""
    return b"".join(encode_code_point(ord(ch), allow_surrogates) for ch in s)


def decode_code_points(data: bytes, errors: str = "replace") -> list[int]:
    """Decode data to a list of code points.

    errors="replace" puts one U+FFFD for each maximal subpart; errors="strict"
    raises UTF8Error at the first ill-formed subsequence.
    """
    out: list[int] = []
    n = len(data)
    i = 0  # @line L5
    while i < n:  # @line L6
        b = data[i]  # @line L7
        if b < 0x80:  # @line L8
            out.append(b)
            i += 1
            continue
        k, lo, hi = lead_info(b)  # @line L9
        if k == 0:  # @line L10
            if errors == "strict":
                raise UTF8Error(i, i + 1)
            out.append(REPLACEMENT)
            i += 1
            continue
        c = b & (0x7F >> (k + 1))  # @line L11
        j = 1
        while j <= k:  # @line L12
            lo2, hi2 = (lo, hi) if j == 1 else (0x80, 0xBF)  # @line L13
            if i + j >= n or not lo2 <= data[i + j] <= hi2:  # @line L14
                break
            c = (c << 6) | (data[i + j] & 0x3F)  # @line L15
            j += 1
        if j == k + 1:  # @line L16
            out.append(c)
        else:
            if errors == "strict":
                raise UTF8Error(i, i + j)
            out.append(REPLACEMENT)
        i += j  # @line L17
    return out  # @line L18


def decode(data: bytes, errors: str = "replace") -> str:
    """Decode UTF-8 bytes to a str."""
    return "".join(map(chr, decode_code_points(data, errors)))


def is_valid(data: bytes) -> bool:
    """Return True if data is well-formed UTF-8 (Table 3-7)."""
    try:
        decode_code_points(data, "strict")
    except UTF8Error:
        return False
    return True


def code_point_start(data: bytes, i: int) -> int:
    """Return the start of the code point that holds byte i of well-formed data.

    A continuation byte has the form 10xxxxxx, so at most 3 steps back are needed.
    """
    j = i
    while j > 0 and i - j < 3 and data[j] & 0xC0 == 0x80:
        j -= 1
    return j
test_utf_8.py 117 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/utf-8/. The authors are listed in prov/59B85A.jsonl.

# The oracle is Python's own codec: str.encode("utf-8") and bytes.decode("utf-8").
# Written against Python 3.14, unicodedata.unidata_version 16.0.0. The UTF-8 rules do not
# depend on the Unicode version.

import itertools
import random

from utf_8 import UTF8Error, code_point_start, decode, decode_code_points, encode, encode_code_point, is_valid

BOUNDARY = [0x00, 0x7F, 0x80, 0x8F, 0x90, 0x9F, 0xA0, 0xBF, 0xC0, 0xC1, 0xC2, 0xDF,
            0xE0, 0xED, 0xEF, 0xF0, 0xF4, 0xF5, 0xFF]


def strict_oracle(b: bytes):
    try:
        return b.decode("utf-8")
    except UnicodeDecodeError as e:
        return (e.start, e.end)


def mine_strict(b: bytes):
    try:
        return decode(b, "strict")
    except UTF8Error as e:
        return (e.start, e.end)


def check(b: bytes) -> None:
    assert mine_strict(b) == strict_oracle(b), b.hex(" ")
    assert decode(b) == b.decode("utf-8", "replace"), b.hex(" ")
    assert is_valid(b) == (not isinstance(strict_oracle(b), tuple))


def test_check_values() -> None:
    table = {0x41: "41", 0xE9: "C3 A9", 0x20AC: "E2 82 AC", 0x800: "E0 A0 80", 0xFFFF: "EF BF BF",
             0x10000: "F0 90 80 80", 0x1F600: "F0 9F 98 80", 0x10FFFF: "F4 8F BF BF"}
    for c, h in table.items():
        assert encode_code_point(c) == bytes.fromhex(h)
        assert decode_code_points(bytes.fromhex(h)) == [c]


def test_replacement_check_values() -> None:
    counts = {"ED A0 80": 3, "C0 AF": 2, "F4 90 80 80": 4, "E0 80 80": 3, "F0 9F 98": 1, "E2 82": 1, "80": 1}
    for h, k in counts.items():
        assert decode(bytes.fromhex(h)) == "�" * k
    assert decode(bytes.fromhex("E1 80 41")) == "�A"


def test_encode_boundaries_and_sample() -> None:
    points = [0, 0x7F, 0x80, 0x7FF, 0x800, 0xD7FF, 0xE000, 0xFFFF, 0x10000, 0x10FFFF]
    rng = random.Random(1)
    points += [rng.choice([rng.randrange(0xD800), rng.randrange(0xE000, 0x110000)]) for _ in range(3000)]
    for c in points:
        assert encode_code_point(c) == chr(c).encode("utf-8")
        assert decode(encode_code_point(c)) == chr(c)
    lengths = [len(encode_code_point(c)) for c in (0x7F, 0x80, 0x7FF, 0x800, 0xFFFF, 0x10000)]
    assert lengths == [1, 2, 2, 3, 3, 4]


def test_surrogates_rejected_or_passed() -> None:
    for c in (0xD800, 0xDBFF, 0xDC00, 0xDFFF):
        try:
            encode_code_point(c)
            raise AssertionError("a surrogate must not encode")
        except ValueError:
            pass
        assert encode_code_point(c, allow_surrogates=True) == chr(c).encode("utf-8", "surrogatepass")
        assert not is_valid(chr(c).encode("utf-8", "surrogatepass"))


def test_all_short_sequences_over_boundary_bytes() -> None:
    for k in range(1, 4):
        for t in itertools.product(BOUNDARY, repeat=k):
            check(bytes(t))


def test_all_byte_strings_of_length_at_most_two() -> None:
    for a in range(256):
        check(bytes([a]))
        for b in range(256):
            check(bytes([a, b]))


def test_random_byte_strings() -> None:
    rng = random.Random(2)
    pool = BOUNDARY + list(range(0x20, 0x7F, 7))
    for _ in range(3000):
        check(bytes(rng.choice(pool) for _ in range(rng.randrange(1, 12))))


def test_valid_text_with_one_byte_changed() -> None:
    rng = random.Random(3)
    for _ in range(1000):
        s = "".join(chr(rng.choice([rng.randrange(0x80), rng.randrange(0x80, 0x800), rng.randrange(0xE000, 0x10000),
                                    rng.randrange(0x10000, 0x110000)])) for _ in range(6))
        b = bytearray(encode(s))
        assert bytes(b) == s.encode("utf-8") and decode(bytes(b), "strict") == s
        b[rng.randrange(len(b))] = rng.randrange(256)
        check(bytes(b))


def test_code_point_start() -> None:
    s = "aé€😀"
    b = encode(s)
    starts = [code_point_start(b, i) for i in range(len(b))]
    assert starts == [0, 1, 1, 3, 3, 3, 6, 6, 6, 6]


def test_byte_order_is_code_point_order() -> None:
    rng = random.Random(4)
    for _ in range(2000):
        x = "".join(chr(rng.choice([rng.randrange(0xD800), rng.randrange(0xE000, 0x110000)])) for _ in range(2))
        y = "".join(chr(rng.choice([rng.randrange(0xD800), rng.randrange(0xE000, 0x110000)])) for _ in range(2))
        assert (encode(x) < encode(y)) == ([ord(c) for c in x] < [ord(c) for c in y])

History

Ken Thompson designed UTF-8 with Rob Pike in September 1992, as an improvement on a proposal of X/Open for a file system safe transformation format of the Universal Character Set. The goals were ASCII compatibility, no zero bytes or "/" inside multi-byte sequences, self-synchronization, and a first byte that gives the length. Their Plan 9 system changed to it soon after, and Pike and Thompson described it in their paper at the USENIX Winter 1993 conference. RFC 2044 (1996) and RFC 2279 (1998) registered it for Internet use with sequences of up to 6 bytes. RFC 3629 (2003) restricted it to the 4-byte range that UTF-16 can also reach, and Unicode defines the same set of sequences in D92 and Table 3-7.

References

  1. The Unicode Consortium, The Unicode Standard, Version 16.0.0, 2024, Chapter 3, Section 3.9 Unicode Encoding Forms: D92 (UTF-8), Table 3-7 (well-formed UTF-8 byte sequences), D93b (maximal subpart) and Section 3.9.6 U+FFFD Substitution of Maximal Subparts
  2. F. Yergeau, UTF-8, a transformation format of ISO 10646, RFC 3629, November 2003, Section 3 (UTF-8 definition), Section 4 (Syntax of UTF-8 byte sequences) and Section 10 (Security considerations)
  3. The Unicode Standard, Version 16.0.0, core specification (online), Chapter 3, Section 3.9
  4. Python documentation, codecs, Error Handlers (strict, replace, surrogatepass)

Where this leads

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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • History with a source
  • a scene preset for the example