From 6ecf8cebfc118846fa2ae5a086a8784dda8ef20c Mon Sep 17 00:00:00 2001 From: "Gregory P. Smith" Date: Sun, 29 Nov 2026 00:29:46 +0000 Subject: [PATCH 1/3] gh-124951: Use SSSE3 for base64 in binascii on x86-64 Encode and decode blocks of standard-alphabet base64 with SSSE3 before handing the rest of the input to the existing scalar loops. Those loops still handle the tail, padding, invalid characters and errors, so results and exceptions are unchanged. SSSE3 is part of x86-64-v2. A build that already targets it calls the kernels directly; otherwise they are compiled with a function target attribute and selected at run time with __builtin_cpu_supports(). This covers GCC and Clang; other compilers keep the scalar code. For 64 KiB inputs on an AMD Zen 2 with GCC 15, b2a_base64() goes from 2.2 to 9.5 GB/s and a2b_base64() from 1.8 to 6.9 GB/s. test_base64_long_inputs is adapted from Justin Bennington's GH-162443. Co-authored with Claude Fable 5.2. --- Doc/whatsnew/3.16.rst | 10 ++ Lib/test/test_binascii.py | 37 +++++ ...-11-28-23-53-38.gh-issue-124951.pSh8fB.rst | 3 + Modules/binascii.c | 151 +++++++++++++++++- 4 files changed, 199 insertions(+), 2 deletions(-) create mode 100644 Misc/NEWS.d/next/Library/2026-11-28-23-53-38.gh-issue-124951.pSh8fB.rst diff --git a/Doc/whatsnew/3.16.rst b/Doc/whatsnew/3.16.rst index 336171ca041f906..89e8ea3309c1b90 100644 --- a/Doc/whatsnew/3.16.rst +++ b/Doc/whatsnew/3.16.rst @@ -1165,6 +1165,16 @@ ast in :gh:`153568`.) +base64 and binascii +------------------- + +* Base64 encoding and decoding with the standard alphabet use SSSE3 + instructions on x86-64 CPUs that support them (everything since 2014). + For inputs of 64 KiB, :func:`base64.b64encode` and :func:`base64.b64decode` + are about 4 times faster. + (Contributed by Gregory P. Smith in :gh:`124951`.) + + datetime and time ----------------- diff --git a/Lib/test/test_binascii.py b/Lib/test/test_binascii.py index 94b1abd4079efd1..0a695e54f764a8c 100644 --- a/Lib/test/test_binascii.py +++ b/Lib/test/test_binascii.py @@ -454,6 +454,43 @@ def test_base64_alphabet(self): with self.assertRaises(TypeError): binascii.a2b_base64(data, alphabet=bytearray(alphabet)) + def test_base64_long_inputs(self): + # Cover all lengths and positions of a bad character across the + # block sizes of the vectorized code paths. + alphabets = [ + (b'!"#$%&\'()*+,-012345689@' + b'ABCDEFGHIJKLMNPQRSTUVXYZ[`abcdefhijklmpqr'), + bytes(range(0x80, 0xc0)), + ] + raw = bytes(range(256)) * 2 + for n in range(len(raw) + 1): + data = self.type2test(raw[:n]) + encoded = binascii.b2a_base64(data, newline=False) + self.assertEqual(binascii.a2b_base64(encoded), raw[:n]) + for alphabet in alphabets: + encoded = binascii.b2a_base64(data, newline=False, + alphabet=alphabet) + decoded = binascii.a2b_base64(encoded, alphabet=alphabet) + self.assertEqual(decoded, raw[:n]) + + encoded = binascii.b2a_base64(raw[:150], newline=False) + for i in range(len(encoded) + 1): + for c in b'*', b'\x80': + bad = self.type2test(encoded[:i] + c + encoded[i:]) + self.assertEqual(binascii.a2b_base64(bad), raw[:150]) + with self.assertRaises(binascii.Error): + binascii.a2b_base64(bad, strict_mode=True) + + # Every byte outside the alphabet in every position of a block. + invalid = bytes(set(range(256)) - set(binascii.BASE64_ALPHABET) + - set(b'=')) + for i in range(64, 80): + for c in invalid: + bad = self.type2test(encoded[:i] + bytes([c]) + encoded[i:]) + self.assertEqual(binascii.a2b_base64(bad), raw[:150]) + with self.assertRaises(binascii.Error): + binascii.a2b_base64(bad, strict_mode=True) + def test_ascii85_valid(self): # Test Ascii85 with valid data ASCII85_PREFIX = b"<~" diff --git a/Misc/NEWS.d/next/Library/2026-11-28-23-53-38.gh-issue-124951.pSh8fB.rst b/Misc/NEWS.d/next/Library/2026-11-28-23-53-38.gh-issue-124951.pSh8fB.rst new file mode 100644 index 000000000000000..e23b24f86b83e76 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-11-28-23-53-38.gh-issue-124951.pSh8fB.rst @@ -0,0 +1,3 @@ +Speed up base64 encoding and decoding with the standard alphabet in +:mod:`binascii` and :mod:`base64` on x86-64 CPUs that support SSSE3. +Large inputs are up to 4 times faster. diff --git a/Modules/binascii.c b/Modules/binascii.c index 406234cac1ed238..8f0d0086001a8b7 100644 --- a/Modules/binascii.c +++ b/Modules/binascii.c @@ -63,6 +63,10 @@ #ifdef USE_ZLIB_CRC32 # include "zlib.h" #endif +#if defined(__x86_64__) && defined(__GNUC__) +# include // SSSE3 intrinsics +# define BASE64_HAVE_SSSE3 1 +#endif typedef struct binascii_state { PyObject *Error; @@ -127,6 +131,129 @@ base64_encode_trio(const unsigned char *in, unsigned char *out, out[3] = table[combined & 0x3f]; } +#ifdef BASE64_HAVE_SSSE3 +/* + * SSSE3 base64 kernels for x86-64, standard alphabet only. + * + * PSHUFB serves both as a byte shuffle and as a 16-entry lookup table, + * which stands in for the per-character table lookups of the scalar code. + * The method is described in W. Mula and D. Lemire, "Faster Base64 Encoding + * and Decoding using AVX2 Instructions", ACM TOW 12(3), 2018. + * + * Each kernel handles a prefix of its input and returns how much of it was + * consumed. The scalar loops finish the rest and remain the reference for + * behaviour: padding, characters outside the alphabet and errors are never + * handled here. Neither kernel reads outside [in, in + in_len) or writes + * more than the scalar code would for the consumed prefix. + * + * SSSE3 is part of x86-64-v2. A build that does not target it compiles + * the kernels with a function target attribute and checks the CPU at run + * time. + */ +# ifdef __SSSE3__ +# define BASE64_SSSE3_TARGET +# define base64_cpu_has_ssse3() 1 +# else +# define BASE64_SSSE3_TARGET __attribute__((target("ssse3"))) +# define base64_cpu_has_ssse3() __builtin_cpu_supports("ssse3") +# endif + +/* Encode groups of 12 bytes into 16 characters. Every step loads 16 + * bytes, so at least the last 4 bytes of the input are left to the caller. + * Returns the number of bytes consumed. + */ +BASE64_SSSE3_TARGET static Py_ssize_t +base64_encode_ssse3(const unsigned char *in, Py_ssize_t in_len, + unsigned char *out) +{ + /* Put each group [b0 b1 b2] in a 32-bit lane as [b1 b0 b2 b1], so + * that every 6-bit field lies within one 16-bit half of the lane. */ + const __m128i spread = _mm_setr_epi8( + 1, 0, 2, 1, 4, 3, 5, 4, 7, 6, 8, 7, 10, 9, 11, 10); + /* The difference between a character and its 6-bit value. The index + * is 13 for 0..25 (A-Z), 0 for 26..51 (a-z), 1..10 for 52..61 (0-9), + * 11 for 62 (+) and 12 for 63 (/). */ + const __m128i offsets = _mm_setr_epi8( + 'a' - 26, '0' - 52, '0' - 52, '0' - 52, '0' - 52, '0' - 52, + '0' - 52, '0' - 52, '0' - 52, '0' - 52, '0' - 52, '+' - 62, + '/' - 63, 'A', 0, 0); + Py_ssize_t done = 0; + + for (; in_len - done >= 16; done += 12, out += 16) { + __m128i x = _mm_loadu_si128((const __m128i *)(in + done)); + x = _mm_shuffle_epi8(x, spread); + /* Move each 6-bit field into a byte of its own. A multiply shifts + * the two 16-bit halves of a lane by different amounts: the high + * product shifts right by 10 and 6, the low one left by 4 and 8. */ + __m128i ac = _mm_mulhi_epu16( + _mm_and_si128(x, _mm_set1_epi32(0x0fc0fc00)), + _mm_set1_epi32(0x04000040)); + __m128i bd = _mm_mullo_epi16( + _mm_and_si128(x, _mm_set1_epi32(0x003f03f0)), + _mm_set1_epi32(0x01000010)); + __m128i v = _mm_or_si128(ac, bd); + __m128i idx = _mm_subs_epu8(v, _mm_set1_epi8(51)); + __m128i upper = _mm_cmpgt_epi8(_mm_set1_epi8(26), v); + idx = _mm_or_si128(idx, _mm_and_si128(upper, _mm_set1_epi8(13))); + v = _mm_add_epi8(v, _mm_shuffle_epi8(offsets, idx)); + _mm_storeu_si128((__m128i *)out, v); + } + return done; +} + +/* Decode blocks of 16 characters into 12 bytes. Stops before the first + * block containing a character outside the alphabet, which is left for the + * caller to deal with. Returns the number of characters consumed. + */ +BASE64_SSSE3_TARGET static Py_ssize_t +base64_decode_ssse3(const unsigned char *in, Py_ssize_t in_len, + unsigned char *out) +{ + /* A character is in the alphabet iff the entries selected by its low + * and high nibbles have no bit in common. */ + const __m128i lut_lo = _mm_setr_epi8( + 0x15, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, + 0x11, 0x11, 0x13, 0x1a, 0x1b, 0x1b, 0x1b, 0x1a); + const __m128i lut_hi = _mm_setr_epi8( + 0x10, 0x10, 0x01, 0x02, 0x04, 0x08, 0x04, 0x08, + 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10); + /* The difference between a 6-bit value and its character, indexed by + * the high nibble. '/' shares its high nibble with '+' and uses + * index 1 instead. */ + const __m128i lut_roll = _mm_setr_epi8( + 0, 16, 19, 4, -65, -65, -71, -71, 0, 0, 0, 0, 0, 0, 0, 0); + /* Reverse the low 3 bytes of each 32-bit lane and drop the fourth. */ + const __m128i pack = _mm_setr_epi8( + 2, 1, 0, 6, 5, 4, 10, 9, 8, 14, 13, 12, -1, -1, -1, -1); + const __m128i nibble = _mm_set1_epi8(0x0f); + Py_ssize_t done = 0; + + for (; in_len - done >= 16; done += 16, out += 12) { + __m128i x = _mm_loadu_si128((const __m128i *)(in + done)); + __m128i lo = _mm_and_si128(x, nibble); + __m128i hi = _mm_and_si128(_mm_srli_epi32(x, 4), nibble); + __m128i bad = _mm_and_si128(_mm_shuffle_epi8(lut_lo, lo), + _mm_shuffle_epi8(lut_hi, hi)); + if (_mm_movemask_epi8(_mm_cmpgt_epi8(bad, _mm_setzero_si128()))) { + break; + } + /* The comparison gives -1 for '/', which turns its index 2 into 1. */ + __m128i slash = _mm_cmpeq_epi8(x, _mm_set1_epi8('/')); + x = _mm_add_epi8(x, _mm_shuffle_epi8(lut_roll, + _mm_add_epi8(hi, slash))); + /* Merge the 6-bit values pairwise into 12 bits, then 24 bits. */ + x = _mm_maddubs_epi16(x, _mm_set1_epi32(0x01400140)); + x = _mm_madd_epi16(x, _mm_set1_epi32(0x00011000)); + x = _mm_shuffle_epi8(x, pack); + /* Store exactly 12 bytes. */ + _mm_storel_epi64((__m128i *)out, x); + int last = _mm_cvtsi128_si32(_mm_srli_si128(x, 8)); + memcpy(out + 8, &last, 4); + } + return done; +} +#endif /* BASE64_HAVE_SSSE3 */ + /* Encode multiple complete 3-byte groups. * Returns the number of input bytes processed (always a multiple of 3). */ @@ -134,6 +261,16 @@ static inline Py_ssize_t base64_encode_fast(const unsigned char *in, Py_ssize_t in_len, unsigned char *out, const unsigned char *table) { + Py_ssize_t done = 0; +#ifdef BASE64_HAVE_SSSE3 + if (table == table_b2a_base64 && in_len >= 16 && base64_cpu_has_ssse3()) { + done = base64_encode_ssse3(in, in_len, out); + in += done; + out += done / 3 * 4; + in_len -= done; + } +#endif + Py_ssize_t n_trios = in_len / 3; const unsigned char *in_end = in + n_trios * 3; @@ -143,7 +280,7 @@ base64_encode_fast(const unsigned char *in, Py_ssize_t in_len, out += 4; } - return n_trios * 3; + return done + n_trios * 3; } /* Decode 4 base64 characters into 3 bytes. @@ -176,6 +313,16 @@ static inline Py_ssize_t base64_decode_fast(const unsigned char *in, Py_ssize_t in_len, unsigned char *out, const unsigned char *table) { + Py_ssize_t done = 0; +#ifdef BASE64_HAVE_SSSE3 + if (table == table_a2b_base64 && in_len >= 16 && base64_cpu_has_ssse3()) { + done = base64_decode_ssse3(in, in_len, out); + in += done; + out += done / 4 * 3; + in_len -= done; + } +#endif + Py_ssize_t n_quads = in_len / 4; Py_ssize_t i; @@ -185,7 +332,7 @@ base64_decode_fast(const unsigned char *in, Py_ssize_t in_len, } } - return i * 4; + return done + i * 4; } From 6069d29eddaafc741a983207108f92368d88e9c6 Mon Sep 17 00:00:00 2001 From: "Gregory P. Smith" Date: Sun, 29 Nov 2026 00:32:35 +0000 Subject: [PATCH 2/3] gh-124951: Enable the SSSE3 base64 kernels with MSVC and clang-cl Extend the compile-time gate to x64 Windows builds. MSVC accepts the SSSE3 intrinsics without a target option, so the kernels need no attribute there; clang-cl still gets the function target attribute. __builtin_cpu_supports() needs support from the compiler's runtime library, which the MSVC runtime does not provide, so on those toolchains the run-time check asks CPUID directly and caches the answer. Not yet built with MSVC. Checked by compiling with Clang for x86_64-pc-windows-msvc and by running the CPUID branch on Linux with a stand-in for __cpuid(). Co-authored with Claude Fable 5.2. --- Modules/binascii.c | 40 ++++++++++++++++++++++++++++++++++------ 1 file changed, 34 insertions(+), 6 deletions(-) diff --git a/Modules/binascii.c b/Modules/binascii.c index 8f0d0086001a8b7..31fb127b18c2b6e 100644 --- a/Modules/binascii.c +++ b/Modules/binascii.c @@ -63,8 +63,12 @@ #ifdef USE_ZLIB_CRC32 # include "zlib.h" #endif -#if defined(__x86_64__) && defined(__GNUC__) +#if (defined(__x86_64__) && defined(__GNUC__)) \ + || (defined(_M_X64) && !defined(_M_ARM64EC)) # include // SSSE3 intrinsics +# ifdef _MSC_VER +# include // __cpuid() +# endif # define BASE64_HAVE_SSSE3 1 #endif @@ -146,16 +150,40 @@ base64_encode_trio(const unsigned char *in, unsigned char *out, * handled here. Neither kernel reads outside [in, in + in_len) or writes * more than the scalar code would for the consumed prefix. * - * SSSE3 is part of x86-64-v2. A build that does not target it compiles - * the kernels with a function target attribute and checks the CPU at run - * time. + * SSSE3 is part of x86-64-v2. A build that does not target it checks the + * CPU at run time. GCC and Clang then need a function target attribute to + * compile the kernels; MSVC accepts the intrinsics as they are. */ # ifdef __SSSE3__ # define BASE64_SSSE3_TARGET # define base64_cpu_has_ssse3() 1 # else -# define BASE64_SSSE3_TARGET __attribute__((target("ssse3"))) -# define base64_cpu_has_ssse3() __builtin_cpu_supports("ssse3") +# if defined(__GNUC__) || defined(__clang__) +# define BASE64_SSSE3_TARGET __attribute__((target("ssse3"))) +# else +# define BASE64_SSSE3_TARGET +# endif +# ifdef _MSC_VER +/* 0 until CPUID has been asked, then 1 if the CPU has SSSE3 and -1 if not. + * __builtin_cpu_supports() is not used with the MSVC runtime, including by + * clang-cl, since it needs support from the compiler's runtime library. */ +static int base64_ssse3_state; + +static inline int +base64_cpu_has_ssse3(void) +{ + int state = _Py_atomic_load_int_relaxed(&base64_ssse3_state); + if (state == 0) { + int info[4]; + __cpuid(info, 1); + state = (info[2] & (1 << 9)) ? 1 : -1; // ECX bit 9: SSSE3 + _Py_atomic_store_int_relaxed(&base64_ssse3_state, state); + } + return state > 0; +} +# else +# define base64_cpu_has_ssse3() __builtin_cpu_supports("ssse3") +# endif # endif /* Encode groups of 12 bytes into 16 characters. Every step loads 16 From 2fdb8b8c84a0ca674b313cd044067a31ce307d99 Mon Sep 17 00:00:00 2001 From: "Gregory P. Smith" Date: Sun, 29 Nov 2026 01:27:51 +0000 Subject: [PATCH 3/3] gh-124951: Use the SSSE3 base64 encoder for URL-safe and altchars The SSSE3 encoder depends on the alphabet only through the two table entries for the values 62 and 63. Fill those in from the alphabet in use, and run the kernel for any alphabet whose first 62 characters are the standard ones. That covers base64.urlsafe_b64encode() and base64.b64encode() with altchars. Decoding is unchanged: its lookup tables are tied to '+' and '/'. For 64 KiB inputs on an AMD Zen 2 with GCC 15, urlsafe_b64encode() goes from 2.2 to 9.5 GB/s. Co-authored with Claude Fable 5.2. --- Doc/whatsnew/3.16.rst | 2 ++ Lib/test/test_binascii.py | 12 +++++++++ ...-11-28-23-53-38.gh-issue-124951.pSh8fB.rst | 4 ++- Modules/binascii.c | 26 +++++++++++++------ 4 files changed, 35 insertions(+), 9 deletions(-) diff --git a/Doc/whatsnew/3.16.rst b/Doc/whatsnew/3.16.rst index 89e8ea3309c1b90..b0a157f3f0824ef 100644 --- a/Doc/whatsnew/3.16.rst +++ b/Doc/whatsnew/3.16.rst @@ -1172,6 +1172,8 @@ base64 and binascii instructions on x86-64 CPUs that support them (everything since 2014). For inputs of 64 KiB, :func:`base64.b64encode` and :func:`base64.b64decode` are about 4 times faster. + :func:`base64.urlsafe_b64encode` and encoding with *altchars* get the same + speedup. (Contributed by Gregory P. Smith in :gh:`124951`.) diff --git a/Lib/test/test_binascii.py b/Lib/test/test_binascii.py index 0a695e54f764a8c..aade2d6b2250dbb 100644 --- a/Lib/test/test_binascii.py +++ b/Lib/test/test_binascii.py @@ -462,11 +462,23 @@ def test_base64_long_inputs(self): b'ABCDEFGHIJKLMNPQRSTUVXYZ[`abcdefhijklmpqr'), bytes(range(0x80, 0xc0)), ] + # Alphabets that differ from the standard one only in the last + # two characters. + variants = [ + binascii.URLSAFE_BASE64_ALPHABET, + binascii.BASE64_ALPHABET[:-2] + b'\xff\x80', + ] raw = bytes(range(256)) * 2 for n in range(len(raw) + 1): data = self.type2test(raw[:n]) encoded = binascii.b2a_base64(data, newline=False) self.assertEqual(binascii.a2b_base64(encoded), raw[:n]) + for alphabet in variants: + trans = bytes.maketrans(b'+/', alphabet[-2:]) + self.assertEqual( + binascii.b2a_base64(data, newline=False, + alphabet=alphabet), + encoded.translate(trans)) for alphabet in alphabets: encoded = binascii.b2a_base64(data, newline=False, alphabet=alphabet) diff --git a/Misc/NEWS.d/next/Library/2026-11-28-23-53-38.gh-issue-124951.pSh8fB.rst b/Misc/NEWS.d/next/Library/2026-11-28-23-53-38.gh-issue-124951.pSh8fB.rst index e23b24f86b83e76..5e1c979c4eed1e8 100644 --- a/Misc/NEWS.d/next/Library/2026-11-28-23-53-38.gh-issue-124951.pSh8fB.rst +++ b/Misc/NEWS.d/next/Library/2026-11-28-23-53-38.gh-issue-124951.pSh8fB.rst @@ -1,3 +1,5 @@ Speed up base64 encoding and decoding with the standard alphabet in :mod:`binascii` and :mod:`base64` on x86-64 CPUs that support SSSE3. -Large inputs are up to 4 times faster. +Large inputs are up to 4 times faster. Encoding is sped up in the same way +for the URL-safe alphabet and for any other alphabet that differs from the +standard one only in its last two characters. diff --git a/Modules/binascii.c b/Modules/binascii.c index 31fb127b18c2b6e..c1da70020e27f23 100644 --- a/Modules/binascii.c +++ b/Modules/binascii.c @@ -137,7 +137,9 @@ base64_encode_trio(const unsigned char *in, unsigned char *out, #ifdef BASE64_HAVE_SSSE3 /* - * SSSE3 base64 kernels for x86-64, standard alphabet only. + * SSSE3 base64 kernels for x86-64. The decoder handles the standard + * alphabet only. The encoder takes any alphabet whose first 62 characters + * are the standard ones, which includes the URL-safe alphabet. * * PSHUFB serves both as a byte shuffle and as a 16-entry lookup table, * which stands in for the per-character table lookups of the scalar code. @@ -192,7 +194,7 @@ base64_cpu_has_ssse3(void) */ BASE64_SSSE3_TARGET static Py_ssize_t base64_encode_ssse3(const unsigned char *in, Py_ssize_t in_len, - unsigned char *out) + unsigned char *out, const unsigned char *table) { /* Put each group [b0 b1 b2] in a 32-bit lane as [b1 b0 b2 b1], so * that every 6-bit field lies within one 16-bit half of the lane. */ @@ -200,11 +202,15 @@ base64_encode_ssse3(const unsigned char *in, Py_ssize_t in_len, 1, 0, 2, 1, 4, 3, 5, 4, 7, 6, 8, 7, 10, 9, 11, 10); /* The difference between a character and its 6-bit value. The index * is 13 for 0..25 (A-Z), 0 for 26..51 (a-z), 1..10 for 52..61 (0-9), - * 11 for 62 (+) and 12 for 63 (/). */ - const __m128i offsets = _mm_setr_epi8( + * 11 for 62 and 12 for 63. The last two entries depend on the + * alphabet and are filled in below. */ + const __m128i fixed_offsets = _mm_setr_epi8( 'a' - 26, '0' - 52, '0' - 52, '0' - 52, '0' - 52, '0' - 52, - '0' - 52, '0' - 52, '0' - 52, '0' - 52, '0' - 52, '+' - 62, - '/' - 63, 'A', 0, 0); + '0' - 52, '0' - 52, '0' - 52, '0' - 52, '0' - 52, 0, 0, 'A', 0, 0); + int last = (unsigned char)(table[62] - 62) + | ((unsigned char)(table[63] - 63) << 8); + const __m128i offsets = _mm_or_si128( + fixed_offsets, _mm_slli_si128(_mm_cvtsi32_si128(last), 11)); Py_ssize_t done = 0; for (; in_len - done >= 16; done += 12, out += 16) { @@ -291,8 +297,12 @@ base64_encode_fast(const unsigned char *in, Py_ssize_t in_len, { Py_ssize_t done = 0; #ifdef BASE64_HAVE_SSSE3 - if (table == table_b2a_base64 && in_len >= 16 && base64_cpu_has_ssse3()) { - done = base64_encode_ssse3(in, in_len, out); + if (in_len >= 16 + && (table == table_b2a_base64 + || memcmp(table, table_b2a_base64, 62) == 0) + && base64_cpu_has_ssse3()) + { + done = base64_encode_ssse3(in, in_len, out, table); in += done; out += done / 3 * 4; in_len -= done;