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
- Model
- Word RAM
- Properties
- deterministiconlineiterative
- Evidence
- Proof sketchCode in 1 languages
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 , that is, an integer with that is not in D800..DFFF. The output is its UTF-8 byte sequence.
Decoding. The input is a byte string of length . If 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
UTF8-ENCODE(c)- 1
if c < 0x80 then return [c] - 2
if c < 0x800 then return [0xC0 OR (c >> 6), 0x80 OR (c AND 0x3F)] - 3
if c < 0x10000 then return [0xE0 OR (c >> 12), 0x80 OR ((c >> 6) AND 0x3F), 0x80 OR (c AND 0x3F)] - 4
return [0xF0 OR (c >> 18), 0x80 OR ((c >> 12) AND 0x3F), 0x80 OR ((c >> 6) AND 0x3F), 0x80 OR (c AND 0x3F)] UTF8-DECODE(B[0..n-1])- 5
out <- empty list; i <- 0 - 6
while i < n do - 7
b <- B[i] - 8
if b < 0x80 then append b to out; i <- i + 1; continue - 9
(k, lo, hi) <- LEAD-INFO(b) - 10
if k = 0 then append 0xFFFD to out; i <- i + 1; continue - 11
c <- b AND (0x7F >> (k + 1)); j <- 1 - 12
while j <= k do - 13
(lo2, hi2) <- (lo, hi) if j = 1 else (0x80, 0xBF) - 14
if i + j >= n or B[i + j] < lo2 or B[i + j] > hi2 then break - 15
c <- (c << 6) OR (B[i + j] AND 0x3F); j <- j + 1 - 16
if j = k + 1 then append c to out else append 0xFFFD to out - 17
i <- i + j - 18
return out
LEAD-INFO reads Table 3-7. It returns the number of bytes that follow a first byte and the range of the second byte, or if is in 80..C1 or F5..FF. Line L11 keeps the payload bits of the first byte: 5 bits for , 4 for and 3 for . 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 behind the fixed prefixes, and the range limits of the rows are the conditions that 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 have been turned into output and 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 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 , UTF8-ENCODE (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 of length , UTF8-DECODE (lines L5 to L18) stops. If is well-formed UTF-8, the output is the sequence of scalar values that 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 returns, for a first byte of a multi-byte row, the number of bytes after it and the range of the second byte, and for the bytes 80..C1 and F5..FF, which start no row.
Lemma 1 (encoding). Let be a scalar value. Line L1 handles with one byte , which is in row 1. Line L2 handles . The first byte is followed by the high 5 of the 11 bits of , and these 5 bits are at least because , so the first byte is in C2..DF. The second byte is followed by the low 6 bits. Line L3 handles , and the first byte is E0 plus the high 4 bits of the 16. If , then forces the next 6 bits to be at least , so the second byte is in A0..BF. If , then (a scalar value is not a surrogate) forces those 6 bits below , so the second byte is in 80..9F. Line L4 handles . The high 3 of the 21 bits are 0 to 4. If they are 0, then forces the next 6 bits to be at least , so the second byte is in 90..BF. If they are 4, then forces those 6 bits to be at most , so the second byte is in 80..8F. In every case the bytes after the second are followed by 6 bits of . So the output is in the row for its length.
Conversely, a sequence of a row of length carries , , or payload bits for , 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 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.
Lemma 2 (one step of the scan). Let and let . One iteration of the loop of line L6 does one of these things.
- (line L8). alone is a sequence of row 1. The iteration outputs and sets .
- (line L10). is the first byte of no row, so no well-formed sequence starts at and the maximal subpart at is alone. The iteration outputs U+FFFD and sets .
- . The inner loop of lines L12 to L15 keeps this invariant: is a prefix of a sequence of the row of , and holds its payload bits. Line L11 sets it up for , and line L15 keeps it, because line L14 lets grow only when is in the range of position of the row. If the loop ends with , the whole row matched, and by Lemma 1 the iteration outputs the scalar value that these bytes encode. If it ends at line L14 with , then is a prefix of a well-formed sequence, and is not, because byte 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 is the maximal subpart at , and the iteration outputs one U+FFFD. In both cases line L17 sets with .
Proof of (a). Lemma 1.
Proof of (b), termination. By Lemma 2, every iteration of the outer loop raises by at least 1, and the inner loop runs at most times. So the loop of line L6 runs at most times and the procedure stops at line L18.
Proof of (b), output. If 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 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 , raises an error whose bounds are and , the bounds of that maximal subpart.
Corollary (order). For scalar values , the encoding of is smaller than the encoding of 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 and . If 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 the number of bytes:
- Encoding costs 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 time, and the output has at most code points.
- Space. Besides the output, both use 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 | |
| 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_startdoes this, and the testtest_code_point_startchecks 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_orderchecks 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 access to the th code point, and remember that the th code point is not the th 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_valueschecks 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
strcan hold U+D800.encode("utf-8")raises an error for it, and the testtest_surrogates_rejected_or_passedchecks 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.
# 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
- 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
- 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)
- The Unicode Standard, Version 16.0.0, core specification (online), Chapter 3, Section 3.9
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 59B85A Edit this page History Report an error Markdown