Decoding base64 email attachments, now with Nim
Daniel Lemire ranked programming languages by how fast their standard base64 decoder reads an email attachment, line breaks included. We ran his benchmark again and added Nim: the standard library, a faster plain-Nim decoder, two SIMD decoders written in Nim, and Nim calling simdutf. Every line of code behind the page, ours and Lemire's, is at the end of the page, folded file by file.
The question
The post (20 November 2026) makes one megabyte of random bytes, encodes it as base64 with 76-character lines ending in CRLF (1.37 MB of text, as in an email), and times the standard decoder of each language. The point: many fast decoders only work on base64 without line breaks, and fall back to a slow path at the first CRLF. simdutf removes line endings inside its vector loop, so everything built on it (C++, Node.js, Bun, Deno, PHP with his pull request, Python's fastpybase64) sits at the top, and the rest sits 10 to 30 times lower.
We used his code unchanged (same input generator, same protocol: check the bytes, warm up 600 calls, keep the best of 10 batches of 200 calls, median of runs) and wrote a Nim harness that follows the same protocol.
The ranking, with Nim
Median of 5 runs on one core of a cloud VM, see below. "preallocated" means the output buffer is reused across calls.
The same numbers as a table, made with tabelline from the same rows:
| MIME base64 decoding, GB/s | ||||
|---|---|---|---|---|
| median and range of 5 runs, one core | ||||
| # | GB/s | Runs | Language | Function |
| 1 | 15.2 | 15.0–15.4 | Python | fastpybase64 0.2.1 (icelake) b64decode |
| 2 | 14.4 | 14.3–14.7 | C++ | base64_to_binary |
| 3 | 14.2 | 14.1–15.1 | Nim | simdutf 9.4.0 (icelake) base64_to_binary via FFI (preallocated) |
| 4 | 12.8 | 12.7–12.9 | Node.js | Buffer.from(str,'base64') |
| 5 | 11.4 | 9.9–11.8 | Nim | AVX-512 VBMI2 decode (preallocated) |
| 6 | 11.1 | 9.9–11.7 | Nim | AVX-512 VBMI2 decode |
| 7 | 9.0 | 8.5–9.2 | Bun | Buffer.from(str,'base64') |
| 8 | 6.3 | 6.2–6.3 | Nim | nimsimd AVX2 decode |
| 9 | 6.3 | 6.2–6.5 | Nim | nimsimd AVX2 decode (preallocated) |
| 10 | 6.1 | 5.9–6.3 | Bun | Uint8Array.fromBase64(str) |
| 11 | 4.0 | 3.9–4.1 | Nim | scalar (4 tables) decode (preallocated) |
| 12 | 4.0 | 4.0–4.0 | Nim | scalar (4 tables) decode |
| 13 | 1.4 | 1.3–1.4 | Go | base64.StdEncoding.Decode (preallocated) |
| 14 | 1.2 | 1.2–1.3 | Go | base64.StdEncoding.DecodeString |
| 15 | 1.0 | 0.9–1.0 | Nim | std/base64 decode |
| 16 | 1.0 | 0.9–1.0 | Java | Base64.decode(byte[]) |
| 17 | 0.7 | 0.7–0.7 | Zig | std.base64 decoderWithIgnore("\r\n") |
| 18 | 0.5 | 0.5–0.5 | PHP | base64_decode(str) |
The code of this table (tabelline) lines 104–115
var ranking: seq[tuple[rank: int, gbps, lo, hi: float, lang, function: string]]
for i, r in ours:
ranking.add (i + 1, r.median, r.runs.min, r.runs.max, langName(r), "`" & r.function & "`")
let rankTable = tabella(ranking):
optCssTheme()
optRowStriping()
tabHeader "MIME base64 decoding, GB/s", &"median and range of {nRuns} runs, one core"
colsLabel {"rank": "#", "lang": "Language", "function": "Function", "gbps": "GB/s", "lo": "Runs"}
fmtMarkdown "function"
fmtNumber ["gbps", "lo", "hi"], decimals = 1
colsMergeRange "lo", "hi"
tabStyle style.text(weight = "bold"), loc.body(rows = where($it["lang"] == "Nim"))
Same tools, his machine and ours
| Same tools, two machines | |||
|---|---|---|---|
| GB/s, median of runs | |||
| Language | Lemire | Here | Function |
| C++ | 18.4 | 14.4 | base64_to_binary |
| Python | 16.4 | 15.2 | fastpybase64 0.1.4 (PR #5) (icelake) b64decode |
| Node.js | 13.3 | 12.8 | Buffer.from(str,'base64') |
| Bun | 14.2 | 9.0 | Buffer.from(str,'base64') |
| Bun | 9.4 | 6.1 | Uint8Array.fromBase64(str) |
| Go | 1.6 | 1.4 | base64.StdEncoding.Decode (preallocated) |
| Go | 1.5 | 1.2 | base64.StdEncoding.DecodeString |
| Java | 1.2 | 1.0 | Base64.decode(byte[]) |
| Zig | 0.8 | 0.7 | std.base64 decoderWithIgnore("\r\n") |
| PHP | 0.6 | 0.5 | base64_decode(str) |
Lemire: Xeon Gold 6548N, his results_big4_run*.txt. Here: a cloud VM, see above. | |||
The code of this table (tabelline) lines 135–149
var compare: seq[tuple[lang: string, his, here: float, function: string]]
for (sys, fn) in [("c++", "base64_to_binary"), ("python", "fastpybase64"), ("node", "Buffer.from"),
("bun", "Buffer.from"), ("bun", "fromBase64"), ("go", "preallocated"),
("go", "DecodeString"), ("java", "Base64"), ("zig", "decoderWithIgnore"),
("php 8.5", "base64_decode")]:
let a = his.pick(sys, fn)
compare.add (langName(a), a.median, ours.pick(sys.split(' ')[0], fn).median, "`" & a.function & "`")
let compareTable = tabella(compare):
optCssTheme()
optRowStriping()
tabHeader "Same tools, two machines", "GB/s, median of runs"
colsLabel {"lang": "Language", "function": "Function", "his": "Lemire", "here": "Here"}
fmtMarkdown "function"
fmtNumber ["his", "here"], decimals = 1
tabSourceNote md("Lemire: Xeon Gold 6548N, his `results_big4_run*.txt`. Here: a cloud VM, see above.")
The order is the same: simdutf-based decoders on top, then Go, Java, Zig and stock PHP an order of magnitude lower. Our absolute numbers are lower because of the slower clock and the older versions (Bun moved the most).
The Nim decoders
The three decoders we wrote end the same way: decodeTail in b64scalar.nim handles the last
few characters and the = padding, character by character. They differ in the hot loop.
Every one is checked on the benchmark input (length and byte sum, as in the other languages)
and in bench/nim/test.nim against std/base64 on random inputs of every size from 0 to
3,000 bytes, with CRLF, LF, space and no line breaks, and with one corrupted character that
must raise. Result: ok: 15005 round trips x 4 decoders, 14970 corrupted inputs rejected x 3 decoders.
1. std/base64: 1.0 GB/s
The standard library already copes with line breaks: before each group of four characters
it skips \r, \n and spaces. Each character is then a table lookup, a check and a shift,
written one byte at a time. That is about Go's speed (1.4 GB/s) and Java's
(1.0 GB/s), faster than Zig's decoderWithIgnore (0.7 GB/s), and twice stock PHP (0.5 GB/s).
2. Plain Nim, four tables: 4.0 GB/s
Base64 packs 3 bytes (24 bits) into 4 characters of 6 bits each. A plain decoder (like
std/base64) looks up each character's 6-bit value, checks it, then shifts and ORs the four
values together and writes three bytes one by one.
The trick comes from modp_b64, the base64 code of Nick Galbreath's stringencoders C library,
which Chromium ships as third_party/modp_b64 for its own base64 functions. It moves
the shifting into the tables: instead of one table of 6-bit values, four tables d0..d3, one per
position in the group of four. d0[c] holds the value of c already shifted to bits 23..18,
d1[c] to bits 17..12, and so on, and already in the byte order the CPU stores (little-endian).
Decoding a group is then four loads and three ORs, and one 4-byte store writes the three bytes
(the fourth byte is overwritten by the next group). An invalid character's entry has bits above
the 24 set, so one comparison of the result checks all four characters. With "TWFu", the base64
of "Man":
let quad = "TWFu"
let tables = [d0, d1, d2, d3]
var x = 0'u32
for k, c in quad:
echo "d", k, "['", c, "'] = 0x", tables[k][uint8 c].toHex(8)
x = x or tables[k][uint8 c]
echo "OR = 0x", x.toHex(8), " bytes in memory: ", [char(x and 0xFF), char(x shr 8 and 0xFF), char(x shr 16 and 0xFF)]
echo "d0['!'] = 0x", d0[uint8 '!'].toHex(8), " >= bad: invalid"
d0['T'] = 0x0000004C d1['W'] = 0x00006001 d2['F'] = 0x00400100 d3['u'] = 0x002E0000 OR = 0x006E614D bytes in memory: ['M', 'a', 'n'] d0['!'] = 0x01FFFFFF >= bad: invalid
A line ending is skipped when it starts a group, which it always does with 76-character lines
(76 is a multiple of 4). Anywhere else it sends the decoder to the slow path in decodeTail
for the rest of the input, the cliff Lemire's post is about: this decoder is fast for email and
PEM (64 is a multiple of 4 too), not for any line length.
bench/nim/b64scalar.nim lines 83–92while i + 4 < n:
let c0 = src[i]
if isSpace(c0):
inc i
continue
let x = d0[uint8 c0] or d1[uint8 src[i+1]] or d2[uint8 src[i+2]] or d3[uint8 src[i+3]]
if x >= bad: break # a space inside the quad, padding or a bad char
copyMem(addr dst[o], unsafeAddr x, 4)
i += 4
o += 3
# the three decoders on a small MIME input (lines of 8 characters here)
let mime = "SGVsbG8s\r\nIE5pbSBh\r\nbmQgYmFz\r\nZTY0IQ==\r\n"
echo decodeScalar(mime)
echo decodeAvx2(mime)
echo decodeAvx512(mime)
Hello, Nim and base64! Hello, Nim and base64! Hello, Nim and base64!
3. AVX2 with nimsimd: 6.3 GB/s
nimsimd gives Nim the x86 intrinsics up to AVX2. The decoder works on a 4 KB buffer in two steps:
- compact: copy the input 32 bytes at a time. A block with no byte at or below
0x20is one load and one store. A block with a line ending is compacted 8 bytes at a time with BMI2pext, which keeps the bytes a mask selects. - decode: the Muła–Lemire AVX2 algorithm: three
pshufblookups validate and translate 32 characters, two multiply-adds and two shuffles pack them into 24 bytes.
bench/nim/b64avx2.nim lines 69–94while b < BufSize and i + 32 <= m:
let x = ld(src[i].addr)
let mask = cast[uint32](mm256_movemask_epi8(
mm256_cmpeq_epi8(mm256_max_epu8(x, space), space))) # bytes <= 0x20
# only \r \n space tab may be dropped; anything else <= 0x20 is an error
let exact = cast[uint32](mm256_movemask_epi8(mm256_or_si256(
mm256_or_si256(mm256_cmpeq_epi8(x, cr), mm256_cmpeq_epi8(x, lf)),
mm256_or_si256(mm256_cmpeq_epi8(x, space), mm256_cmpeq_epi8(x, tab)))))
bad = bad or (exact xor mask)
# A clean block is one 32-byte store. Otherwise drop the marked bytes
# 8 at a time with BMI2 pext. (A branch-free version that always takes
# the pext path measured slower: about 5.5 vs 6.7 GB/s.)
if mask == 0:
mm256_storeu_si256(buf[b].addr, x)
b += 32
else:
for g in 0..3:
let m8 = (mask shr (8*g)) and 0xFF
var w: uint64
copyMem(w.addr, src[i + 8*g].addr, 8)
w = pext_u64(w, not expand[m8])
# a plain 8-byte store (copyMem here became a _FORTIFY_SOURCE
# __memcpy_chk call on Ubuntu's gcc)
cast[ptr uint64](buf[b].addr)[] = w
b += 8 - mm_popcnt_u32(m8).int # (std/bitops countSetBits compiled to a call here)
i += 32
On the same machine it decodes base64 without line breaks at about 10 GB/s, so the compaction step costs about a third.
4. AVX-512 VBMI2: 11.4 GB/s
nimsimd stops at AVX2, so b64avx512.nim imports the dozen AVX-512 intrinsics it needs
with importc. Same two steps, 64 bytes at a time, and both get simpler:
vpcompressb drops the line endings of a 64-byte block in one instruction (no branch at all),
and one vpermi2b translates 64 characters through a 128-entry table, as in Muła and Lemire's
AVX-512 decoder. That is roughly what simdutf does on this CPU (its "icelake" kernel); part of
the gap left (11.4 vs 14.4 GB/s) is probably that simdutf, as the post says, decodes
clean blocks straight from the input and compacts only the blocks that need it.
bench/nim/b64avx512.nim lines 75–83while b < BufSize and i + 64 <= m:
let x = mm512_loadu_si512(src[i].addr)
let ws = mm512_cmple_epu8_mask(x, space)
let exact = mm512_cmpeq_epi8_mask(x, cr) or mm512_cmpeq_epi8_mask(x, lf) or
mm512_cmpeq_epi8_mask(x, space) or mm512_cmpeq_epi8_mask(x, tab)
bad = bad or (ws xor exact)
mm512_storeu_si512(buf[b].addr, mm512_maskz_compress_epi8(not ws, x))
b += 64 - int(mm_popcnt_u64(ws))
i += 64
5. Nim calling simdutf: 14.2 GB/s
The same as PHP's pull request or Python's fastpybase64: Nim calls the C++ library. Nim
compiles to C here (the C backend, not nim cpp), and C cannot call a C++ function directly, so
simdutf_wrap.cpp is a small extern "C" wrapper around simdutf::base64_to_binary. g++
compiles it and simdutf into object files, simdutf.nim declares the wrapper's functions with
{.importc.} and links the objects with -lstdc++. With nim cpp one could instead call
simdutf directly with {.importcpp.} and no wrapper; it would run the same simdutf code.
C++, Python and Nim all run the same simdutf kernel ("icelake", the AVX-512 one), so they should be equally fast, and they are, within this machine's noise: 14.4, 15.2 and 14.2 GB/s. Calling through Python or Nim adds a few nanoseconds per call, nothing next to the 94 µs a call takes to decode 1.37 MB. The compiler is not it either: the C++ benchmark built with clang 18 instead of g++ 13 ran at the same speed (14.0 to 14.7 GB/s in three runs); the fastpybase64 wheel was built with clang 21.
Run it yourself
Everything is in this page's src/ folder:
bench/: Lemire's files (commit inbench/UPSTREAM_COMMIT; hiszig/main.zigandgo/), ourrun_cloud.sh, andbench/nim/with the decoders,bench.nim(the harness) andtest.nim.data/: the raw result lines of each run, ours and Lemire's.
From bench/, after python3 gen.py: build Lemire's programs as in his run.sh (Zig with
python3 -m ziglang build-exe -O ReleaseFast -lc zig/main.zig), then
g++ -O3 -c simdutf and nim/simdutf_wrap.cpp into nim/, and
nim c -d:danger nim/bench.nim. ./run_cloud.sh prints one run; this page reads all the
results_cloud_run*.txt files in data/ when it is built.
All the sources
Every file of the benchmark and of this page, as it ran. Tap a name to open it.
The Nim decoders and their harness
bench/nim/b64scalar.nim 99 lines
## Fast scalar MIME base64 decoder in plain Nim.
##
## Four 256-entry uint32 tables (the modp_b64 / Chromium trick) turn four
## characters into three bytes with four loads and three ORs. A bad character
## sets the top bit, so one comparison per quad validates it. Line endings
## (and spaces) are skipped wherever they occur.
const bad* = 0x01FF_FFFF'u32 ## any table entry >= bad marks an invalid character
func charValue(c: char): int =
case c
of 'A'..'Z': ord(c) - ord('A')
of 'a'..'z': ord(c) - ord('a') + 26
of '0'..'9': ord(c) - ord('0') + 52
of '+': 62
of '/': 63
else: -1
func makeTable(shift: int): array[256, uint32] =
# Output bytes are stored little-endian: byte0 | byte1 << 8 | byte2 << 16.
for i in 0..255:
let v = charValue(char(i))
if v < 0:
result[i] = bad
else:
# 24-bit big-endian value (v << shift), then byte-swapped into place.
let x = uint32(v) shl shift
result[i] = ((x shr 16) and 0xFF) or (x and 0xFF00) or ((x and 0xFF) shl 16)
const
d0* = makeTable(18) ## first character of a group: bits 23..18 of the 24
d1* = makeTable(12)
d2* = makeTable(6)
d3* = makeTable(0) ## fourth character: bits 5..0
template isSpace(c: char): bool = c in {'\r', '\n', ' ', '\t'}
proc decodeError(i: int) {.noinline, noreturn.} =
raise newException(ValueError, "invalid base64 character at " & $i)
func maxDecodedLen*(n: int): int = (n div 4) * 3 + 3
proc decodeTail*(src: ptr UncheckedArray[char], i0, n: int,
dst: ptr UncheckedArray[char], o0: int): int =
## Slow path: skips spaces character by character, handles padding.
## Returns the new output index.
var acc = 0'u32
var k = 0
var o = o0
var i = i0
while i < n:
let c = src[i]
inc i
if isSpace(c): continue
if c == '=': # padding: only more '=' and spaces may follow
while i < n:
if src[i] != '=' and not isSpace(src[i]): decodeError(i)
inc i
break
let v = charValue(c)
if v < 0: decodeError(i - 1)
acc = (acc shl 6) or uint32(v)
inc k
if k == 4:
dst[o] = char((acc shr 16) and 0xFF); dst[o+1] = char((acc shr 8) and 0xFF); dst[o+2] = char(acc and 0xFF)
o += 3; k = 0; acc = 0
case k
of 0: discard
of 2:
dst[o] = char((acc shr 4) and 0xFF); o += 1
of 3:
dst[o] = char((acc shr 10) and 0xFF); dst[o+1] = char((acc shr 2) and 0xFF); o += 2
else: decodeError(i)
o
proc decodeScalar*(src: ptr UncheckedArray[char], n: int,
dst: ptr UncheckedArray[char]): int =
## Decodes `n` characters of (line-broken) base64 at `src` into `dst`,
## which needs `maxDecodedLen(n) + 1` bytes. Returns the decoded length.
var i = 0
var o = 0
# Fast loop: whole quads with no space inside. 4-byte stores (3 valid).
while i + 4 < n:
let c0 = src[i]
if isSpace(c0):
inc i
continue
let x = d0[uint8 c0] or d1[uint8 src[i+1]] or d2[uint8 src[i+2]] or d3[uint8 src[i+3]]
if x >= bad: break # a space inside the quad, padding or a bad char
copyMem(addr dst[o], unsafeAddr x, 4)
i += 4
o += 3
decodeTail(src, i, n, dst, o)
proc decodeScalar*(s: string): string =
result = newStringUninit(maxDecodedLen(s.len) + 1)
let n = decodeScalar(cast[ptr UncheckedArray[char]](s.cstring), s.len,
cast[ptr UncheckedArray[char]](result.cstring))
result.setLen(n)
bench/nim/b64avx2.nim 126 lines
## AVX2 MIME base64 decoder in Nim, with nimsimd.
##
## Two steps on a small (L1-sized) buffer:
## 1. compact: copy the input 32 bytes at a time, dropping line endings.
## A clean block is one load and one store. A block with a line ending is
## compacted 8 bytes at a time with BMI2 `pext`.
## 2. decode: the Muła–Lemire AVX2 algorithm, 32 characters to 24 bytes,
## validating with three pshufb lookups.
## Line endings never send the decoder to a slow path.
import nimsimd/[avx2, bmi2, popcnt]
import b64scalar
when defined(gcc) or defined(clang):
{.localPassC: "-mavx2 -mbmi -mbmi2 -mpopcnt".}
const BufSize = 4096
proc lut(a: array[16, int8]): array[32, int8] =
for i in 0..15:
result[i] = a[i]
result[i+16] = a[i]
let
lutLoA = lut([0x15'i8, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11,
0x11, 0x11, 0x13, 0x1A, 0x1B, 0x1B, 0x1B, 0x1A])
lutHiA = lut([0x10'i8, 0x10, 0x01, 0x02, 0x04, 0x08, 0x04, 0x08,
0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10])
lutRollA = lut([0'i8, 16, 19, 4, -65, -65, -71, -71,
0, 0, 0, 0, 0, 0, 0, 0])
packA = lut([2'i8, 1, 0, 6, 5, 4, 10, 9, 8, 14, 13, 12, -1, -1, -1, -1])
permA = [0'i32, 1, 2, 4, 5, 6, -1, -1]
const expand = block: # 8-bit mask -> 0xFF in each marked byte
var t: array[256, uint64]
for m in 0..255:
for k in 0..7:
if (m shr k and 1) == 1: t[m] = t[m] or (0xFF'u64 shl (8*k))
t
template ld(p: pointer): M256i = mm256_loadu_si256(p)
proc decodeError(i: int) {.noinline, noreturn.} =
raise newException(ValueError, "invalid base64 character near " & $i)
proc decodeAvx2*(src: ptr UncheckedArray[char], n: int,
dst: ptr UncheckedArray[char]): int =
## `dst` needs `maxDecodedLen(n) + 32` bytes. Returns the decoded length.
let
lutLo = ld(lutLoA.unsafeAddr)
lutHi = ld(lutHiA.unsafeAddr)
lutRoll = ld(lutRollA.unsafeAddr)
pack = ld(packA.unsafeAddr)
perm = ld(permA.unsafeAddr)
mask2F = mm256_set1_epi8(0x2F'i8)
space = mm256_set1_epi8(0x20'i8)
cr = mm256_set1_epi8(0x0D'i8)
lf = mm256_set1_epi8(0x0A'i8)
tab = mm256_set1_epi8(0x09'i8)
k1 = mm256_set1_epi32(0x01400140'i32)
k2 = mm256_set1_epi32(0x00011000'i32)
var m = n # the vector loops stop before trailing padding
while m > 0 and src[m-1] in {'\r', '\n', ' ', '\t', '='}: dec m
var buf {.noinit.}: array[BufSize + 64, char]
var i, o, b = 0
while true:
# 1. compact into buf
var bad = 0'u32
while b < BufSize and i + 32 <= m:
let x = ld(src[i].addr)
let mask = cast[uint32](mm256_movemask_epi8(
mm256_cmpeq_epi8(mm256_max_epu8(x, space), space))) # bytes <= 0x20
# only \r \n space tab may be dropped; anything else <= 0x20 is an error
let exact = cast[uint32](mm256_movemask_epi8(mm256_or_si256(
mm256_or_si256(mm256_cmpeq_epi8(x, cr), mm256_cmpeq_epi8(x, lf)),
mm256_or_si256(mm256_cmpeq_epi8(x, space), mm256_cmpeq_epi8(x, tab)))))
bad = bad or (exact xor mask)
# A clean block is one 32-byte store. Otherwise drop the marked bytes
# 8 at a time with BMI2 pext. (A branch-free version that always takes
# the pext path measured slower: about 5.5 vs 6.7 GB/s.)
if mask == 0:
mm256_storeu_si256(buf[b].addr, x)
b += 32
else:
for g in 0..3:
let m8 = (mask shr (8*g)) and 0xFF
var w: uint64
copyMem(w.addr, src[i + 8*g].addr, 8)
w = pext_u64(w, not expand[m8])
# a plain 8-byte store (copyMem here became a _FORTIFY_SOURCE
# __memcpy_chk call on Ubuntu's gcc)
cast[ptr uint64](buf[b].addr)[] = w
b += 8 - mm_popcnt_u32(m8).int # (std/bitops countSetBits compiled to a call here)
i += 32
if bad != 0: decodeError(i)
# 2. decode buf, 32 characters at a time
var j = 0
while j + 32 <= b:
var v = ld(buf[j].addr)
let
hiNib = mm256_and_si256(mm256_srli_epi32(v, 4), mask2F)
loNib = mm256_and_si256(v, mask2F)
lo = mm256_shuffle_epi8(lutLo, loNib)
hi = mm256_shuffle_epi8(lutHi, hiNib)
eq2F = mm256_cmpeq_epi8(v, mask2F)
roll = mm256_shuffle_epi8(lutRoll, mm256_add_epi8(eq2F, hiNib))
if mm256_testz_si256(lo, hi) == 0: decodeError(i)
v = mm256_add_epi8(v, roll)
var w = mm256_madd_epi16(mm256_maddubs_epi16(v, k1), k2)
w = mm256_permutevar8x32_epi32(mm256_shuffle_epi8(w, pack), perm)
mm256_storeu_si256(dst[o].addr, w) # 24 useful bytes
j += 32; o += 24
if j < b: moveMem(buf[0].addr, buf[j].addr, b - j)
b -= j
if i + 32 > m: break
# leftover: < 32 clean chars in buf, then < 32 chars (+ padding) of input
var rest = newString(b + n - i)
if b > 0: copyMem(rest[0].addr, buf[0].addr, b)
if n > i: copyMem(rest[b].addr, src[i].addr, n - i)
decodeTail(cast[ptr UncheckedArray[char]](rest.cstring), 0, rest.len, dst, o)
proc decodeAvx2*(s: string): string =
result = newStringUninit(maxDecodedLen(s.len) + 32)
let n = decodeAvx2(cast[ptr UncheckedArray[char]](s.cstring), s.len,
cast[ptr UncheckedArray[char]](result.cstring))
result.setLen(n)
bench/nim/b64avx512.nim 105 lines
## AVX-512 (VBMI + VBMI2) MIME base64 decoder in Nim.
##
## nimsimd stops at AVX2, so the dozen intrinsics needed are imported here.
## Same two steps as the AVX2 version, 64 bytes at a time:
## 1. compact: `vpcompressb` drops the line endings of a 64-byte block in one
## instruction (no branch: every block takes the same path).
## 2. decode: Muła–Lemire AVX-512 VBMI: one `vpermi2b` translates 64
## characters through a 128-entry table, two multiply-adds and one
## `vpermb` pack them into 48 bytes.
import b64scalar
when defined(gcc) or defined(clang):
{.localPassC: "-mavx512f -mavx512bw -mavx512vbmi -mavx512vbmi2 -mpopcnt".}
type M512i {.importc: "__m512i", header: "immintrin.h", bycopy.} = object
{.push header: "immintrin.h".}
func mm512_loadu_si512(p: pointer): M512i {.importc: "_mm512_loadu_si512".}
proc mm512_storeu_si512(p: pointer, a: M512i) {.importc: "_mm512_storeu_si512".}
func mm512_set1_epi8(a: int8): M512i {.importc: "_mm512_set1_epi8".}
func mm512_set1_epi32(a: int32): M512i {.importc: "_mm512_set1_epi32".}
func mm512_cmple_epu8_mask(a, b: M512i): uint64 {.importc: "_mm512_cmple_epu8_mask".}
func mm512_cmpeq_epi8_mask(a, b: M512i): uint64 {.importc: "_mm512_cmpeq_epi8_mask".}
func mm512_maskz_compress_epi8(k: uint64, a: M512i): M512i {.importc: "_mm512_maskz_compress_epi8".}
func mm512_permutex2var_epi8(a, idx, b: M512i): M512i {.importc: "_mm512_permutex2var_epi8".}
func mm512_permutexvar_epi8(idx, a: M512i): M512i {.importc: "_mm512_permutexvar_epi8".}
func mm512_or_si512(a, b: M512i): M512i {.importc: "_mm512_or_si512".}
func mm512_movepi8_mask(a: M512i): uint64 {.importc: "_mm512_movepi8_mask".}
func mm512_maddubs_epi16(a, b: M512i): M512i {.importc: "_mm512_maddubs_epi16".}
func mm512_madd_epi16(a, b: M512i): M512i {.importc: "_mm512_madd_epi16".}
func mm_popcnt_u64(a: uint64): int64 {.importc: "_mm_popcnt_u64".}
{.pop.}
const BufSize = 4096
proc tables(): (array[64, int8], array[64, int8], array[64, int8]) =
const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
var t: array[128, int8]
for i in 0..127: t[i] = int8(-128) # 0x80 = invalid
for v, c in alphabet: t[ord(c)] = int8(v)
for i in 0..63:
result[0][i] = t[i]
result[1][i] = t[i + 64]
# pack: keep bytes 2,1,0 of each 32-bit word (16 words -> 48 bytes)
for k in 0..15:
result[2][3*k] = int8(4*k + 2)
result[2][3*k + 1] = int8(4*k + 1)
result[2][3*k + 2] = int8(4*k)
let (lut0A, lut1A, packA) = tables()
proc decodeError(i: int) {.noinline, noreturn.} =
raise newException(ValueError, "invalid base64 character near " & $i)
proc decodeAvx512*(src: ptr UncheckedArray[char], n: int,
dst: ptr UncheckedArray[char]): int =
## `dst` needs `maxDecodedLen(n) + 64` bytes. Returns the decoded length.
let
lut0 = mm512_loadu_si512(lut0A.unsafeAddr)
lut1 = mm512_loadu_si512(lut1A.unsafeAddr)
pack = mm512_loadu_si512(packA.unsafeAddr)
space = mm512_set1_epi8(0x20)
cr = mm512_set1_epi8(0x0D)
lf = mm512_set1_epi8(0x0A)
tab = mm512_set1_epi8(0x09)
k1 = mm512_set1_epi32(0x01400140'i32)
k2 = mm512_set1_epi32(0x00011000'i32)
var m = n
while m > 0 and src[m-1] in {'\r', '\n', ' ', '\t', '='}: dec m
var buf {.noinit.}: array[BufSize + 128, char]
var i, o, b = 0
while true:
var bad = 0'u64
while b < BufSize and i + 64 <= m:
let x = mm512_loadu_si512(src[i].addr)
let ws = mm512_cmple_epu8_mask(x, space)
let exact = mm512_cmpeq_epi8_mask(x, cr) or mm512_cmpeq_epi8_mask(x, lf) or
mm512_cmpeq_epi8_mask(x, space) or mm512_cmpeq_epi8_mask(x, tab)
bad = bad or (ws xor exact)
mm512_storeu_si512(buf[b].addr, mm512_maskz_compress_epi8(not ws, x))
b += 64 - int(mm_popcnt_u64(ws))
i += 64
if bad != 0: decodeError(i)
var j = 0
while j + 64 <= b:
let v = mm512_loadu_si512(buf[j].addr)
let t = mm512_permutex2var_epi8(lut0, v, lut1)
if mm512_movepi8_mask(mm512_or_si512(t, v)) != 0: decodeError(i)
let w = mm512_madd_epi16(mm512_maddubs_epi16(t, k1), k2)
mm512_storeu_si512(dst[o].addr, mm512_permutexvar_epi8(pack, w)) # 48 useful bytes
j += 64; o += 48
if j < b: moveMem(buf[0].addr, buf[j].addr, b - j)
b -= j
if i + 64 > m: break
var rest = newString(b + n - i)
if b > 0: copyMem(rest[0].addr, buf[0].addr, b)
if n > i: copyMem(rest[b].addr, src[i].addr, n - i)
decodeTail(cast[ptr UncheckedArray[char]](rest.cstring), 0, rest.len, dst, o)
proc decodeAvx512*(s: string): string =
result = newStringUninit(maxDecodedLen(s.len) + 64)
let n = decodeAvx512(cast[ptr UncheckedArray[char]](s.cstring), s.len,
cast[ptr UncheckedArray[char]](result.cstring))
result.setLen(n)
bench/nim/simdutf.nim 16 lines
## Nim binding to simdutf's base64 decoder (the library behind the top six).
{.passL: "simdutf_wrap.o simdutf.o -lstdc++".}
proc nsu_max_len(i: cstring, n: csize_t): csize_t {.importc, cdecl.}
proc nsu_decode(i: cstring, n: csize_t, o: cstring): csize_t {.importc, cdecl.}
proc nsu_impl(): cstring {.importc, cdecl.}
proc nsu_version(): cstring {.importc, cdecl.}
proc simdutfInfo*(): string = "simdutf " & $nsu_version() & " (" & $nsu_impl() & ")"
proc maxLen*(s: string): int = int nsu_max_len(s.cstring, csize_t s.len)
proc decodeInto*(s: string, dst: var string): int =
let r = nsu_decode(s.cstring, csize_t s.len, dst.cstring)
if r == high(csize_t): raise newException(ValueError, "invalid base64")
int r
proc decodeSimdutf*(s: string): string =
result = newStringUninit(maxLen(s))
result.setLen(decodeInto(s, result))
bench/nim/simdutf_wrap.cpp 12 lines
// Tiny C ABI over simdutf, so Nim (C backend) can call it.
#include "simdutf.h"
extern "C" {
size_t nsu_max_len(const char *in, size_t n) { return simdutf::maximal_binary_length_from_base64(in, n); }
// returns decoded length, or (size_t)-1 on error
size_t nsu_decode(const char *in, size_t n, char *out) {
auto r = simdutf::base64_to_binary(in, n, out);
return r.error == simdutf::error_code::SUCCESS ? r.count : (size_t)-1;
}
const char *nsu_impl() { return simdutf::get_active_implementation()->name().data(); }
const char *nsu_version() { return SIMDUTF_VERSION; }
}
bench/nim/bench.nim 48 lines
## MIME base64 decoding benchmark for Nim, same protocol as Lemire's mimebench:
## check the bytes once, warm up 3*200 calls, best of 10 batches of 200 calls.
import std/[base64, monotimes, times, strutils]
import b64scalar, b64avx2, b64avx512, simdutf
let (expLen, expSum) = block:
let p = readFile("../expected.txt").strip.split(' ')
(parseInt(p[0]), parseBiggestUInt(p[1]))
let data = readFile("../mime.txt")
var sink: int
proc check(n: int, o: openArray[char], label: string) =
var s = 0'u64
for i in 0..<n: s += uint64(uint8(o[i]))
if n != expLen or s != expSum: quit "bad decode " & label
proc bench(label: string, f: proc(): int) =
const iters = 200
for _ in 0..<3*iters: sink += f()
var best = Inf
for _ in 0..<10:
let st = getMonoTime()
for _ in 0..<iters: sink += f()
best = min(best, float((getMonoTime() - st).inNanoseconds) / iters)
echo "nim ", NimVersion, " mime ", label, ": ", formatFloat(data.len.float / best, ffDecimal, 2), " GB/s"
var r = base64.decode(data); check(r.len, r, "std")
bench("std/base64 decode") do () -> int: base64.decode(data).len
r = decodeScalar(data); check(r.len, r, "scalar")
bench("scalar (4 tables) decode") do () -> int: decodeScalar(data).len
var buf = newString(maxDecodedLen(data.len) + 64)
bench("scalar (4 tables) decode (preallocated)") do () -> int:
decodeScalar(cast[ptr UncheckedArray[char]](data.cstring), data.len, cast[ptr UncheckedArray[char]](buf.cstring))
r = decodeAvx2(data); check(r.len, r, "avx2")
bench("nimsimd AVX2 decode") do () -> int: decodeAvx2(data).len
bench("nimsimd AVX2 decode (preallocated)") do () -> int:
decodeAvx2(cast[ptr UncheckedArray[char]](data.cstring), data.len, cast[ptr UncheckedArray[char]](buf.cstring))
r = decodeAvx512(data); check(r.len, r, "avx512")
bench("AVX-512 VBMI2 decode") do () -> int: decodeAvx512(data).len
bench("AVX-512 VBMI2 decode (preallocated)") do () -> int:
decodeAvx512(cast[ptr UncheckedArray[char]](data.cstring), data.len, cast[ptr UncheckedArray[char]](buf.cstring))
r = decodeSimdutf(data); check(r.len, r, "simdutf")
var sbuf = newString(maxLen(data))
bench(simdutfInfo() & " base64_to_binary via FFI (preallocated)") do () -> int: decodeInto(data, sbuf)
bench/nim/test.nim 34 lines
## Random round trips against std/base64: sizes 0..3000, line widths 4..100,
## CRLF / LF / no line breaks, plus invalid characters that must raise.
import std/[base64, random]
import b64scalar, b64avx2, b64avx512, simdutf
randomize(42)
proc wrap(s: string, w: int, eol: string): string =
if w == 0: return s
for i in countup(0, s.len - 1, w):
result.add s[i ..< min(i + w, s.len)]
result.add eol
var cases, bad = 0
for size in 0..3000:
var raw = newString(size)
for c in raw.mitems: c = char(rand(255))
let enc = base64.encode(raw)
for (w, eol) in [(0, ""), (76, "\r\n"), (64, "\n"), (rand(1..100), "\r\n"), (rand(1..100), " ")]:
let s = wrap(enc, w, eol)
doAssert decodeScalar(s) == raw, "scalar " & $size & " " & $w
doAssert decodeAvx2(s) == raw, "avx2 " & $size & " " & $w
doAssert decodeAvx512(s) == raw, "avx512 " & $size & " " & $w
if eol != " ": doAssert decodeSimdutf(s) == raw
inc cases
if s.len > 10:
var t = s
t[rand(t.len - 3)] = sample({'\0', '\x01', '!', '-', '_', '\x80', '\xff', '#'})
template mustRaise(call: untyped, name: string) =
var raised = false
try: discard call except ValueError: raised = true
doAssert raised, name & " accepted bad char at size " & $size
inc bad
mustRaise(decodeScalar(t), "scalar")
mustRaise(decodeAvx2(t), "avx2")
mustRaise(decodeAvx512(t), "avx512")
echo "ok: ", cases, " round trips x 4 decoders, ", bad, " corrupted inputs rejected x 3 decoders"
Lemire's benchmark
Unchanged, from his repository (commit in bench/UPSTREAM_COMMIT), except run_cloud.sh, our
version of his run.sh for the tools of this machine.
bench/gen.py 11 lines
# Generates a MIME base64 input (76-char lines, CRLF).
import base64, random, sys, zlib
n = int(sys.argv[1]) if len(sys.argv) > 1 else 1_000_000
random.seed(1234)
raw = bytes(random.getrandbits(8) for _ in range(n))
plain = base64.b64encode(raw)
mime = b"\r\n".join(plain[i:i+76] for i in range(0, len(plain), 76)) + b"\r\n"
assert base64.b64decode(mime) == raw
open("mime.txt", "wb").write(mime)
open("expected.txt", "w").write(f"{len(raw)} {sum(raw)}\n")
print(f"decoded {len(raw)} bytes, mime {len(mime)} bytes")
bench/bench.cpp 37 lines
#include "simdutf.h"
#include <chrono>
#include <cstdio>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
static std::string slurp(const char *p) {
std::ifstream f(p, std::ios::binary); std::stringstream ss; ss << f.rdbuf(); return ss.str();
}
int main() {
size_t expLen; unsigned long long expSum;
{ std::ifstream f("expected.txt"); f >> expLen >> expSum; }
printf("simdutf %s, implementation %s\n", SIMDUTF_VERSION, simdutf::get_active_implementation()->name().data());
for (const char *name : {"mime"}) {
std::string in = slurp((std::string(name) + ".txt").c_str());
std::vector<char> out(simdutf::maximal_binary_length_from_base64(in.data(), in.size()));
auto decode = [&] {
auto r = simdutf::base64_to_binary(in.data(), in.size(), out.data());
if (r.error != simdutf::error_code::SUCCESS) { printf("error\n"); exit(1); }
return r.count;
};
size_t n = decode();
unsigned long long s = 0; for (size_t i = 0; i < n; i++) s += (unsigned char)out[i];
if (n != expLen || s != expSum) { printf("bad decode %s\n", name); return 1; }
const int iters = 200; volatile size_t sink = 0;
for (int i = 0; i < 3 * iters; i++) sink = decode();
double best = 1e300;
for (int t = 0; t < 10; t++) {
auto st = std::chrono::steady_clock::now();
for (int i = 0; i < iters; i++) sink = decode();
best = std::min(best, std::chrono::duration<double, std::nano>(std::chrono::steady_clock::now() - st).count() / iters);
}
printf("c++ simdutf %s base64_to_binary: %.2f GB/s\n", name, in.size() / best);
}
}
bench/bench.py 27 lines
import os, platform, sys, time
exp_len, exp_sum = map(int, open("expected.txt").read().split())
data = open("mime.txt", "rb").read()
cands = []
try:
import fastpybase64
cands.append((f"fastpybase64 {fastpybase64.__version__}{os.environ.get('FASTPYLABEL', '')} ({fastpybase64.get_implementation()}) b64decode", fastpybase64.b64decode))
except ImportError:
print("fastpybase64 not installed")
ver = f"python {platform.python_version()}"
for label, f in cands:
out = f(data)
if len(out) != exp_len or sum(out) != exp_sum:
sys.exit(f"bad decode {label}")
iters = 200
for _ in range(3 * iters):
f(data)
best = float("inf")
for _ in range(10):
st = time.perf_counter_ns()
for _ in range(iters):
f(data)
best = min(best, (time.perf_counter_ns() - st) / iters)
print(f"{ver} mime {label}: {len(data) / best:.2f} GB/s")
bench/bench.mjs 25 lines
import { readFileSync } from 'node:fs';
const [expLen, expSum] = readFileSync('expected.txt', 'latin1').trim().split(' ').map(Number);
function check(u8, name) {
let s = 0; for (const b of u8) s += b;
if (u8.length !== expLen || s !== expSum) throw new Error('bad decode ' + name);
}
let sink;
const runtime = globalThis.Bun ? `bun ${Bun.version}` : globalThis.Deno ? `deno ${Deno.version.deno}` : `node ${process.version}`;
function bench(label, f, inLen) {
check(f(), label);
const iters = 200;
for (let w = 0; w < 30; w++) for (let i = 0; i < iters; i++) sink = f();
let best = Infinity;
for (let t = 0; t < 10; t++) {
const st = process.hrtime.bigint();
for (let i = 0; i < iters; i++) sink = f();
best = Math.min(best, Number(process.hrtime.bigint() - st) / iters);
}
console.log(`${runtime} ${label}: ${(inLen / best).toFixed(2)} GB/s`);
}
for (const name of ['mime']) {
const s = readFileSync(name + '.txt', 'latin1');
bench(`${name} Buffer.from(str,'base64')`, () => Buffer.from(s, 'base64'), s.length);
if (Uint8Array.fromBase64) bench(`${name} Uint8Array.fromBase64(str)`, () => Uint8Array.fromBase64(s), s.length);
}
bench/go/main.go 64 lines
// MIME base64 decoding (76-character lines, CRLF) with encoding/base64,
// which ignores '\r' and '\n'.
package main
import (
"encoding/base64"
"fmt"
"os"
"runtime"
"time"
)
var sink int
func bench(label string, inLen, expLen int, expSum uint64, f func() []byte) {
out := f()
var s uint64
for _, b := range out {
s += uint64(b)
}
if len(out) != expLen || s != expSum {
panic("bad decode " + label)
}
iters := 200
for i := 0; i < 3*iters; i++ {
sink += len(f())
}
best := 1e300
for t := 0; t < 10; t++ {
st := time.Now()
for i := 0; i < iters; i++ {
sink += len(f())
}
best = min(best, float64(time.Since(st).Nanoseconds())/float64(iters))
}
fmt.Printf("go %s mime %s: %.2f GB/s\n", runtime.Version(), label, float64(inLen)/best)
}
func main() {
var expLen int
var expSum uint64
ef, _ := os.Open("expected.txt")
fmt.Fscan(ef, &expLen, &expSum)
in, err := os.ReadFile("mime.txt")
if err != nil {
panic(err)
}
str := string(in)
bench("base64.StdEncoding.DecodeString", len(in), expLen, expSum, func() []byte {
out, err := base64.StdEncoding.DecodeString(str)
if err != nil {
panic(err)
}
return out
})
dst := make([]byte, base64.StdEncoding.DecodedLen(len(in)))
bench("base64.StdEncoding.Decode (preallocated)", len(in), expLen, expSum, func() []byte {
n, err := base64.StdEncoding.Decode(dst, in)
if err != nil {
panic(err)
}
return dst[:n]
})
}
bench/zig/main.zig 50 lines
// MIME base64 decoding (76-character lines, CRLF) with std.base64's
// decoder that ignores chosen characters. Zig 0.17.
const std = @import("std");
const builtin = @import("builtin");
const Io = std.Io;
fn decode(d: anytype, a: std.mem.Allocator, in: []const u8) ![]u8 {
const buf = try a.alloc(u8, d.calcSizeUpperBound(in.len));
const n = try d.decode(buf, in);
return buf[0..n];
}
pub fn main(init: std.process.Init) !void {
const io = init.io;
const gpa = std.heap.c_allocator;
const cwd = Io.Dir.cwd();
const exp_txt = try cwd.readFileAlloc(io, "expected.txt", gpa, .unlimited);
var it = std.mem.tokenizeAny(u8, exp_txt, " \n");
const exp_len = try std.fmt.parseInt(usize, it.next().?, 10);
const exp_sum = try std.fmt.parseInt(u64, it.next().?, 10);
const input = try cwd.readFileAlloc(io, "mime.txt", gpa, .unlimited);
const decoder = std.base64.standard.decoderWithIgnore("\r\n");
const cap = decoder.calcSizeUpperBound(input.len);
const out = try decode(&decoder, gpa, input);
var s: u64 = 0;
for (out) |b| s += b;
if (out.len != exp_len or s != exp_sum) return error.BadDecode;
gpa.free(out.ptr[0..cap]);
const iters = 200;
for (0..3 * iters) |_| {
const o = try decode(&decoder, gpa, input);
std.mem.doNotOptimizeAway(o.ptr);
gpa.free(o.ptr[0..cap]);
}
var best: f64 = std.math.floatMax(f64);
for (0..10) |_| {
const st = Io.Timestamp.now(io, .awake);
for (0..iters) |_| {
const o = try decode(&decoder, gpa, input);
std.mem.doNotOptimizeAway(o.ptr);
gpa.free(o.ptr[0..cap]);
}
const ns: f64 = @floatFromInt(st.durationTo(Io.Timestamp.now(io, .awake)).nanoseconds);
best = @min(best, ns / iters);
}
std.debug.print("zig {s} mime std.base64 decoderWithIgnore(\"\\r\\n\"): {d:.2} GB/s\n", .{ builtin.zig_version_string, @as(f64, @floatFromInt(input.len)) / best });
}
bench/Bench.java 25 lines
import java.nio.file.*;
import java.util.Base64;
public class Bench {
static volatile Object sink;
public static void main(String[] args) throws Exception {
String[] exp = Files.readString(Path.of("expected.txt")).trim().split(" ");
int expLen = Integer.parseInt(exp[0]); long expSum = Long.parseLong(exp[1]);
run("mime", Files.readAllBytes(Path.of("mime.txt")), Base64.getMimeDecoder(), expLen, expSum);
}
static void run(String name, byte[] in, Base64.Decoder dec, int expLen, long expSum) {
byte[] out = dec.decode(in);
long s = 0; for (byte b : out) s += b & 0xff;
if (out.length != expLen || s != expSum) throw new RuntimeException("bad decode " + name);
int iters = 200;
for (int w = 0; w < 30; w++) for (int i = 0; i < iters; i++) sink = dec.decode(in); // warm-up (JIT)
double best = Double.MAX_VALUE;
for (int t = 0; t < 10; t++) {
long st = System.nanoTime();
for (int i = 0; i < iters; i++) sink = dec.decode(in);
best = Math.min(best, (System.nanoTime() - st) / (double) iters);
}
System.out.printf(java.util.Locale.ROOT, "java %s %s Base64.decode(byte[]): %.2f GB/s%n", Runtime.version(), name, in.length / best);
}
}
bench/bench.php 16 lines
<?php
[$expLen, $expSum] = array_map('intval', explode(' ', trim(file_get_contents('expected.txt'))));
foreach (['mime'] as $name) {
$s = file_get_contents("$name.txt");
$out = base64_decode($s);
if (strlen($out) !== $expLen || array_sum(unpack('C*', $out)) !== $expSum) die("bad decode $name\n");
$iters = 200;
for ($i = 0; $i < 3 * $iters; $i++) $out = base64_decode($s);
$best = PHP_FLOAT_MAX;
for ($t = 0; $t < 10; $t++) {
$st = hrtime(true);
for ($i = 0; $i < $iters; $i++) $out = base64_decode($s);
$best = min($best, (hrtime(true) - $st) / $iters);
}
printf("php %s%s %s base64_decode(str): %.2f GB/s\n", PHP_VERSION, getenv("PHPLABEL") ?: "", $name, strlen($s) / $best);
}
bench/rank.py 21 lines
"""Ranks the decoders by the median of several result files.
Usage: python3 rank.py results_big4_run*.txt > ranking_big4.md
"""
import re, statistics, sys
from collections import defaultdict
line_re = re.compile(r"^(.*?) mime (.*): ([0-9.]+) GB/s$")
speeds = defaultdict(list)
for path in sys.argv[1:]:
for line in open(path):
m = line_re.match(line.strip())
if m:
speeds[(m.group(1), m.group(2))].append(float(m.group(3)))
rows = sorted(((statistics.median(v), k, v) for k, v in speeds.items()), reverse=True)
print(f"MIME base64 decoding, 1 MB decoded (76-character lines, CRLF), GB/s of input, median of {len(sys.argv) - 1} runs.\n")
print("| rank | system | function | GB/s | runs |")
print("|---:|---|---|---:|---|")
for i, (med, (system, func), v) in enumerate(rows, 1):
print(f"| {i} | {system} | `{func}` | {med:.2f} | {' '.join(f'{x:.2f}' for x in v)} |")
bench/run_cloud.sh 15 lines
#!/bin/bash
# Lemire's mimebench, plus Nim, on whatever this machine has.
# Usage: ./run_cloud.sh > results_cloud_runN.txt
set -e
PIN=${PIN:-"taskset -c 2"}
uname -srm; grep -m1 "model name" /proc/cpuinfo; g++ --version | head -1; head -1 expected.txt
$PIN ./build/bench_cpp
$PIN build/gobench
$PIN build/zigbench 2>&1
env -u _JAVA_OPTIONS $PIN java -cp build Bench 2>&1 | grep -v JAVA_TOOL
$PIN node bench.mjs
$PIN bun bench.mjs
$PIN php bench.php
$PIN python3 bench.py
(cd nim && $PIN ./bench_nim)
This page
A nimib document; the tables are made with tabelline.
index.nim 345 lines
## Lemire's MIME base64 decoding ranking, replicated, with Nim added.
## Build: sh deps.sh && nim r index.nim (writes ../index.html; the numbers come from data/, written by bench/run_cloud.sh)
import std/[strformat, strutils, sequtils, os]
import nimib except md
import tabelline, tabelline/nimib
import lib/[data, blocks]
import lib/style as pagestyle # (as: tabelline exports a `style` too)
import review # tabelline's review mode, from shared/review at the root of this repository (config.nims)
import bench/nim/[b64scalar, b64avx2, b64avx512]
nbInit
nb.doc.filename = currentSourcePath().parentDir.parentDir / "index.html"
nb.title = "Decoding base64 email attachments, now with Nim"
nb.useExplainerStyle
nb.useSourceFooter
nbReview(tpage = "lemire-base64", tsource = "lemire-base64/src/index.nim")
# ---------------------------------------------------------------- data, at build time
let here = currentSourcePath().parentDir
let ours = readRuns(here / "data", "results_cloud_run")
let his = readRuns(here / "data", "results_big4_run")
let ourHeader = header(here / "data", "results_cloud_run1.txt")
let nRuns = toSeq(walkFiles(here / "data" / "results_cloud_run*.txt")).len
let testLine = readFile(here / "data" / "test_output.txt").strip
proc g(r: Speed): string = formatFloat(r.median, ffDecimal, 1)
let
nimStd = ours.pick("nim", "std/base64")
nimScalar = ours.pick("nim", "scalar (4 tables) decode (preallocated)")
nimAvx2 = ours.pick("nim", "nimsimd AVX2 decode (preallocated)")
nimAvx512 = ours.pick("nim", "AVX-512 VBMI2 decode (preallocated)")
nimFfi = ours.pick("nim", "simdutf")
cpp = ours.pick("c++", "base64_to_binary")
goPre = ours.pick("go", "preallocated")
java = ours.pick("java", "Base64")
php = ours.pick("php", "base64_decode")
zig = ours.pick("zig", "decoderWithIgnore")
func kindOf(r: Speed): BarKind =
if not r.isNim: bkOther
elif "simdutf" in r.function: bkFfi
else: bkNim
func langName*(r: Speed): string =
let sys = r.system.split(' ')[0]
case sys
of "c++": "C++"
of "nim": "Nim"
of "go": "Go"
of "java": "Java"
of "php": "PHP"
of "python": "Python"
of "node": "Node.js"
of "bun": "Bun"
of "zig": "Zig"
else: sys
func short(r: Speed): string =
&"**{langName(r)}** `{r.function}`"
# ---------------------------------------------------------------- the page
nbText: """
# Decoding base64 email attachments, **now with Nim**
"""
nbLede: &"""
Daniel Lemire ranked programming languages by how fast their standard base64 decoder
reads an email attachment, line breaks included. We ran his benchmark again and added Nim:
the standard library, a faster plain-Nim decoder, two SIMD decoders written in Nim, and Nim
calling simdutf. Every line of code behind the page, ours and Lemire's, is at the
end of the page, folded file by file.
"""
nbStats(@[
(value: g(nimStd), label: "GB/s, Nim's std/base64 (about Go and Java)"),
(value: g(nimScalar), label: "GB/s, plain Nim with lookup tables, no SIMD"),
(value: g(nimAvx512), label: "GB/s, Nim with AVX-512, about " & $int(100 * nimAvx512.median / cpp.median + 0.5) & "% of simdutf"),
(value: g(cpp), label: "GB/s, C++ simdutf, the top of the ranking"),
])
nbText: &"""
## The question
[The post](https://lemire.me/blog/2026/11/20/decoding-base64-email-attachments/) (20 November 2026)
makes one megabyte of random bytes, encodes it as base64 with 76-character lines ending in CRLF
(1.37 MB of text, as in an email), and times the standard decoder of each language. The point:
many fast decoders only work on base64 without line breaks, and fall back to a slow path at the
first CRLF. simdutf removes line endings inside its vector loop, so everything built on it
(C++, Node.js, Bun, Deno, PHP with his pull request, Python's fastpybase64) sits at the top,
and the rest sits 10 to 30 times lower.
We used [his code](https://github.com/lemire/Code-used-on-Daniel-Lemire-s-blog/tree/master/2026/11/javashell/mimebench)
unchanged (same input generator, same protocol: check the bytes, warm up 600 calls, keep the best
of 10 batches of 200 calls, median of runs) and wrote a Nim harness that follows the same protocol.
## The ranking, with Nim
"""
nbBars("MIME base64 decoding, GB/s of input (higher is faster)",
ours.mapIt((label: short(it), value: it.median, kind: kindOf(it))),
&"Median of {nRuns} runs on one core of a cloud VM, see below. \"preallocated\" means the output buffer is reused across calls.")
nbText: "The same numbers as a table, made with [tabelline](https://pietroppeter.github.io/tabelline/) from the same rows:"
var ranking: seq[tuple[rank: int, gbps, lo, hi: float, lang, function: string]]
for i, r in ours:
ranking.add (i + 1, r.median, r.runs.min, r.runs.max, langName(r), "`" & r.function & "`")
let rankTable = tabella(ranking):
optCssTheme()
optRowStriping()
tabHeader "MIME base64 decoding, GB/s", &"median and range of {nRuns} runs, one core"
colsLabel {"rank": "#", "lang": "Language", "function": "Function", "gbps": "GB/s", "lo": "Runs"}
fmtMarkdown "function"
fmtNumber ["gbps", "lo", "hi"], decimals = 1
colsMergeRange "lo", "hi"
tabStyle style.text(weight = "bold"), loc.body(rows = where($it["lang"] == "Nim"))
nbTable rankTable
nbFile "index.nim", start = "var ranking:", stop = "nbTable rankTable", folded = true,
title = "The code of this table ([tabelline](https://pietroppeter.github.io/tabelline/))"
nbNote(nkCareful, &"""
This is not Lemire's machine. It is a shared cloud VM: {ourHeader[1].split(':')[1].strip},
4 vCPUs, which reports CPU model 207, the same Emerald Rapids family as his Xeon Gold 6548N,
but at 2.1 GHz and shared with other machines, so runs vary. The same simdutf code ran at {g(cpp)} GB/s from C++ and
{g(nimFfi)} GB/s from Nim, with runs from {formatFloat(nimFfi.runs.min, ffDecimal, 1)} to
{formatFloat(nimFfi.runs.max, ffDecimal, 1)}: read differences under about 20% as noise.
The versions are the ones this machine has: g++ 13, Node.js 22, Go 1.27.0, Java 21, PHP 8.3,
Python 3.13 with fastpybase64 0.2.1, Bun 1.4.4, and Zig 0.17.1 (the same as Lemire's, from PyPI's
`ziglang` package). No Deno or .NET here.
""")
nbText: """
### Same tools, his machine and ours
"""
var compare: seq[tuple[lang: string, his, here: float, function: string]]
for (sys, fn) in [("c++", "base64_to_binary"), ("python", "fastpybase64"), ("node", "Buffer.from"),
("bun", "Buffer.from"), ("bun", "fromBase64"), ("go", "preallocated"),
("go", "DecodeString"), ("java", "Base64"), ("zig", "decoderWithIgnore"),
("php 8.5", "base64_decode")]:
let a = his.pick(sys, fn)
compare.add (langName(a), a.median, ours.pick(sys.split(' ')[0], fn).median, "`" & a.function & "`")
let compareTable = tabella(compare):
optCssTheme()
optRowStriping()
tabHeader "Same tools, two machines", "GB/s, median of runs"
colsLabel {"lang": "Language", "function": "Function", "his": "Lemire", "here": "Here"}
fmtMarkdown "function"
fmtNumber ["his", "here"], decimals = 1
tabSourceNote md("Lemire: Xeon Gold 6548N, his `results_big4_run*.txt`. Here: a cloud VM, see above.")
nbTable compareTable
nbFile "index.nim", start = "var compare:", stop = "nbTable compareTable", folded = true,
title = "The code of this table ([tabelline](https://pietroppeter.github.io/tabelline/))"
nbText: """
The order is the same: simdutf-based decoders on top, then Go, Java, Zig and stock PHP an
order of magnitude lower. Our absolute numbers are lower because of the slower clock and the older
versions (Bun moved the most).
"""
nbText: &"""
## The Nim decoders
The three decoders we wrote end the same way: `decodeTail` in `b64scalar.nim` handles the last
few characters and the `=` padding, character by character. They differ in the hot loop.
Every one is checked on the benchmark input (length and byte sum, as in the other languages)
and in `bench/nim/test.nim` against `std/base64` on random inputs of every size from 0 to
3,000 bytes, with CRLF, LF, space and no line breaks, and with one corrupted character that
must raise. Result: `{testLine}`.
### 1. `std/base64`: {g(nimStd)} GB/s
The standard library already copes with line breaks: before each group of four characters
it skips `\r`, `\n` and spaces. Each character is then a table lookup, a check and a shift,
written one byte at a time. That is about Go's speed ({g(goPre)} GB/s) and Java's
({g(java)} GB/s), faster than Zig's `decoderWithIgnore` ({g(zig)} GB/s), and twice stock PHP ({g(php)} GB/s).
### 2. Plain Nim, four tables: {g(nimScalar)} GB/s
Base64 packs 3 bytes (24 bits) into 4 characters of 6 bits each. A plain decoder (like
`std/base64`) looks up each character's 6-bit value, checks it, then shifts and ORs the four
values together and writes three bytes one by one.
The trick comes from **modp_b64**, the base64 code of Nick Galbreath's [*stringencoders*](https://github.com/client9/stringencoders) C library,
which Chromium ships as [`third_party/modp_b64`](https://github.com/chromium/chromium/tree/main/third_party/modp_b64) for its own base64 functions. It moves
the shifting into the tables: instead of one table of 6-bit values, four tables `d0`..`d3`, one per
position in the group of four. `d0[c]` holds the value of `c` already shifted to bits 23..18,
`d1[c]` to bits 17..12, and so on, and already in the byte order the CPU stores (little-endian).
Decoding a group is then four loads and three ORs, and one 4-byte store writes the three bytes
(the fourth byte is overwritten by the next group). An invalid character's entry has bits above
the 24 set, so one comparison of the result checks all four characters. With `"TWFu"`, the base64
of `"Man"`:
"""
nbCode:
let quad = "TWFu"
let tables = [d0, d1, d2, d3]
var x = 0'u32
for k, c in quad:
echo "d", k, "['", c, "'] = 0x", tables[k][uint8 c].toHex(8)
x = x or tables[k][uint8 c]
echo "OR = 0x", x.toHex(8), " bytes in memory: ", [char(x and 0xFF), char(x shr 8 and 0xFF), char(x shr 16 and 0xFF)]
echo "d0['!'] = 0x", d0[uint8 '!'].toHex(8), " >= bad: invalid"
nbText: &"""
A line ending is skipped when it starts a group, which it always does with 76-character lines
(76 is a multiple of 4). Anywhere else it sends the decoder to the slow path in `decodeTail`
for the rest of the input, the cliff Lemire's post is about: this decoder is fast for email and
PEM (64 is a multiple of 4 too), not for any line length.
"""
nbFile "bench/nim/b64scalar.nim", start = "while i + 4 < n:", stop = "decodeTail(src, i, n, dst, o)"
nbCode:
# the three decoders on a small MIME input (lines of 8 characters here)
let mime = "SGVsbG8s\r\nIE5pbSBh\r\nbmQgYmFz\r\nZTY0IQ==\r\n"
echo decodeScalar(mime)
echo decodeAvx2(mime)
echo decodeAvx512(mime)
nbText: &"""
### 3. AVX2 with nimsimd: {g(nimAvx2)} GB/s
[nimsimd](https://github.com/guzba/nimsimd) gives Nim the x86 intrinsics up to AVX2. The decoder
works on a 4 KB buffer in two steps:
1. **compact**: copy the input 32 bytes at a time. A block with no byte at or below `0x20` is
one load and one store. A block with a line ending is compacted 8 bytes at a time with
BMI2 `pext`, which keeps the bytes a mask selects.
2. **decode**: the Muła–Lemire AVX2 algorithm: three `pshufb` lookups validate and translate
32 characters, two multiply-adds and two shuffles pack them into 24 bytes.
"""
nbFile "bench/nim/b64avx2.nim", start = "while b < BufSize and i + 32", stop = "if bad != 0"
nbText: &"""
On the same machine it decodes base64 without line breaks at about 10 GB/s, so the
compaction step costs about a third.
### 4. AVX-512 VBMI2: {g(nimAvx512)} GB/s
nimsimd stops at AVX2, so `b64avx512.nim` imports the dozen AVX-512 intrinsics it needs
with `importc`. Same two steps, 64 bytes at a time, and both get simpler:
`vpcompressb` drops the line endings of a 64-byte block in one instruction (no branch at all),
and one `vpermi2b` translates 64 characters through a 128-entry table, as in Muła and Lemire's
AVX-512 decoder. That is roughly what simdutf does on this CPU (its "icelake" kernel); part of
the gap left ({g(nimAvx512)} vs {g(cpp)} GB/s) is probably that simdutf, as the post says, decodes
clean blocks straight from the input and compacts only the blocks that need it.
"""
nbFile "bench/nim/b64avx512.nim", start = "while b < BufSize and i + 64", stop = "if bad != 0"
nbText: &"""
### 5. Nim calling simdutf: {g(nimFfi)} GB/s
The same as PHP's pull request or Python's fastpybase64: Nim calls the C++ library. Nim
compiles to C here (the C backend, not `nim cpp`), and C cannot call a C++ function directly, so
`simdutf_wrap.cpp` is a small `extern "C"` wrapper around `simdutf::base64_to_binary`. g++
compiles it and simdutf into object files, `simdutf.nim` declares the wrapper's functions with
`{{.importc.}}` and links the objects with `-lstdc++`. With `nim cpp` one could instead call
simdutf directly with `{{.importcpp.}}` and no wrapper; it would run the same simdutf code.
C++, Python and Nim all run the same simdutf kernel ("icelake", the AVX-512 one), so they should
be equally fast, and they are, within this machine's noise: {g(cpp)}, {g(ours.pick("python", "fastpybase64"))}
and {g(nimFfi)} GB/s. Calling through Python or Nim adds a few nanoseconds per call, nothing
next to the {int(1368424.0 / cpp.median / 1000)} µs a call takes to decode
1.37 MB. The compiler is not it either: the C++ benchmark built with clang 18 instead of g++ 13
ran at the same speed (14.0 to 14.7 GB/s in three runs); the fastpybase64 wheel was built with clang 21.
"""
nbNote(nkReading, """
Three things made the AVX2 decoder slow while we wrote it. All three are fixed in the code on
this page (the numbers are before and after); each was found by reading the generated assembly:
- **`countSetBits` from `std/bitops`** showed up as a function call in the hot loop, where one
`popcnt` instruction was wanted. Fixed by using `mm_popcnt_u32` from nimsimd, which is the instruction.
- **`copyMem` into a stack array** became `__memcpy_chk`, because Ubuntu's gcc turns on
`_FORTIFY_SOURCE`. Each call also emitted a `vzeroupper`. Fixed with a plain 8-byte store
through a `ptr uint64`, which took the AVX2 decoder from 1.6 to 5.5 GB/s.
- **A branch-free compaction was slower** (5.5 GB/s) than branching on "is this block clean?"
(6.7 GB/s): with 78-byte lines more than half of the 32-byte blocks are clean, and the predictor copes.
The code keeps the branch.
""")
nbNote(nkNimib, &"""
The cheap win is the scalar decoder: plain Nim, no SIMD, no new dependency, and
{formatFloat(nimScalar.median / nimStd.median, ffDecimal, 1)}x faster than `std/base64` on email
attachments. It could go to the standard library as it is (with `decode` keeping its
signature). The SIMD decoders need a CPU check at run time (nimsimd's `runtimecheck`) before
they could be used anywhere but on a machine you know.
""")
nbText: """
## Run it yourself
Everything is in this page's [`src/` folder](https://github.com/pietroppeter/claude-artifacts/tree/main/lemire-base64/src):
- `bench/`: Lemire's files (commit in `bench/UPSTREAM_COMMIT`; his `zig/main.zig` and `go/`), our
`run_cloud.sh`, and `bench/nim/` with the decoders, `bench.nim` (the harness) and `test.nim`.
- `data/`: the raw result lines of each run, ours and Lemire's.
From `bench/`, after `python3 gen.py`: build Lemire's programs as in his `run.sh` (Zig with
`python3 -m ziglang build-exe -O ReleaseFast -lc zig/main.zig`), then
`g++ -O3 -c` simdutf and `nim/simdutf_wrap.cpp` into `nim/`, and
`nim c -d:danger nim/bench.nim`. `./run_cloud.sh` prints one run; this page reads all the
`results_cloud_run*.txt` files in `data/` when it is built.
"""
nbText: """
## All the sources
Every file of the benchmark and of this page, as it ran. Tap a name to open it.
### The Nim decoders and their harness
"""
for f in ["bench/nim/b64scalar.nim", "bench/nim/b64avx2.nim", "bench/nim/b64avx512.nim",
"bench/nim/simdutf.nim", "bench/nim/simdutf_wrap.cpp", "bench/nim/bench.nim", "bench/nim/test.nim"]:
nbFile f, folded = true
nbText: """
### Lemire's benchmark
Unchanged, from his repository (commit in `bench/UPSTREAM_COMMIT`), except `run_cloud.sh`, our
version of his `run.sh` for the tools of this machine.
"""
for f in ["bench/gen.py", "bench/bench.cpp", "bench/bench.py", "bench/bench.mjs", "bench/go/main.go",
"bench/zig/main.zig", "bench/Bench.java", "bench/bench.php", "bench/rank.py", "bench/run_cloud.sh"]:
nbFile f, folded = true, lang = (if f.endsWith(".mjs"): "js" else: "")
nbText: """
### This page
A [nimib](https://github.com/pietroppeter/nimib) document; the tables are made with
[tabelline](https://pietroppeter.github.io/tabelline/).
"""
for f in ["index.nim", "lib/data.nim", "lib/blocks.nim", "lib/style.nim", "config.nims", "deps.sh"]:
nbFile f, folded = true
nbSave
lib/data.nim 43 lines
## The benchmark results, read at build time from the files the runs wrote
## (same line format and the same median as Lemire's rank.py).
import std/[re, algorithm, strutils, tables, os, sequtils]
type Speed* = object
system*, function*: string
runs*: seq[float]
median*: float
func median(v: seq[float]): float =
let s = v.sorted
if s.len mod 2 == 1: s[s.len div 2] else: (s[s.len div 2 - 1] + s[s.len div 2]) / 2
proc readRuns*(dir, prefix: string): seq[Speed] =
## All `<prefix>*.txt` files in `dir`, one row per (system, function), fastest first.
let lineRe = re"^(.*?) mime (.*): ([0-9.]+) GB/s$"
var speeds = initOrderedTable[(string, string), seq[float]]()
for path in toSeq(walkFiles(dir / prefix & "*.txt")).sorted:
for line in lines(path):
var m: array[3, string]
if line.strip.match(lineRe, m):
speeds.mgetOrPut((m[0], m[1]), @[]).add parseFloat(m[2])
for k, v in speeds:
result.add Speed(system: k[0], function: k[1], runs: v, median: median(v))
result.sort(proc(a, b: Speed): int = cmp(b.median, a.median))
proc header*(dir, file: string): seq[string] =
## The first lines of a results file: kernel, CPU, compiler.
for line in lines(dir / file):
if " mime " in line: break
result.add line
func isNim*(r: Speed): bool = r.system.startsWith("nim ")
proc pick*(rows: seq[Speed], system, function: string): Speed =
## The row whose system starts with `system` and whose function contains `function`.
for r in rows:
if r.system.startsWith(system) and function in r.function: return r
raise newException(KeyError, "no result for " & system & " " & function)
func spread*(r: Speed): float =
## (max - min) / median, in percent: how noisy the runs were.
100 * (r.runs.max - r.runs.min) / r.median
lib/blocks.nim 87 lines
## The custom blocks of the base64 benchmark page. Classes only: every style is in style.nim.
## Bar widths are the only inline numbers (data).
import std/[strformat, strutils, json]
import nimib
type NoteKind* = enum
nkNimib = "nimib" ## what it means for Nim
nkReading = "reading" ## what we measured or found
nkCareful = "careful" ## a caveat
func noteLabel(k: NoteKind): string =
case k
of nkNimib: "For Nim"
of nkReading: "What we found"
of nkCareful: "Careful"
newNbBlock(NbNote):
level: NoteKind
text: string
toHtml:
&"""<aside class="note {blk.level}"><span class="note-label">{noteLabel(blk.level)}</span>{markdownToHtml(blk.text)}</aside>"""
template nbNote*(tkind: NoteKind, ttext: string) =
## A labelled aside: `nbNote(nkCareful, "A shared cloud machine.")`
nb.add newNbNote(level = tkind, text = ttext)
newNbBlock(NbLede):
text: string
toHtml:
&"""<div class="lede">{markdownToHtml(blk.text)}</div>"""
template nbLede*(ttext: string) =
## The opening paragraph, larger than body text.
nb.add newNbLede(text = ttext)
type Stat* = tuple[value, label: string]
newNbBlock(NbStats):
stats: seq[Stat]
toHtml:
var s = """<div class="stats">"""
for st in blk.stats:
s.add &"""<div class="stat"><div class="stat-value">{st.value}</div><div class="stat-label">{st.label}</div></div>"""
s & "</div>"
template nbStats*(tstats: seq[Stat]) =
## A row of headline numbers.
nb.add newNbStats(stats = tstats)
type
BarKind* = enum
bkNim = "nim" ## pure Nim
bkFfi = "ffi" ## Nim calling a C++ library
bkOther = "other" ## the other languages
Bar* = tuple[label: string, value: float, kind: BarKind]
func swatch(k: BarKind, label: string): string =
&"""<span class="key"><span class="swatch {k}"></span>{label}</span>"""
newNbBlock(NbBars):
title: string
note: string
bars: seq[Bar]
toHtml:
var top = 0.0
for b in blk.bars: top = max(top, b.value)
var s = &"""<figure class="chart"><figcaption>{blk.title}</figcaption><div class="legend">""" &
swatch(bkNim, "Nim") & swatch(bkFfi, "Nim calling simdutf") & swatch(bkOther, "other languages") &
"""</div><div class="bars">"""
for b in blk.bars:
let w = formatFloat(100 * b.value / max(top, 1e-9), ffDecimal, 1)
let v = formatFloat(b.value, ffDecimal, 1)
s.add &"""<div class="bar-row"><div class="bar-label">{markdownToHtml(b.label).strip.replace("<p>", "").replace("</p>", "")}</div><div class="bar-line"><span class="bar {b.kind}" style="width:{w}%"></span><span class="bar-value">{v} GB/s</span></div></div>"""
s.add "</div>"
if blk.note.len > 0: s.add &"""<p class="chart-note">{blk.note}</p>"""
s & "</figure>"
template nbBars*(ttitle: string, tbars: seq[Bar], tnote = "") =
## A horizontal bar chart of speeds, coloured by kind.
nb.add newNbBars(title = ttitle, bars = tbars, note = tnote)
func sourceFooter(blk: JsonNode, nb: Nb): string =
"""<span class="nb-small">After <a href="https://lemire.me/blog/2026/11/20/decoding-base64-email-attachments/">Daniel Lemire, “Decoding base64 email attachments”</a> (20 Nov 2026)</span>"""
proc useSourceFooter*(nb: var Nb) =
## The centre of the footer names the post this page replicates.
nb.backend.partials["footer_center"] = sourceFooter
lib/style.nim 110 lines
## The style module of the base64 benchmark page: every colour and CSS rule, from named tokens.
## Airmail: an envelope's red and blue stripes, Bricolage Grotesque and Source Sans; Nim's crown gold for Nim. Series colours are slots 1-3 of the validated default
## categorical palette (dataviz skill), as in the other explainers of this project.
import std/json
import nimib
const
fonts = """<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,wght@12..96,700;12..96,800&family=Source+Sans+3:wght@400;600;700&family=JetBrains+Mono:wght@400;600&display=swap" rel="stylesheet">"""
tokens = {
"--paper": "#f6f7fb", "--card": "#eceff6", "--ink": "#14213d", "--muted": "#4f5873",
"--line": "#d9deea", "--accent": "#1d4e9e", "--airmail-red": "#c8102e", "--airmail-blue": "#1d4e9e",
"--gold": "#f4c300", "--goldsoft": "#fdf0b8", "--white": "#ffffff",
"--one": "#2a78d6",
"--nimib": "#f4c300", "--reading": "#1baf7a", "--careful": "#eb6834", "--paper-note": "#2a78d6",
"--code-bg": "#ffffff",
# the names the review mode (shared/review, tabelline's) reads, from this page's own
"--surface": "#ffffff", "--shade": "#eceff6", "--secondary": "#f4c300", "--secondary-soft": "#fdf0b8",
"--primary-text": "#8a3550", "--font": "\"Source Sans 3\", system-ui, sans-serif", "--mono": "\"JetBrains Mono\", monospace", "--kw": "#8a1f7a", "--str": "#2d7a3a", "--num": "#9a5b00", "--com": "#7d8399"}
css = """
*{box-sizing:border-box}
[hidden]{display:none!important}
html{background:var(--paper)}
body{margin:0 auto;max-width:760px;padding:0 18px 48px;color:var(--ink);background:var(--paper);
font:17px/1.6 "Source Sans 3",system-ui,sans-serif}
header,footer .nb-box{display:flex;justify-content:space-between;align-items:center;gap:12px;
font:12px "Source Sans 3",sans-serif;color:var(--muted);padding:12px 0}
header{border-bottom:4px solid;border-image:repeating-linear-gradient(135deg,var(--airmail-red) 0 9px,var(--paper) 9px 14px,var(--airmail-blue) 14px 23px,var(--paper) 23px 28px) 4} footer .nb-box{border-top:1px solid var(--line);margin-top:40px}
header a,footer a{color:var(--muted)}
h1,h2,h3{font-family:"Bricolage Grotesque",system-ui,sans-serif;line-height:1.12;font-weight:700}
h1{font-size:clamp(34px,8vw,54px);margin:28px 0 8px}
h2{font-size:28px;margin:52px 0 10px}
h2::before{content:"";display:block;width:72px;height:6px;margin-bottom:12px;
background:repeating-linear-gradient(135deg,var(--airmail-red) 0 9px,var(--paper) 9px 14px,var(--airmail-blue) 14px 23px,var(--paper) 23px 28px)}
h1 strong{background:linear-gradient(transparent 60%,var(--gold) 60%);font-weight:700}
h3{font-size:20px;margin:28px 0 6px}
a{color:var(--accent);text-underline-offset:3px}
.lede{font-size:19px;line-height:1.55;color:var(--muted)}
.lede p{margin:8px 0}
p code,li code{font:14px "JetBrains Mono",monospace;background:var(--card);padding:1px 5px;border-radius:4px}
blockquote{margin:16px 0;padding:8px 16px;border-left:4px solid var(--accent);background:var(--card)}
table{border-collapse:collapse;display:block;overflow-x:auto;margin:14px 0;font-size:15px}
th{text-align:left;font-weight:600;border-bottom:2px solid var(--ink);padding:6px 8px}
td{border-bottom:1px solid var(--line);padding:6px 8px;vertical-align:top}
details{margin:14px 0;border:1px solid var(--line);border-radius:8px;padding:4px 14px;background:var(--card)}
details summary{cursor:pointer;font-weight:600;color:var(--muted);padding:6px 0}
/* code: small, scrolls inside its box (nimib-theme rules) */
body pre{margin:12px 0;overflow-x:auto;max-width:100%}
body pre > code{font-variant-ligatures:none;display:block;overflow-x:auto;padding:12px 14px;font:13px/1.5 "JetBrains Mono",monospace;
background:var(--code-bg);border-radius:6px;border:1px solid var(--line)}
body pre.nb-output{padding:10px 14px;font:13px/1.5 "JetBrains Mono",monospace;background:var(--ink);color:var(--paper);
border-radius:6px;white-space:pre}
.hljs-keyword{color:var(--kw);font-weight:600}.hljs-string{color:var(--str)}
.hljs-number,.hljs-literal,.hljs-type,.hljs-built_in{color:var(--num)}.hljs-comment{color:var(--com);font-style:italic}
/* files (nimib's nbFile): a name and a line count over the code, folded or not */
.nb-file{margin:12px 0}
details.nb-file{border:1px solid var(--line);border-radius:8px;background:var(--white);padding:0 12px}
details.nb-file[open]{padding-bottom:2px}
.nb-file-head{font:14px "JetBrains Mono",monospace;padding:10px 0;color:var(--ink)}
summary.nb-file-head{cursor:pointer;min-height:44px;display:list-item}
.nb-file-head code{font:600 14px "JetBrains Mono",monospace}
.nb-file-head .nb-small{color:var(--muted);font:13px "Source Sans 3",sans-serif;margin-left:6px}
details.nb-file pre{margin:0 0 10px}
/* notes */
.note{margin:18px 0;padding:10px 14px 4px;border-radius:8px;background:var(--card);border-left:5px solid var(--paper-note)}
.note.nimib{border-left-color:var(--nimib)} .note.reading{border-left-color:var(--reading)} .note.careful{border-left-color:var(--careful)}
.note-label{display:block;font:600 12px "Source Sans 3",sans-serif;letter-spacing:.08em;text-transform:uppercase;color:var(--muted)}
.note p{margin:4px 0 8px}
/* stat tiles */
.stats{display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:10px;margin:18px 0}
.stat{background:var(--white);border:1px solid var(--line);border-radius:10px;padding:12px 14px}
.stat-value{font:700 30px "Bricolage Grotesque",system-ui,sans-serif}
.stat-label{font-size:14px;color:var(--muted);line-height:1.35}
/* bars */
.legend{display:flex;flex-wrap:wrap;gap:12px;font-size:13px;color:var(--muted);margin-bottom:8px}
.key{display:inline-flex;align-items:center;gap:5px}
.swatch{width:12px;height:12px;border-radius:3px;display:inline-block}
.swatch.round{border-radius:50%}
.bar-row{margin:6px 0 10px}
.bar-label{font-size:14px;margin-bottom:3px;overflow-wrap:anywhere}
.bar-line{display:flex;align-items:center;gap:6px;height:12px}
.bar{height:10px;border-radius:0 4px 4px 0;min-width:2px;background:var(--one)}
.bar-value{font:12px "JetBrains Mono",monospace;color:var(--muted);white-space:nowrap}
.chart-note{font-size:13px;color:var(--muted);margin:6px 0 0}
.bar.nim{background:var(--gold)} .bar.ffi{background:var(--goldsoft);outline:1px solid var(--gold)} .bar.other{background:var(--one)}
.swatch.nim{background:var(--gold)} .swatch.ffi{background:var(--goldsoft);outline:1px solid var(--gold)} .swatch.other{background:var(--one)}
.bar-label b{font-weight:600}
.chart{margin:18px 0;padding:12px 14px;border:1px solid var(--line);border-radius:14px;background:var(--white)}
figcaption{font-weight:600;margin:4px 0 6px}
.bar-label .muted{color:var(--muted)}
"""
proc useExplainerStyle*(nb: var Nb) =
## Replace nimib's default theme (water.css and highlight.js from CDNs) with this page's
## own CSS, so the page is self-contained. Code is highlighted at build time by nimib.
var root = ":root{"
for (name, value) in tokens:
root.add name & ":" & value & ";"
root.add "}"
nb.doc.context["stylesheet"] = %(fonts & "<style>" & root & css & "</style>")
nb.doc.context["highlight"] = %""
nb.doc.context["highlightJs"] = %""
nb.doc.context["disableHighlightJs"] = %true
config.nims 8 lines
# Dependencies from deps.sh (LEMIRE_BASE64_DEPS, default ./deps).
import std/os
let deps = getEnv("LEMIRE_BASE64_DEPS", thisDir() / "deps")
for d in ["tabelline", "nimib", "fusion", "markdown", "parsetoml", "jsony"]:
switch("path", deps / d / "src")
switch("hints", "off")
# The review mode, shared by the pages of this repository (shared/review/README.md).
switch("path", thisDir() / ".." / ".." / "shared" / "review")
deps.sh 22 lines
#!/bin/sh
# Fetches nimib and its dependencies at pinned commits into
# $LEMIRE_BASE64_DEPS (default ./deps, not committed); config.nims puts them on the path.
set -e
here=$(cd "$(dirname "$0")" && pwd)
deps=${LEMIRE_BASE64_DEPS:-$here/deps}
mkdir -p "$deps"
while read -r name repo commit; do
d="$deps/$name"
if [ "$(git -C "$d" rev-parse HEAD 2>/dev/null)" != "$commit" ]; then
rm -rf "$d" && git init -q "$d"
git -C "$d" fetch -q --depth 1 "https://github.com/$repo" "$commit"
git -C "$d" checkout -q FETCH_HEAD
fi
done <<DEPS
tabelline pietroppeter/tabelline 47ba07b659481d408ad7be66e6bec7ef6b4c911f
nimib pietroppeter/nimib 4ecc850178665244328e383f1cae488234fc8d1e
fusion nim-lang/fusion 562467452b32cb7a97410ea177f083e6d8405734
markdown soasme/nim-markdown 995405b78fb49b7658b7f0d94efe1b52f86c0a85
parsetoml NimParsers/parsetoml d297f5a81be2472905d367aa675dcbbca6e7a5d2
jsony treeform/jsony ce1ea84458c721947bd8e86ec065eeefab2656f1
DEPS