Ce qu’il fait
- Hex avec SSSE3 et AVX2, base64 avec AVX2
- Cœur sans allocation, avec variantes en temps constant pour hex
- Base64 avec deux alphabets, trois modes de padding et rejet des formes non canoniques
- Base32 RFC 4648 et Crockford
- UTF-8, UTF-16 et UTF-32 (LE/BE), BOM, Latin-1 et Windows-1252
- Codecs en streaming avec 32 octets d'état
Mesuré
- Release, bloc de 64 KiB, Windows x64 MSVC / Linux x64 GCC. Hex : encode à 19.32 / 18.56 GB/s et décode à 14.40 / 14.53 GB/s (objectifs de 12 et 8 GB/s atteints)
- Base64 : encode à 12.44 / 11.79 GB/s et décode à 13.93 / 12.71 GB/s (objectifs de 8 et 6 GB/s atteints)
- Taille liée : 28 KiB
- Validation UTF-8, texte mixte : 6.7 GB/s avec AVX2. Objectif de 15 GB/s non atteint
Limites connues
- La validation UTF-8 atteint 6.7 GB/s avec AVX2 sur du texte mixte, en deçà de l'objectif de 15 GB/s
- Base32, percent, quoted-printable et transcodage sont scalaires et n'ont pas de couche C
Conversion from bytes to text and back. A leaf module: it includes no header from any other module of the library.
#include <ethereal/cpp/encoding/encoding_inc.hpp>
using namespace Ethereal::Encoding;
// Allocation-free path: the space belongs to the caller.
std::uint8_t aBytes[] = { 0xDE, 0xAD, 0xBE, 0xEF };
char aText[ 8 ];
std::size_t uWritten = 0;
if( HexEncode( aBytes, aText, uWritten ) != EEncodingError::eOk )
return 1;
// Convenience path, which allocates. Underneath it calls the one above.
const std::string sHex = ToHex( aBytes );---
What already exists
| Piece | Status |
|---|---|
EEncodingError, EncodingErrorName | ready |
Hex: HexEncode / HexDecode / HexDecodeAt + *Size | ready, with SSSE3 and AVX2 |
Hex: HexEncodeConstantTime / HexDecodeConstantTime | ready (scalar, on purpose) |
Base64: Base64Encode / Base64Decode / Base64DecodeAt + *Size | ready, with AVX2 |
| Base64: two alphabets, three padding modes, non-canonical rejection | ready |
Cpu::ESimdLevel, detection and ceiling for testing | ready (lives in the core, resource/) |
ToHex, FromHex, ToBase64, FromBase64 | old surface, now a shell over the core |
ToWide, ToUtf8, IsValidUtf8 | old surface, not yet rewritten |
IsValidUtf8At (and IsValidUnicode on UTF-8) + Utf8ValidatePath | ready, with SSE4.1, AVX2 and NEON (2026-10-16, stage 1 of AI-01) |
Vectorized UTF-8 validation. The Keiser and Lemire algorithm (2021): three lookups per nibble classify each pair of neighboring bytes, and a saturating subtraction on the bytes two and three positions back tells where the third and fourth bytes of the long sequences must be. The core validates whole 64-byte blocks (utf8_simd_sse.cpp, utf8_simd_avx2.cpp, utf8_simd_neon.cpp) and returns the start of the last sequence before the block with the error, or before the end. From there the scalar code finds the exact offset and reads the remainder: the result and the offset are always those of the scalar code alone. Below 64 bytes, or with the ceiling below SSE4.1, only the scalar code runs. NEON builds (checked with Clang for AArch64) and does not run on this test bench. The tests (encoding.utf8.simd, encoding.utf8.fuzz) compare each path with the scalar one: every invalid form at every offset from 0 to 200, random buffers from 0 to 4,096 bytes at every alignment from 0 to 63, and the short sequences exhaustively. Throughput on 1 MiB (i7-6700, GCC 15.2, Release): mixed-width text, scalar 348 MB/s, SSE4.1 6.1 GB/s, AVX2 6.7 GB/s. ASCII with one long code point every 16, scalar 0.9 GB/s, AVX2 9.4 GB/s.
Already in place, and covered in the last section of this document: Base32, percent-encoding, quoted-printable, Unicode transcoding among the five formats, BOM detection and removal, the single-byte encoders, line endings and the stream API.
Still missing: NEON for hex and base64, SSSE3 for base64, and the spec's throughput targets. The codecs added in this step are all scalar, and that is stated at the end.
The C ABI layer has existed since 2026-09-16. See its own section further down.
---
Measured performance
Release, 64 KiB block, 400 iterations. Throughput is counted over the bytes that go through memory: when decoding, that is the text consumed, which is twice the bytes produced.
| Measurement | Windows x64 (MSVC) | Linux x64 (GCC, on WSL) | Spec target |
|---|---|---|---|
| Hex encode scalar | 1.27 GB/s | 1.15 GB/s | n/a |
| Hex encode SSSE3 | 13.71 GB/s | 9.91 GB/s | n/a |
| Hex encode AVX2 | 19.32 GB/s | 18.56 GB/s | > 12 GB/s, met |
| Hex decode scalar | 0.37 GB/s | 0.76 GB/s | n/a |
| Hex decode SSSE3 | 7.01 GB/s | 8.60 GB/s | n/a |
| Hex decode AVX2 | 14.40 GB/s | 14.53 GB/s | > 8 GB/s, met |
| Base64 encode scalar | 1.41 GB/s | 1.51 GB/s | n/a |
| Base64 encode AVX2 | 12.44 GB/s | 11.79 GB/s | > 8 GB/s, met |
| Base64 decode scalar | 0.62 GB/s | 0.87 GB/s | n/a |
| Base64 decode AVX2 | 13.93 GB/s | 12.71 GB/s | > 6 GB/s, met |
| Base64 decode AVX2, URL alphabet | 6.15 GB/s | 7.34 GB/s | n/a |
cmake -S . -B build/bench -DCMAKE_BUILD_TYPE=Release -DETHEREAL_BUILD_BENCH=ON
cmake --build build/bench
./build/bench/bin/ethereal_bench_encodingThe spec's four throughput targets for Hex and Base64 were met, on both systems. The numbers vary by about 15 percent between runs. The ones in the table are from a typical run, and no run fell below the target.
Decoding with the URL alphabet gives about half the throughput of the standard one, and that is expected: it pays two extra comparisons and two extra blends to reject + and / and to translate - and _. Even so, it is ten times the scalar code.
---
Design notes
The old surface became a shell. ToHex, FromHex, ToBase64 and FromBase64 still exist, but underneath they call the allocation-free core. A single implementation: two implementations diverge, and on the day they diverge nobody knows which of the two is right.
Dispatch is by length before it is by instruction set, as the spec requires. Setting up the constant registers costs more than converting twenty bytes, so short input goes straight to the scalar code without even asking what the processor has.
The 16-entry hexadecimal table is allowed. The package rule forbids a table "where arithmetic is faster", and the example it gives is the 64-entry lookup of base64. Here the table fits in one register and pshufb resolves the 16 digits in a single instruction, against three for the arithmetic.
The vectorized decoding path requires the no-whitespace mode. A space in the middle shifts every following pair, and the fixed-size block no longer holds. The mode that skips whitespace is the slow one, and the spec already wanted it that way.
The constant-time variants are scalar on purpose, and the test suite can only check that they agree with the regular ones. Constant time cannot be measured in a test suite: the operating system noise is larger than the difference. An early exit was planted in them, breaking the constant time without changing the result, and it survived. That survival proves where the limit of the measurement is.
URL base64 reuses the table of the standard alphabet. Deriving a second lookup table by hand would be the most likely place for a silent error. Instead, the core rejects + and /, translates - to + and _ to /, and uses the same table that is already checked. It costs four instructions per block and eliminates an entire class of defect.
---
How this was verified
- 152 checks in the
encodingsection, on both systems. - RFC 4648 vectors in both directions, and 1,500 random round trips in both alphabets, with and without padding.
- Differential test per level: each vectorized path against the scalar one, at every length from 0 to 200 bytes. Without it, on a machine with AVX2 the SSSE3 code would never run.
- Adversarial input: the ten characters that sit one step outside each accepted range (
/,:,@,G, ``,g`, and bytes with the high bit set), at 80 positions, requiring every level to reject and point to the same position as the scalar code. - Space one byte short on every write and read, with a sentinel proving that nothing is written outside.
- Base64 differential: AVX2 against scalar at every length from 0 to 400 bytes, in both alphabets and both padding modes. The rejection is also compared character by character, with 14 poisons at 72 positions, requiring the same verdict and the same position.
- 53 planted defects (11 in the hex core, 14 in scalar base64, 11 in the hex vector cores, 4 in the hex dispatch, 13 in the base64 vector core). Four survivors, all analyzed and recorded in the code. None was a correctness defect.
The survivor that changed the design
Replacing ActiveSimdLevel() with DetectedSimdLevel() inside the dispatch survived, because AVX2 and scalar produce the same bytes. That meant the "scalar oracle" of the differential test might not be scalar at all, and the test would be comparing AVX2 with AVX2, always passing and measuring nothing.
The fix was the same one the event loop uses to declare whether it is on epoll or poll: the codec now declares its path, through HexEncodePath and HexDecodePath, and the decision now has a single source of truth. With that, the mutant dies.
The other three survivors
Two were equivalent, and both are recorded in the code so that nobody "simplifies" them the wrong way later:
- in hexadecimal, the shift of 31 can become 30 without changing anything, because the character comes from an
unsigned charand there any large shift yields the same mask. - in base64, the low bits of the mask
0x0FC0FC00do not matter, becausemulhireturns only the high half of the product.
The third is not a correctness defect, and no output test can catch it. Removing the translation of - and _ in the URL core makes the vector code reject those characters and stop, and the scalar code finishes the job, with the right result, at scalar speed. An output test cannot tell "the vector code did it" from "the vector code gave up".
What catches it is measurement: the B64 dec endereco line exists in the benchmark precisely so that this regression shows up as a number plummeting. The code says so.
---
Section 8, item by item
| item | status |
|---|---|
| 1: unit tests | smoke.encoding, 152 checks |
| 2: differential | already the strong point: every vector level against the scalar one, in both directions, for hex and base64, including the position of the error |
| 3: fuzz | encoding.fuzz (did not exist) |
| 4: sanitizer | linux-asan clean, and the fuzz runs 300,000 iterations under ASan |
| 5: baseline and gate | bench/encoding/baseline-linux.txt |
| 6: build matrix | 7 configurations, plus C11 and C17 for the C layer (which was written for this) |
| 7: failing allocator | core.noalloc, in both directions |
| 8: linked size | 28 KiB, the leanest of the three modules measured |
The missing fuzz (item 3)
The spec cites encoding by name when it asks for fuzz targets, and it had none. What existed was the SIMD vs. scalar differential. It is strong, but only over well-formed input: it proves that the two paths agree, and it does not prove that neither leaves the buffer when the text is garbage.
tests/encoding_fuzz.cpp has the usual two halves: LLVMFuzzerTestOneInput for libFuzzer/AFL++/OSS-Fuzz, and a mutation driver, because this test machine has no clang. It covers the nine decoding entry points, the two base64 alphabets, the three padding policies, the tolerant mode, whitespace skipping, the variants that report where, the constant-time one, and IsValidUtf8 checked against the ToWide/ToUtf8 round trip.
And it requires more than "did not crash". On every call: if it returned eOk, what it wrote has to fit in what was promised. If it returned an error, it cannot claim bytes written. The error position either falls inside the text or is the NO_ERROR_OFFSET sentinel.
The fuzzer found my own mistake first, twice
First. It failed on the initial run, saying that Base64DecodeAt pointed to an error outside the text. The fault was the test's: the contract provides NO_ERROR_OFFSET for a failure that has no position (a buffer that is too small is rejected without blaming any character). What is still worth requiring is that there be no third case.
Second, and this one is worth more. I planted an off-by-one on purpose in the space check of the final base64 group (uAt + 2u became uAt + 1u) and it survived 150,000 iterations under ASan.
The fuzzer was not weak. The reason was the geometry of the harness. I always passed the maximum output buffer (Base64DecodedSizeMax). With guaranteed slack, the checks uAt + N > Out.size() are never true. The whole family of buffer-edge defects, and the eBufferTooSmall branches in their entirety, were out of reach of the target. And the target said nothing about it: it said "no crash".
The buffer size now comes from the input itself: maximum, one less, two less, half, and zero. The same off-by-one died right away, with heap-buffer-overflow pointing at base64.cpp:443.
The rule: a fuzzer that only provides slack measures a different program from the one the customer uses.
The allocator, in both directions (item 7)
The module has two layers that promise opposite things. The core (HexEncode, Base64Decode, ...) writes into the caller's space and says in every @note that it does not allocate. The convenience layer (ToHex, ToBase64, FromHex) returns std::string/std::vector and allocates by design.
Requiring only the first half would be requiring a row of zeros, and a row of zeros is what a blind counter also produces. So the test requires both: the convenience functions have to allocate, and the tally only closes if the instrument is alive. They allocated 8,193, 5,465 and 4,096 bytes.
Proven with a planted defect: 24 bytes inside HexEncode failed the case by name.
The gate (item 5), and what it cannot tighten
Twelve throughput keys. On the first recording, three of them fell into the tight 5%, and the gate failed on its own at the next check, on those same three. It was the lesson already written in the playbook showing up in practice: seven recording iterations underestimate the spread.
Re-recorded with 20 iterations, the gate passed 3 out of 3 times in a row, and the measured truth is that none of the 12 keys reaches 5% on this machine. That is written in the baseline file, key by key, instead of being hidden behind a green result.
Proven with a planted defect: an extra pass over the input in HexEncode dropped Hex_encode/AVX2 from 16.8 to 1.4 GB/s against a limit of 9.7, and the gate failed.
The matrix (item 6), and what is missing from it
The seven configurations build and run. The C11/C17 half is also closed, and the C layer had to be written first. Until then include/ethereal/c/encoding/ was an empty folder, and that gap belonged to section 7, more than to section 8.
---
The C layer (section 7)
include/ethereal/c/encoding/encoding.h and src/c/encoding/encoding.cpp. Tests core.cabi and core.cabi.c17: the same source compiled under both standards.
There is no handle here, by architecture. The core of this module has no state: each call receives the input, receives the output space, and finishes. The opaque handle of section 7 exists for what has state. Inventing one to wrap stateless functions would create a lifetime where none exists.
Two more decisions:
- Text crosses as a pointer and a size, and zero termination is never assumed. A base64 that comes from a network packet is not terminated by anything. Requiring NUL would force the integrator to copy just to make the call, and the copy would be the size of the untrusted input.
- **
ToWideandToUtf8do not cross, and the header says so.**wchar_tis 16 bits on Windows and 32 on Linux: the same call would mean different things on the two sides and the ABI would no longer be an ABI. What crosses isETLC_EncodingIsValidUtf8, which answers about bytes and means the same everywhere.
The sentinel ETLC_ENCODING_NO_ERROR_OFFSET is tied to the C++ side's value by static_assert, because it is a number the caller compares before using it as an index. If the two sides disagreed, the integrator would read outside the text.
The C layer produced a fix in the size meter
Adding the layer to the module added 2,528 bytes of code, and the linked-size meter kept saying 39,144 bytes, the same number to the byte. The ELF file grows in steps of 4,096 bytes, and the entire addition fit in the slack. Today the verdict comes from the sum of the sections. With it, the module went from 24 to 28 KiB.
---
What spec 02 had pending, and was closed
Base32, percent-encoding, quoted-printable, Unicode transcoding among the five formats, the single-byte encoders, line endings and the stream codecs are delivered.
| Piece | File | Status |
|---|---|---|
| Base32: RFC 4648 and Crockford, with the ambiguity map | base32.hpp | ready |
| Percent-encoding, with a 256-bit map per URI component | percent.hpp | ready |
| Transcoding among UTF-8, UTF-16LE/BE and UTF-32LE/BE | unicode.hpp | ready |
Validation, IsAscii, CodePointCount, traversal in both directions | unicode.hpp | ready |
| BOM detection and removal in the five formats | unicode.hpp | ready |
| Latin-1 and Windows-1252, in both directions | unicode.hpp | ready |
| Line endings: detect and normalize, with the in-place variant | unicode.hpp | ready |
| Quoted-printable, with soft line break at 76 | stream.hpp | ready |
CEncoderStream and CDecoderStream | stream.hpp | ready |
---
There is no single "URL encode". There are eight, and choosing the wrong one is a defect
The spec asks for "precomputed 256-bit allowed-character bitmaps, one per URI component", because what is safe in one place of a URI may not be safe in another:
- a
/in the path is a segment separator and has to pass. Inside a segment it has to be encoded, otherwise the segment splits in two and the request goes somewhere else. - an
&in the query is a separator. Inside a parameter value it has to be encoded, otherwise a value containing an&invents a parameter nobody sent, one of the classic ways of fooling a server.
Using a map that is too permissive is a security flaw. Using one that is too restrictive is just ugly. So, when in doubt, the most restrictive one.
The test proves this head-on: the same input gives five different outputs for the five components, and there is a check dedicated solely to the path letting / through and the segment not.
The map is 256 bits, not a 256-byte table. Thirty-two bytes fit in half a cache line. The byte table takes four lines. In a loop that walks an entire URI, it is the difference between the map staying in L1 and being evicted by each block of input.
---
The three things a UTF-8 validator has to reject
Accepting bytes that are "almost" UTF-8 is a security flaw with a name of its own, however much it looks like tolerance.
Overlong sequences. / is 0x2F and fits in one byte, but C0 AF also decodes to / if the validator is not paying attention. A filter that looks for slashes finds none, and whatever comes next decodes it and has a slash. That is how people escaped from locked-down folders for years.
Surrogates. U+D800 to U+DFFF exist only as halves of a pair in UTF-16 and are not characters. A UTF-8 that carries them produces invalid UTF-16 when converted, and by the third conversion nobody knows any more where the garbage came from.
Above U+10FFFF. UTF-16 cannot represent those values, and that is why Unicode declared them nonexistent.
The six rejections (the three above, plus the truncated sequence and the stray continuation byte) are all in the test, one by one.
Validation is fused into decoding, in the same pass. Validating and then converting reads the input twice and opens a window in which it can change between the two reads.
The order of the byte order marks matters, and it is easy to swap
The UTF-32LE mark is FF FE 00 00 and the UTF-16LE mark is FF FE. The first two bytes are the same. If the two-byte mark were tested first, a UTF-32LE file would be read as UTF-16 and the whole text would come out interleaved with zeros. The four-byte one is tested first, and the test requires that.
Without a mark, nothing is guessed. DetectBom returns false and the caller decides. Guessing the encoding of a text from its bytes is how files get silently corrupted.
---
Base32 exists because people still read codes out loud
It takes 60% more space than base64 and still has not disappeared: its alphabet has no +, no /, and is case-insensitive. It is the format of almost everything someone has to dictate over the phone or write by hand: two-factor keys, recovery codes. A dictated base64 gets lost at the first lowercase l mistaken for 1.
Crockford goes further: it accepts the reading error instead of rejecting it. Whoever wrote O meant 0. Whoever wrote I or l meant 1. Without that map, half the value of the format disappears. It exists to be written by hand, and rejecting the most common mistake there is would be rejecting the use case.
The leftover bits have to be zero, and the test requires it: MY is the canonical form of f and passes. MZ gives the same byte with leftover bits and is rejected. Two forms of the same content become different identifiers when the text is compared, signed or used as a key.
Lengths the format does not produce are also rejected. A final group has 2, 4, 5 or 7 characters. With 1, 3 or 6 there is a whole character left over with no byte at all, and decoding gives eInvalidLength. Until 2026-10-05 only the group of 1 was rejected.
---
The stream codec, and the defect it had
The spec asks for state below 64 bytes and trivially destructible. Measured: 32 bytes each, and both promises are guaranteed by static_assert in the header, not just stated in a comment.
It had a real defect, which the test caught right away. A base64 text with padding has a length that is a multiple of four, and so the group with the = is a complete group like the others. The first version decoded that group in Update, with the rule "padding forbidden", which is right for the middle groups and wrong for the last one. Stream decoding failed at every chunk size.
The fix was for the decoder to always hold back the last complete group, so that Finish gets the only one that can have padding.
That is what the test proves: the three codecs, with chunks of 1 to 17 bytes (51 combinations), give exactly the same result as a single pass. The classic defect of a homemade streaming base64 is to encode each chunk separately and stuff padding into the middle of the output. That is exactly what these 51 combinations do not let through.
---
What was measured and is required by the tests
| allocations in one thousand base32 encodings | zero |
| allocations in one thousand percent-encodes | zero |
| allocations in one thousand transcodings | zero |
| allocations in one thousand UTF-8 validations | zero |
| stream encoder state | 32 bytes (the spec limit is 64) |
| stream decoder state | 32 bytes |
| percent-encoding round trip | 3,000 random inputs, exact |
| transcoding round trip | all 25 pairs of formats, exact |
| stream against single pass | 51 combinations, identical |
---
How this was verified
tests/encoding_codecs.cpp, 80 checks, green in Debug and Release.
Beyond the RFC 4648 vectors and the rejections, there are three properties that cannot be proven with examples: 3,000 random inputs through the percent-encoding of each component, all 25 pairs of Unicode formats in a round trip, and the 51 combinations of codec and chunk size in the stream.
Three defects the test caught, and two belonged to the test itself:
- the stream one, described above. That one was in the code.
- the Crockford test used a group of two characters, which leaves leftover bits and is therefore rejected as non-canonical. The property it meant to prove was a different one, and it now uses a whole group.
- the base32 test claimed that
MZwas canonical. It is not:MYis what the RFC saysfgives, andMZis exactly the non-canonical case the module has to reject. The test was asking for the opposite of what the spec requires.
---
What is still missing from 02-encoding
- NEON for hexadecimal and base64, and SSSE3 for base64. The vector paths that exist are those for hexadecimal (SSSE3 and AVX2), the one for base64 (AVX2) and the one for UTF-8 validation (SSE4.1, AVX2 and NEON). The new codecs of this step are all scalar.
- The spec's throughput target for UTF-8 validation (15 GB/s) is not met.
IsValidUtf8Athas used the three-nibble-table approach since 2026-10-16 and measures 6.7 GB/s with AVX2 on mixed-width text and 9.4 GB/s on ASCII with one long code point every 16 (see the beginning of this document). The base64 target (8 GB/s to encode) is met, at 12.44 GB/s. The oldIsValidUtf8, not yet rewritten, is still a scalar walk with a vectorized shortcut for the ASCII case. - The C ABI layer for the new codecs. The existing one covers hexadecimal, base64 and UTF-8 validation. Base32, percent, quoted-printable and transcoding do not cross yet.
- **
fuzzing** of each new parser.