← 输入框|github.com|刷新
Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions Doc/whatsnew/3.16.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1165,6 +1165,18 @@ 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.
:func:`base64.urlsafe_b64encode` and encoding with *altchars* get the same
speedup.
(Contributed by Gregory P. Smith in :gh:`124951`.)


datetime and time
-----------------

Expand Down
49 changes: 49 additions & 0 deletions Lib/test/test_binascii.py
Original file line number Diff line number Diff line change
Expand Up @@ -454,6 +454,55 @@ 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)),
]
# 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)
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"<~"
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +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. 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.
189 changes: 187 additions & 2 deletions Modules/binascii.c
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,14 @@
#ifdef USE_ZLIB_CRC32
# include "zlib.h"
#endif
#if (defined(__x86_64__) && defined(__GNUC__)) \
|| (defined(_M_X64) && !defined(_M_ARM64EC))
# include <tmmintrin.h> // SSSE3 intrinsics
# ifdef _MSC_VER
# include <intrin.h> // __cpuid()
# endif
# define BASE64_HAVE_SSSE3 1
#endif

typedef struct binascii_state {
PyObject *Error;
Expand Down Expand Up @@ -127,13 +135,180 @@ 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. 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.
* 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 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
# 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);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

While it doesn't matter for leaf 1, let's use __cpuidex(info, 1, 0); so that CPython sources are consistent.

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
* 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, 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. */
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. 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, 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) {
__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).
*/
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 (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;
}
#endif

Py_ssize_t n_trios = in_len / 3;
const unsigned char *in_end = in + n_trios * 3;

Expand All @@ -143,7 +318,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.
Expand Down Expand Up @@ -176,6 +351,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;

Expand All @@ -185,7 +370,7 @@ base64_decode_fast(const unsigned char *in, Py_ssize_t in_len,
}
}

return i * 4;
return done + i * 4;
}


Expand Down
Loading