Algorithm Search⌘K

Algorithmresearch

Keiser-Lemire UTF-8 validation

Also called SIMD UTF-8 validation.

Validate UTF-8 with vector table lookups on the nibbles of each byte and of the byte before it. The authors measured under 0.4 instructions per byte on AVX2 hardware.

Time
Θ(n / W) worst · best
Space
Θ(W) extra
Where
W = the number of bytes in a vector register; n = the number of input bytes
Properties
deterministiconlineiterative

The Keiser-Lemire validator decides whether a byte string is well-formed UTF-8 with a few vector instructions per block of 16, 32 or 64 bytes and no branch per byte. Every error in a UTF-8 string shows up in some pair of a byte and the byte before it, or as a continuation byte that the byte two or three places back requires or forbids. The validator looks up the high nibble and the low nibble of the previous byte and the high nibble of the current byte in three 16-entry tables, ANDs the three results, and so gets a set of error bits for every byte in parallel. John Keiser and Daniel Lemire published it in 2021, and on AVX2 processors it ran at over 10 GiB/s in their tests.

In plain words

A UTF-8 checker usually reads one byte at a time and asks: is this byte allowed here, given the bytes before it? That costs a few decisions per byte, and modern processors are slow when they cannot predict a decision.

This method asks the same question for 16 or 32 bytes at once, with no decisions. The trick is that almost every mistake can be seen by looking at just two neighbouring bytes, and in fact at only three of their four-bit halves. For each half there is a small table of 16 entries that says which mistakes are possible. If all three tables agree on a mistake, the pair is wrong.

One more check looks two and three bytes back, to catch the bytes that a long character needs. The results of all blocks are ORed together, and the text is valid if the final result is zero.

The problem

The input is a byte string BB of length nn. The output is true if BB is a concatenation of the sequences of Table 3-7 of the core specification, and false otherwise. The validator does not say where the first error is, and it does not decode.

Section 3 of the paper lists the kinds of error. With a continuation byte meaning one in 80..BF and a lead byte one in C0..FF, they are:

  • 5+ byte. A byte F8..FF. It is caught as "too large" below.
  • Too short. A lead byte followed by a byte that is not a continuation.
  • Too long. A continuation byte with nothing to continue: after an ASCII byte, or after a complete sequence.
  • Overlong. C0 or C1 followed by a continuation, E0 followed by 80..9F, F0 followed by 80..8F.
  • Too large. F4 followed by 90..BF, or F5..FF followed by a continuation.
  • Surrogate. ED followed by A0..BF.

The algorithm

The vectors have WW bytes (W=16W = 16 in the implementation, 32 with AVX2). The operations are lane-wise: AND, OR, XOR, a saturating subtraction SATSUB that stops at 0, a nibble extraction, a 16-entry table lookup (the instruction pshufb on x86 and vqtbl1q_u8 on ARM), and SHIFT(prev,x,k)(prev, x, k), which builds the vector whose lane ii is the byte kk places before x[i]x[i], taking the first kk lanes from the end of prevprev.

  1. VALIDATE(B[0..n-1])
  2. 1error <- 0; prev <- 0; prev_incomplete <- 0
  3. 2for each block x of W bytes of B, the last one padded with zero bytes do
  4. 3if every byte of x is below 0x80 then
  5. 4error <- error OR prev_incomplete
  6. 5else
  7. 6error <- error OR CHECK-BLOCK(x, prev)
  8. 7prev_incomplete <- SATSUB(x, MAX_TAIL)
  9. 8prev <- x
  10. 9error <- error OR prev_incomplete
  11. 10return every byte of error is 0
  12. CHECK-BLOCK(x, prev)
  13. 11p1 <- SHIFT(prev, x, 1)
  14. 12sc <- T1[HIGH(p1)] AND T2[LOW(p1)] AND T3[HIGH(x)]
  15. 13p2 <- SHIFT(prev, x, 2); p3 <- SHIFT(prev, x, 3)
  16. 14must23 <- (SATSUB(p2, 0x60) OR SATSUB(p3, 0x70)) AND 0x80
  17. 15return must23 XOR sc

The tables (line L12). Each error kind gets one bit. A bit is set in the AND exactly when all three tables have it, so each table entry lists the error kinds that its nibble allows. With the bit values of the paper's Table 9:

bit name previous byte current byte
01 TOO_SHORT C0..FF 00..7F or C0..FF
02 TOO_LONG 00..7F 80..BF
04 OVERLONG_3 E0 80..9F
08 TOO_LARGE F4..FF 90..BF
10 SURROGATE ED A0..BF
20 OVERLONG_2 C0, C1 80..BF
40 OVERLONG_4 or TOO_LARGE_1000 F0 or F5..FF 80..8F
80 TWO_CONTS 80..BF 80..BF

For example, T1, indexed by the high nibble of the previous byte, has 02 at the nibbles 0 to 7, 80 at 8 to B, 21 at C, 01 at D, 15 at E and 49 at F. The nibble E allows TOO_SHORT, OVERLONG_3 and SURROGATE, and T2 and T3 then narrow OVERLONG_3 to the low nibble 0 and the current bytes 80..9F. Bit 40 serves two kinds that never meet: both need a current byte in 80..8F, and the previous byte is F0 for one and F5..FF for the other.

Two continuations (line L14). TWO_CONTS is not always an error. The third and fourth bytes of a sequence are continuations after a continuation. They are expected exactly when the byte two places back is at least E0 or the byte three places back is at least F0. SATSUB(y,60)(y, \mathtt{60}) has bit 7 set exactly when y≥E0y \ge \mathtt{E0}, and SATSUB(y,70)(y, \mathtt{70}) exactly when y≥F0y \ge \mathtt{F0}. The XOR of line L15 clears TWO_CONTS where it is expected and sets bit 7 where a continuation is expected but missing.

The end of the input (lines L7 and L9). A sequence can start in the last 3 bytes of a block. The next block checks it, but if the input ends, or the next block is all ASCII and skipped, nothing would. MAX_TAIL is FF in every lane except the last three, which hold EF, DF and BF. SATSUB(x,MAX_TAIL)(x, \mathtt{MAX\_TAIL}) is nonzero exactly when the third last byte is at least F0, the second last at least E0 or the last at least C0.

The ASCII path (lines L3 and L4). A block of ASCII bytes has no error of its own. It only needs the check of the end of the block before it. The paper does this test on blocks of 64 bytes.

Example

The bytes of "9", ç, 鏡 and 😀, followed by a zero byte, as in Table 9 of the paper. The previous vector is zero.

lane 0 1 2 3 4 5 6 7 8 9 10
input 39 C3 A7 E9 8F A1 F0 9F 98 80 00
previous byte 00 39 C3 A7 E9 8F A1 F0 9F 98 80
T1 02 02 21 80 15 80 80 49 80 80 80
T2 E7 CB 83 CB CB CB A3 E7 CB CB E7
T3 01 01 BA 01 E6 BA 01 AE AE E6 01
sc 00 00 00 00 00 80 00 00 80 80 00
must23 00 00 00 00 00 80 00 00 80 80 00
error 00 00 00 00 00 00 00 00 00 00 00

The three 80 values of sc are the third byte A1 of 鏡 and the third and fourth bytes 98 and 80 of 😀. The bytes E9 two places before lane 5 and F0 two and three places before lanes 8 and 9 make must23 equal there, so the XOR clears them. The test test_table_9_worked_example checks every row.

Now change the last byte of 😀 from 80 to 41. In lane 9, T1 at 9 is 80, T2 at 8 is CB and T3 at 4 is 01, so sc is 00. But F0 is three places back, so must23 is 80, and the error is 80: the sequence is too short. For the overlong pair C0 AF, the lane of AF has 21 AND E7 AND BA = 20, which is OVERLONG_2.

Correctness

The paper derives the tables from the error list. The proof in proofs/correctness.md goes the other way. First, the bits of scsc have exactly the meanings in the table above, which test_meaning_of_each_error_bit checks on all 65,536 byte pairs. Second, with the input padded by zero bytes on both sides, the validator reports an error exactly when some position jj has sc(j)≠must23(j)sc(j) \ne must23(j), because the block checks see every position of the input, and the end check covers the positions of the skipped ASCII blocks and of the padding. Third, a string is well-formed exactly when no position has such an error. In one direction, in a well-formed string, scsc is TWO_CONTS exactly at the third and fourth bytes of sequences, and must23must23 is 80 at exactly the same places. In the other, the first place where a decoder would fail has a bad pair, or a missing or extra continuation that must23must23 exposes.

Proof: The lookup validator accepts exactly the well-formed UTF-8 stringsfull

Claim. For every byte string BB of length nn, VALIDATE(B)(B) (lines L1 to L10) stops after ⌈n/16⌉\lceil n / 16 \rceil passes of its loop, and it returns true if and only if BB is well-formed UTF-8 in the sense of D92 and Table 3-7 of the core specification.

Setup. Let ZZ be the infinite byte sequence with Z[j]=B[j]Z[j] = B[j] for 0≤j<n0 \le j < n and Z[j]=0Z[j] = 0 for all other jj, also the negative ones. A continuation byte is one in 80..BF and a lead byte one in C0..FF. For a position j≥0j \ge 0, define

  • sc(j)sc(j) = the AND of the three lookups of line L12 for the previous byte a=Z[j−1]a = Z[j-1] and the current byte x=Z[j]x = Z[j],
  • m(j)m(j) = 80 if Z[j−2]≥E0Z[j-2] \ge \mathtt{E0} or Z[j−3]≥F0Z[j-3] \ge \mathtt{F0}, and 0 otherwise,
  • e(j)=sc(j)⊕m(j)e(j) = sc(j) \oplus m(j).

Lemma 1 (the tables). The bits of sc(j)sc(j) have these meanings. The test test_meaning_of_each_error_bit checks all 65,536 pairs (a,x)(a, x).

bit set exactly when
01 TOO_SHORT aa is a lead and xx is not a continuation
02 TOO_LONG a<80a < \mathtt{80} and xx is a continuation
80 TWO_CONTS aa and xx are both continuations
20 OVERLONG_2 aa is C0 or C1 and xx is a continuation
04 OVERLONG_3 a=E0a = \mathtt{E0} and xx is in 80..9F
10 SURROGATE a=EDa = \mathtt{ED} and xx is in A0..BF
08 TOO_LARGE a≥F4a \ge \mathtt{F4} and xx is in 90..BF
40 a=F0a = \mathtt{F0} or a≥F5a \ge \mathtt{F5}, and xx is in 80..8F

Proof. A bit of the AND is set exactly when it is set in all three entries. Each entry depends on one nibble, so each condition is a product of a set of high nibbles of aa, a set of low nibbles of aa and a set of high nibbles of xx, and the table rows give these sets. For example, bit 04 is in BYTE_1_HIGH only at nibble E, in BYTE_1_LOW only at nibble 0, and in BYTE_2_HIGH at nibbles 8 and 9. Bit 40 is in BYTE_1_HIGH only at F, in BYTE_1_LOW at 0 and at 5 to F, and in BYTE_2_HIGH only at 8. The other rows follow in the same way. □\square

Lemma 2 (the 3 and 4 byte check). Line L14 computes m(j)m(j). For a byte yy, the saturating difference y⊖60y \ominus \mathtt{60} is at least 80 exactly when y≥E0y \ge \mathtt{E0}, and it is at most 9F, so bit 7 of it is set exactly when y≥E0y \ge \mathtt{E0}. In the same way, bit 7 of y⊖70y \ominus \mathtt{70} is set exactly when y≥F0y \ge \mathtt{F0}. The OR and the AND with 80 keep only bit 7. □\square

Lemma 3 (coverage). VALIDATE(B)(B) returns false exactly when e(j)≠0e(j) \ne 0 for some j≥0j \ge 0.

Proof. Split Z[0…]Z[0 \ldots] into vectors of 16 bytes. The loop of line L2 visits the vectors that hold bytes of BB, padded with zero bytes, and line L8 keeps the previous vector in prevprev, which starts as zeros, the bytes of ZZ before position 0. For a vector xx that is not all ASCII, line L13 builds the bytes 1, 2 and 3 places back from xx and prevprev, so by Lemmas 1 and 2, line L6 ORs e(j)e(j) into the error for each lane jj of xx.

Now let xx be an all-ASCII vector, either one of the input or one of the zero vectors after the input. Inside it, sc(j)sc(j) and m(j)m(j) can be nonzero only in lanes 0 to 2, because every other lane has an ASCII byte and three ASCII bytes before it. In lanes 0 to 2, x[j]x[j] is not a continuation, so only TOO_SHORT and m(j)m(j) can be set. Lane 0 gets an error if prev[15]≥C0prev[15] \ge \mathtt{C0}, prev[14]≥E0prev[14] \ge \mathtt{E0} or prev[13]≥F0prev[13] \ge \mathtt{F0}, lane 1 if prev[15]≥E0prev[15] \ge \mathtt{E0} or prev[14]≥F0prev[14] \ge \mathtt{F0}, and lane 2 if prev[15]≥F0prev[15] \ge \mathtt{F0}. Together, the vector has a lane with e(j)≠0e(j) \ne 0 exactly when prevprev fails the bounds C0, E0 and F0 on its last three bytes, which is when IS-INCOMPLETE(prev)(prev) is nonzero. Line L7 computes this value for every vector that is not all ASCII, and line L4 or line L9 ORs it in when an all-ASCII vector follows, or when the input ends and the zero vectors follow. If prevprev is itself all ASCII, its own value is zero, and the stored value comes from an earlier vector and was already ORed in when prevprev was visited. All zero vectors after the first one have e(j)=0e(j) = 0 in every lane. □\square

Lemma 4. BB is well-formed exactly when e(j)=0e(j) = 0 for every j≥0j \ge 0.

Proof that well-formed implies no error. Z[0…]Z[0 \ldots] is then a concatenation of Table 3-7 sequences, and the bytes before position 0 are zeros, which also end a sequence. Take a position jj and the sequence that holds Z[j]Z[j].

  • Z[j]Z[j] starts its sequence. Then Z[j−1]Z[j-1] ends a sequence, so it is not a lead and TOO_SHORT is clear, and the other bits need xx to be a continuation. So sc(j)=0sc(j) = 0. If Z[j−2]≥E0Z[j-2] \ge \mathtt{E0} or Z[j−3]≥F0Z[j-3] \ge \mathtt{F0}, that byte would start a sequence long enough to contain Z[j]Z[j], which is not the case. So m(j)=0m(j) = 0.
  • Z[j]Z[j] is the second byte. Then a=Z[j−1]a = Z[j-1] is a lead of Table 3-7 and xx is in the range of its row. TOO_SHORT, TOO_LONG and TWO_CONTS are clear, aa is not C0, C1 or F5..FF, and the row ranges exclude the four cases of OVERLONG_3, SURROGATE, TOO_LARGE and bit 40. So sc(j)=0sc(j) = 0. The bytes Z[j−2]Z[j-2] and Z[j−3]Z[j-3] belong to earlier sequences, so a value at least E0 or F0 there would start a sequence that contains Z[j−1]Z[j-1], but Z[j−1]Z[j-1] is a lead. So m(j)=0m(j) = 0.
  • Z[j]Z[j] is the third byte. Then aa is a continuation, so $sc(j) = $ TWO_CONTS =80= \mathtt{80}, and Z[j−2]≥E0Z[j-2] \ge \mathtt{E0} is the lead, so m(j)=80m(j) = \mathtt{80} and e(j)=0e(j) = 0.
  • Z[j]Z[j] is the fourth byte. Again sc(j)=80sc(j) = \mathtt{80}, and Z[j−3]≥F0Z[j-3] \ge \mathtt{F0} is the lead, so e(j)=0e(j) = 0.

Proof that ill-formed implies an error. Run the scan of a UTF-8 decoder on Z[0…]Z[0 \ldots] and let ii be the start of the first sequence that does not match Table 3-7. Everything before ii consists of complete sequences, so Z[i−1]<C0Z[i-1] < \mathtt{C0}, Z[i−2]<E0Z[i-2] < \mathtt{E0} and Z[i−3]<F0Z[i-3] < \mathtt{F0}. Bits 01 to 40 of scsc cannot be cancelled by mm, which has only bit 80.

  1. Z[i]Z[i] is a continuation. If Z[i−1]<80Z[i-1] < \mathtt{80}, TOO_LONG is set in sc(i)sc(i). Otherwise Z[i−1]Z[i-1] is a continuation, TWO_CONTS is set, and m(i)=0m(i) = 0 by the bounds above, so e(i)≠0e(i) \ne 0.
  2. Z[i]Z[i] is C0, C1 or in F5..FF, which start no row. At j=i+1j = i + 1, TOO_SHORT is set if Z[i+1]Z[i+1] is not a continuation. If it is one, OVERLONG_2 is set for C0 and C1, and TOO_LARGE or bit 40 for F5..FF.
  3. Z[i]Z[i] is a lead of a row with kk continuation bytes, and byte i+ti + t with 1≤t≤k1 \le t \le k is the first one out of range. Bytes after the end of BB are zeros, so this covers a truncated end too. If t=1t = 1 and Z[i+1]Z[i+1] is not a continuation, TOO_SHORT is set at i+1i + 1. If t=1t = 1 and it is a continuation outside the row's second byte range, then by Table 3-7 the pair is E0 with 80..9F, ED with A0..BF, F0 with 80..8F, or F4 with 90..BF, and OVERLONG_3, SURROGATE, bit 40 or TOO_LARGE is set. If t≥2t \ge 2, then Z[i+t]Z[i+t] is not a continuation, because the later ranges are all of 80..BF, and its previous byte is a continuation, so sc(i+t)=0sc(i+t) = 0. But Z[i]≥E0Z[i] \ge \mathtt{E0} if t=2t = 2, and Z[i]≥F0Z[i] \ge \mathtt{F0} if t=3t = 3, so m(i+t)=80m(i+t) = \mathtt{80} and e(i+t)≠0e(i+t) \ne 0. □\square

Proof of the claim. Lemmas 3 and 4. Each pass of the loop of line L2 does a fixed number of vector operations and moves 16 bytes forward, so the procedure stops after ⌈n/16⌉\lceil n / 16 \rceil passes. ■\blacksquare

Complexity

Count each vector instruction as one step. This is an assumption of the analysis: a real instruction has a latency and a throughput that depend on the processor. Then each block of WW bytes costs a constant number of steps: two nibble extractions and three lookups, three shifts, two saturating subtractions, and five AND, OR and XOR operations. The whole input costs Θ(n/W)\Theta(n / W) steps and Θ(W)\Theta(W) bytes of state. The ASCII path makes blocks of pure ASCII cost only a test and an OR.

The speed is a measurement, not a consequence of the model. On an Intel i7-6700 (Skylake) and an AMD EPYC 7262 (Zen 2), with GCC 9.3 and AVX2, the lookup validator retires slightly under 0.4 instructions per byte on the files twitter.json and hongkong.html (section 7.2), and it validates random UTF-8 at about 12 to 13 GB/s (Figure 2). Section 2 states: "We consistently exceed 10 GiB/s".

claim value
steps per block a constant number of vector instructions
total Θ(n/W)\Theta(n / W) steps
measured, AVX2 under 0.4 instructions per byte

Properties

  • No data-dependent branch inside a block. The only branch is the ASCII test, which is well predicted on most real text.
  • Same language as Table 3-7. It accepts exactly the well-formed UTF-8 strings, including the noncharacters, which are scalar values.
  • Verdict only. The errors are ORed across blocks, so the result says only that the input is bad. Finding the position needs a second, scalar pass.
  • Streaming. The state between blocks is the previous block, the end check value and the error vector, so the input can arrive in pieces.

Variants and improvements

  • Branchy and finite-state validators. A scalar validator reads one byte at a time with branches, or runs a finite automaton with a transition table. The paper uses such validators as baselines.
  • Wider vectors. With AVX2, W=32W = 32, and the shifts must cross the two 128-bit halves of a register with a permute. With AVX-512, W=64W = 64.
  • Transcoding. The same checks run inside SIMD converters from UTF-8 to UTF-16, which must validate anyway.
  • Error position. After a failed block, run a scalar decoder from a few bytes before that block to find the first bad byte.

When to use it

Use it when large inputs must be validated before they are parsed: JSON documents, files read from disk, and network messages. Most such input is valid and mostly ASCII, and the validator then costs a small part of the parsing time. For short strings, a scalar validator is as fast, because the vector setup dominates. When the program also needs the code points, decoding validates as a side effect, so a separate validator is only worth it when the decoder itself is slow or when the data stays in UTF-8.

Pitfalls

  • Missing end check. If the input ends exactly at a block boundary, an incomplete sequence in the last 3 bytes leaves no trace in the block checks. Lines L7 and L9 catch it, and the test test_sequence_cut_at_the_end_of_a_full_vector checks it.
  • Skipped ASCII blocks. An ASCII block after a block that ends inside a sequence must still raise the error. Line L4 does that, and the same test covers it.
  • Padding. The last block must be padded with zero bytes, which are ASCII. Other padding can hide a truncated sequence or create a false error.
  • Lost context. The previous block must be kept even when the current one is ASCII, or the shifts of the next block see the wrong bytes.
  • Copying the tables by hand. One wrong bit in one of the 48 table entries accepts some bad pair or rejects some good one, and random tests rarely find it. Build the entries from the named bit constants, as the implementation does, and check all 65,536 pairs.
  • Reading the speed as a bound. "Less than one instruction per byte" is a measurement on specific processors and inputs. On other hardware the number differs.

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.

simd_utf_8_validation.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/simd-utf-8-validation/. The authors are listed in prov/6SS0HB.jsonl.

"""The lookup algorithm of Keiser and Lemire (2021), section 6, emulated on 16-byte vectors.

A vector is a list of 16 ints in 0..255. Each helper below stands for one or two SIMD
instructions: a table lookup on nibbles (pshufb, vqtbl1q_u8), a byte shift across two
vectors (palignr, vextq_u8), a saturating subtraction (psubusb, vqsubq_u8), and lane-wise
AND, OR and XOR. Python runs them one lane at a time, so this file shows the method and is
not fast. The table values are those of the paper's Table 9 and of the authors' code.
"""

W = 16  # bytes per vector

# Error bits. Bit 6 has two meanings that never meet in one lookup (see the proof).
TOO_SHORT = 0x01  # a lead byte or an ASCII byte follows a lead byte
TOO_LONG = 0x02  # a continuation byte follows an ASCII byte
OVERLONG_3 = 0x04  # E0 followed by 80..9F
TOO_LARGE = 0x08  # F4 followed by 90..BF, or F5..FF followed by a continuation byte
SURROGATE = 0x10  # ED followed by A0..BF
OVERLONG_2 = 0x20  # C0 or C1 followed by a continuation byte
TOO_LARGE_1000 = 0x40  # F5..FF followed by 80..8F
OVERLONG_4 = 0x40  # F0 followed by 80..8F
TWO_CONTS = 0x80  # a continuation byte follows a continuation byte
CARRY = TOO_SHORT | TOO_LONG | TWO_CONTS

# Indexed by the high nibble of the previous byte.
BYTE_1_HIGH = (
    [TOO_LONG] * 8
    + [TWO_CONTS] * 4
    + [TOO_SHORT | OVERLONG_2, TOO_SHORT, TOO_SHORT | OVERLONG_3 | SURROGATE,
       TOO_SHORT | TOO_LARGE | TOO_LARGE_1000 | OVERLONG_4]
)
# Indexed by the low nibble of the previous byte.
BYTE_1_LOW = (
    [CARRY | OVERLONG_3 | OVERLONG_2 | OVERLONG_4, CARRY | OVERLONG_2, CARRY, CARRY, CARRY | TOO_LARGE]
    + [CARRY | TOO_LARGE | TOO_LARGE_1000] * 8
    + [CARRY | TOO_LARGE | TOO_LARGE_1000 | SURROGATE]
    + [CARRY | TOO_LARGE | TOO_LARGE_1000] * 2
)
# Indexed by the high nibble of the current byte.
BYTE_2_HIGH = (
    [TOO_SHORT] * 8
    + [TOO_LONG | OVERLONG_2 | TWO_CONTS | OVERLONG_3 | TOO_LARGE_1000 | OVERLONG_4,
       TOO_LONG | OVERLONG_2 | TWO_CONTS | OVERLONG_3 | TOO_LARGE]
    + [TOO_LONG | OVERLONG_2 | TWO_CONTS | SURROGATE | TOO_LARGE] * 2
    + [TOO_SHORT] * 4
)

# The last byte must be below C0, the second last below E0 and the third last below F0.
MAX_TAIL = [0xFF] * (W - 3) + [0xF0 - 1, 0xE0 - 1, 0xC0 - 1]


def lookup(table: list[int], v: list[int]) -> list[int]:
    return [table[x] for x in v]


def high_nibbles(v: list[int]) -> list[int]:
    return [x >> 4 for x in v]


def low_nibbles(v: list[int]) -> list[int]:
    return [x & 0x0F for x in v]


def vand(a: list[int], b: list[int]) -> list[int]:
    return [x & y for x, y in zip(a, b)]


def vor(a: list[int], b: list[int]) -> list[int]:
    return [x | y for x, y in zip(a, b)]


def vxor(a: list[int], b: list[int]) -> list[int]:
    return [x ^ y for x, y in zip(a, b)]


def sat_sub(a: list[int], b: list[int]) -> list[int]:
    return [max(x - y, 0) for x, y in zip(a, b)]


def splat(x: int) -> list[int]:
    return [x] * W


def prev_n(x: list[int], prev: list[int], n: int) -> list[int]:
    """Lane i holds the byte n places before x[i]; the first n lanes come from the end of prev."""
    return prev[W - n:] + x[:W - n]


def check_special_cases(x: list[int], p1: list[int]) -> list[int]:
    """The 2-byte check of section 6.1: three lookups ANDed together."""
    return vand(vand(lookup(BYTE_1_HIGH, high_nibbles(p1)), lookup(BYTE_1_LOW, low_nibbles(p1))),
                lookup(BYTE_2_HIGH, high_nibbles(x)))


def must_be_2_3_continuation(p2: list[int], p3: list[int]) -> list[int]:
    """Bit 7 is set where the byte 2 back is E0..FF or the byte 3 back is F0..FF (section 6.2)."""
    is_third = sat_sub(p2, splat(0xE0 - 0x80))
    is_fourth = sat_sub(p3, splat(0xF0 - 0x80))
    return vand(vor(is_third, is_fourth), splat(0x80))


def check_block(x: list[int], prev: list[int]) -> list[int]:
    p1 = prev_n(x, prev, 1)  # @line L11
    sc = check_special_cases(x, p1)  # @line L12
    p2, p3 = prev_n(x, prev, 2), prev_n(x, prev, 3)  # @line L13
    must23 = must_be_2_3_continuation(p2, p3)  # @line L14
    return vxor(must23, sc)  # @line L15


def is_incomplete(x: list[int]) -> list[int]:
    """Nonzero in a lane of the last three if a sequence starting there runs past the end of x."""
    return sat_sub(x, MAX_TAIL)


def any_nonzero(v: list[int]) -> bool:
    return any(v)


def validate(data: bytes) -> bool:
    """True if data is well-formed UTF-8 (D92, Table 3-7 of the core spec)."""
    error = splat(0)  # @line L1
    prev, prev_incomplete = splat(0), splat(0)
    for i in range(0, len(data), W):  # @line L2
        x = list(data[i:i + W])
        x += [0] * (W - len(x))  # zero bytes are ASCII, so padding never hides an error
        if max(x) < 0x80:  # @line L3
            error = vor(error, prev_incomplete)  # @line L4
        else:  # @line L5
            error = vor(error, check_block(x, prev))  # @line L6
            prev_incomplete = is_incomplete(x)  # @line L7
        prev = x  # @line L8
    error = vor(error, prev_incomplete)  # @line L9
    return not any_nonzero(error)  # @line L10
test_simd_utf_8_validation.py 135 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/simd-utf-8-validation/. The authors are listed in prov/6SS0HB.jsonl.

# Oracle: bytes.decode("utf-8") in strict mode, which accepts exactly the well-formed
# sequences of Table 3-7 of the core spec. Written against Python 3.14.

import itertools
import random

from simd_utf_8_validation import (
    BYTE_1_HIGH, BYTE_1_LOW, BYTE_2_HIGH, W, check_block, check_special_cases, high_nibbles, lookup,
    low_nibbles, prev_n, validate)

BOUNDARY = bytes([0x00, 0x7F, 0x80, 0x8F, 0x90, 0x9F, 0xA0, 0xBF, 0xC0, 0xC1, 0xC2, 0xDF, 0xE0, 0xE1, 0xED,
                  0xEE, 0xEF, 0xF0, 0xF1, 0xF3, 0xF4, 0xF5, 0xFF])


def reference(data: bytes) -> bool:
    try:
        data.decode("utf-8")
        return True
    except UnicodeDecodeError:
        return False


def h(s: str) -> list[int]:
    return [int(x, 16) for x in s.split()]


def test_table_9_worked_example() -> None:
    # Keiser and Lemire, Table 9: the bytes of "9", U+00E7, U+93E1, U+1F600 and a zero byte.
    data = "9ç鏡\U0001f600\x00".encode()
    assert list(data) == h("39 C3 A7 E9 8F A1 F0 9F 98 80 00")
    x = list(data) + [0] * (W - len(data))
    p1 = prev_n(x, [0] * W, 1)
    n = len(data)
    assert lookup(BYTE_1_HIGH, high_nibbles(p1))[:n] == h("02 02 21 80 15 80 80 49 80 80 80")
    assert lookup(BYTE_1_LOW, low_nibbles(p1))[:n] == h("E7 CB 83 CB CB CB A3 E7 CB CB E7")
    assert lookup(BYTE_2_HIGH, high_nibbles(x))[:n] == h("01 01 BA 01 E6 BA 01 AE AE E6 01")
    assert check_special_cases(x, p1)[:n] == h("00 00 00 00 00 80 00 00 80 80 00")
    assert check_block(x, [0] * W) == [0] * W
    assert validate(data)


def test_meaning_of_each_error_bit() -> None:
    # For every pair (a, x) of a byte and the byte after it, each bit of the AND of the three
    # lookups is set exactly under the condition that the proof of correctness uses.
    def cont(v: int) -> bool:
        return 0x80 <= v <= 0xBF

    for a in range(256):
        p1 = [a] * W
        for x0 in range(0, 256, W):
            row = check_special_cases(list(range(x0, x0 + W)), p1)
            for x, sc in zip(range(x0, x0 + W), row):
                want = 0
                want |= 0x01 if a >= 0xC0 and not cont(x) else 0
                want |= 0x02 if a < 0x80 and cont(x) else 0
                want |= 0x80 if cont(a) and cont(x) else 0
                want |= 0x20 if a in (0xC0, 0xC1) and cont(x) else 0
                want |= 0x04 if a == 0xE0 and 0x80 <= x <= 0x9F else 0
                want |= 0x10 if a == 0xED and 0xA0 <= x <= 0xBF else 0
                want |= 0x08 if a >= 0xF4 and 0x90 <= x <= 0xBF else 0
                want |= 0x40 if (a == 0xF0 or a >= 0xF5) and 0x80 <= x <= 0x8F else 0
                assert sc == want, (hex(a), hex(x))


def test_check_values() -> None:
    assert validate(b"") and validate(b"hello") and validate("€😀".encode())
    for bad in [b"\xc0\xaf", b"\xe0\x80\xaf", b"\xed\xa0\x80", b"\xf4\x90\x80\x80", b"\xf8\x88\x80\x80\x80",
                b"\x80", b"\xe2\x82", b"\xff"]:
        assert not validate(bad), bad


def test_short_sequences_over_boundary_bytes() -> None:
    # Each sequence is tried at every offset near a vector boundary, so that the bytes before
    # it come from the previous vector.
    for n in range(1, 4):
        for seq in itertools.product(BOUNDARY, repeat=n):
            s = bytes(seq)
            want = reference(s)
            for pad in (0, W - 2, W - 1):
                assert validate(b"a" * pad + s) == want, (pad, s)
    rng = random.Random(1)
    for _ in range(4000):
        s = bytes(rng.choice(BOUNDARY) for _ in range(4))
        pad = rng.randrange(0, 2 * W)
        assert validate(b"a" * pad + s) == reference(s), (pad, s)


def test_all_two_byte_strings() -> None:
    for a in range(256):
        assert validate(bytes([a])) == reference(bytes([a]))
        for b in range(0x80, 0x100):  # with an ASCII second byte, the verdict is that of a alone
            s = bytes([a, b])
            assert validate(s) == reference(s), s


def test_sequence_cut_at_the_end_of_a_full_vector() -> None:
    # The input ends exactly at a vector boundary, so only the incomplete-end check can see it.
    for tail in [b"\xc2", b"\xe2\x82", b"\xe2", b"\xf0\x9f\x98", b"\xf0\x9f", b"\xf0"]:
        s = b"a" * (W - len(tail)) + tail
        assert len(s) == W and not validate(s)
        assert not validate(s + b"a" * W)  # an ASCII vector after it does not hide the error
    assert validate(b"a" * (W - 2) + "ç".encode())


def random_text(rng: random.Random) -> str:
    pools = [(0x20, 0x7F), (0x80, 0x800), (0x800, 0xD800), (0xE000, 0x10000), (0x10000, 0x110000)]
    out = []
    for _ in range(rng.randrange(0, 40)):
        lo, hi = rng.choice(pools)
        out.append(chr(rng.randrange(lo, hi)))
    return "".join(out)


def test_valid_text_and_one_changed_byte() -> None:
    rng = random.Random(2)
    for _ in range(1500):
        data = random_text(rng).encode()
        assert validate(data)
        if data:
            b = bytearray(data)
            b[rng.randrange(len(b))] = rng.randrange(256)
            assert validate(bytes(b)) == reference(bytes(b))
            cut = data[:rng.randrange(len(data))]
            assert validate(cut) == reference(cut)


def test_random_bytes() -> None:
    rng = random.Random(3)
    for _ in range(1500):
        data = bytes(rng.choice(BOUNDARY) if rng.random() < 0.7 else rng.randrange(256)
                     for _ in range(rng.randrange(0, 50)))
        assert validate(data) == reference(data), data

History

UTF-8 validation was long done with byte-at-a-time decoders or with table-driven automata. Keiser and Lemire posted their lookup method on arXiv in October 2020 and published it in Software: Practice and Experience in 2021. The method is used in the simdjson parser, which must validate its UTF-8 input, and the paper compares it with scalar validators on the same hardware.

References

  1. John Keiser and Daniel Lemire, Validating UTF-8 In Less Than One Instruction Per Byte, arXiv:2010.03090, Section 3 (the rules), Section 6 (the lookup algorithm: 6.1 the 2-byte tables, 6.2 the 3 and 4 byte check, 6.3 incomplete input, 6.4 the ASCII path), Tables 8 and 9, Section 7.2 and Figure 2
  2. John Keiser and Daniel Lemire, Validating UTF-8 In Less Than One Instruction Per Byte, Software, Practice and Experience 51(5), 950-964, 2021, Sections 6 and 7
  3. The Unicode Consortium, The Unicode Standard, Version 16.0.0, 2024, Chapter 3, Section 3.9, D92 and Table 3-7 (well-formed UTF-8 byte sequences)

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