Blogofbrew

home

Revisiting the Lemire Thanksgiving Challenge

27 Nov 2026

Back in November 2023 Daniel Lemire posted Parsing 8-bit integers quickly. Turn a 1–3 character string into a uint8_t, and reject anything that isn’t 0–255. The comments turned into a SWAR golf tournament. Three Thanksgivings later, I decided to revisit it with a brute force checker, Lean, and a superoptimizer.

This post writes up a session where I drove Anthropic’s Opus 5.5 through the whole thing. Opus wrote ran everything on my M2 Ultra: the brute force checker, the Lean models and proofs, the benchmarks, and the constant search that found the new validity test below. The search itself is a dumb exhaustive program Opus wrote. The formula came out of it, not out of anyone’s head. Everything is in tools/bruteeq32/, and every number below is reproducible.

What makes this fun is that every SWAR entry loads the string as one 32-bit word. Fix the length and each parser is a unary function on 32 bits. 2^32 is not a big number anymore. Check them all.

The Contenders

The naive loop is the spec:

int parse_uint8_naive(const char *str, size_t len, uint8_t *num) {
  uint32_t n = 0;
  for (size_t i = 0, r = len & 3; i < r; i++) {
    uint8_t d = (uint8_t)(str[i] - '0');
    if (d > 9) return 0;
    n = n * 10 + d;
  }
  *num = (uint8_t)n;
  return n < 256 && len && len < 4;
}

Lemire’s fastswar XORs off the '0's, shifts the digits to the top of the word, and does one multiply by 0x640a01 to land 100a + 10b + c in the top byte. Jean-Marc Bourguet supplied the validation: a nibble test for digits, and a byte swap plus a compare against 0x020505 for the range. Perforated Bob, KWillets, and Jeroen Koekkoek posted variants in the comments. All of them are re-implemented in lemire8.h.

Every parser returns 0x100 | value on success and 0 on failure, so two parsers can be compared with a single XOR.

Brute Force

bruteeq32 is built for exactly this kind of thing. Give it two C functions on uint32_t and it checks every input on every core, keeping the smallest counterexample. There is also a Metal version that compiles the same header as a GPU kernel at run time. On my M2 Ultra the GPU does one length in 0.02–0.05 seconds.

fastswar, Bob’s version, and the multiply-first variant all match the naive loop on all 2^32 words at lengths 0–7. Koekkoek’s skips validation, but it gets every valid string right.

It is also good at catching near misses. Testing only the high nibble, (d & 0xF0F0F0F0) == 0, accepts ":", smallest counterexample 0x3A. Dropping the d | from Bourguet’s check accepts byte 0xCA: after the XOR it is 0xFA, and adding 6 wraps it to zero. Both pass a test of “0” through “255”.

Lean

Brute force stops at the lengths you try. Lean’s bv_decide bit-blasts the goal to SAT and checks the certificate, so the proofs quantify over the length too:

theorem fastswar_eq (x len : W) : fastswar x len = ref x len := by
  simp only [fastswar, ref, dig, tag, bswap]; bv_decide

That one line covers all 2^32 words and all 2^32 lengths, and there is one like it for every validating parser above. The same file proves Bourguet’s range trick: three digits are under 256 exactly when they compare ≤ “255”. It also proves that both broken checks fail at the counterexamples bruteeq32 found and at nothing smaller, and that a correct parser has to read all three bytes. The whole file, Lemire8.lean, checks in about 35 seconds, mostly spent importing Mathlib.

You are still trusting the SAT certificate checker and the hand translation from C to Lean. 440 #guard lines spot-check the translation against the C outputs.

Benchmark With Garbage

With one call per string, every SWAR entry lands around 1.6 ns on my machine, and the differences are mostly noise. But Lemire’s benchmark only feeds valid numbers, and real input is dirtier. So I had it add a run where half the strings are bad and the lengths are random. That is where the early if (len == 0 || len > 3) return 0; falls over.

Single-call benchmark, all valid vs half invalid

Making fastswar branch-free (mask the shift count, fold the length test into the others) costs 0.1 ns on clean input and removes the penalty. Bob’s version is branch-free under Apple clang, but gcc 11 gives it a branch, and it then takes 5.3 ns on the dirty input. See lemire8bench.c.

Superoptimizing the Check

Next I asked Opus to try to beat Bourguet’s check, so it pointed a dumb search at it. After the shift, the digits sit in bytes 1–3, and the product P = d * 0x640a01 gets computed anyway. For each candidate formula, the search tried every 24-bit constant against all 2^24 byte triples. Three-instruction formulas: nothing. At four instructions, after Opus added AArch64’s free operand shifts to the search, this one falls out:

uint32_t d = (x ^ 0x30303030u) << ((0u - (len << 3)) & 31u);
uint64_t P = (uint64_t)d * 0x640a01u;
uint32_t u = ((d + 0x76060000u) | d) | (uint32_t)(P >> 1);
uint32_t ok = ((u & 0x80707c7fu) == 0) & (len - 1u < 3u);
return (0x100u | (uint32_t)((P >> 24) & 0xFF)) & (0u - ok);

Why it works: write out the 64-bit product.

P = a<<8 + (10a+b)<<16 + (100a+10b+c)<<24 + (100b+10c)<<32 + 100c<<40

Since 100b + 10c is always even, bit 32 of P is bit 8 of the value, i.e. the “too big” flag (for a hundreds digit up to 3; bigger ones trip d’s own bits). P >> 1 drops it onto bit 31, where the 0x76 byte of K also parks a bad units digit, so one mask test catches both. The rev and the range compare disappear. On AArch64 the >> 1 can ride along in the orr for free, and (0 - 8*len) & 31 is a single neg w, w, lsl #3, since the hardware masks shift counts anyway.

No solution’s mask fits in a tst immediate, so with one call per string it is a tie. In a vectorized loop, clang emits 77 instructions per 16 strings instead of 108. Lean proves it too (so_eq). The search programs are in superopt/.

Batch It

The biggest win was never the parser. Drop the per-call overhead, parse a batch in a loop, and clang vectorizes anything branch-free 16 strings at a time.

Batch loop benchmark

The 32-bit form of the new test gets the same bits from (d >> 1) * 0x640a01, which is exact since d is even. Opus also hand-wrote a NEON version that skips SWAR entirely: test the digits bytewise, then build each value with one udot against weights (100, 10, 1) picked by length with tbl. Lean proves its lane logic for every uint8_t length.

Compiled vector code isn’t what bruteeq32 checked, so lemire8batch -x runs every compiled loop over all 2^32 words at lengths 0–8 and 255. All of them match, in 18 seconds on 24 cores.

Timings are from one machine (M2 Ultra, Apple clang), best of 5, with data in L1. Feedback is welcome.