Skip to content

Commit 7ab0470

Browse files
committed
gh-124951: Use NEON for base64 in binascii on AArch64
Encode and decode whole groups with NEON 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. NEON is part of the AArch64 baseline, so no build flags or runtime detection are needed.
1 parent fd71353 commit 7ab0470

8 files changed

Lines changed: 326 additions & 2 deletions

File tree

‎Doc/whatsnew/3.16.rst‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1137,6 +1137,15 @@ ast
11371137
in :gh:`153568`.)
11381138

11391139

1140+
base64 and binascii
1141+
-------------------
1142+
1143+
* Base64 encoding and decoding use NEON instructions on AArch64. For inputs
1144+
of 64 KiB, :func:`base64.b64encode` is about 5x faster and
1145+
:func:`base64.b64decode` about 3x faster on an Apple M5.
1146+
(Contributed by Justin Bennington in :gh:`124951`.)
1147+
1148+
11401149
datetime and time
11411150
-----------------
11421151

‎Lib/test/test_binascii.py‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -453,6 +453,33 @@ def test_base64_alphabet(self):
453453
with self.assertRaises(TypeError):
454454
binascii.a2b_base64(data, alphabet=bytearray(alphabet))
455455

456+
def test_base64_long_inputs(self):
457+
# Cover all lengths and positions of a bad character across the
458+
# block sizes of the vectorized code paths.
459+
alphabets = [
460+
(b'!"#$%&\'()*+,-012345689@'
461+
b'ABCDEFGHIJKLMNPQRSTUVXYZ[`abcdefhijklmpqr'),
462+
bytes(range(0x80, 0xc0)),
463+
]
464+
raw = bytes(range(256)) * 2
465+
for n in range(len(raw) + 1):
466+
data = self.type2test(raw[:n])
467+
encoded = binascii.b2a_base64(data, newline=False)
468+
self.assertEqual(binascii.a2b_base64(encoded), raw[:n])
469+
for alphabet in alphabets:
470+
encoded = binascii.b2a_base64(data, newline=False,
471+
alphabet=alphabet)
472+
decoded = binascii.a2b_base64(encoded, alphabet=alphabet)
473+
self.assertEqual(decoded, raw[:n])
474+
475+
encoded = binascii.b2a_base64(raw[:150], newline=False)
476+
for i in range(len(encoded) + 1):
477+
for c in b'*', b'\x80':
478+
bad = self.type2test(encoded[:i] + c + encoded[i:])
479+
self.assertEqual(binascii.a2b_base64(bad), raw[:150])
480+
with self.assertRaises(binascii.Error):
481+
binascii.a2b_base64(bad, strict_mode=True)
482+
456483
def test_ascii85_valid(self):
457484
# Test Ascii85 with valid data
458485
ASCII85_PREFIX = b"<~"

‎Makefile.pre.in‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3516,6 +3516,7 @@ MODULE_DEPS_SHARED=@MODULE_DEPS_SHARED@
35163516
MODULE__CURSES_DEPS=$(srcdir)/Include/py_curses.h
35173517
MODULE__CURSES_PANEL_DEPS=$(srcdir)/Include/py_curses.h
35183518
MODULE__DATETIME_DEPS=$(srcdir)/Include/datetime.h
3519+
MODULE_BINASCII_DEPS=$(srcdir)/Modules/binascii_neon.h
35193520
MODULE_CMATH_DEPS=$(srcdir)/Modules/_math.h
35203521
MODULE_MATH_DEPS=$(srcdir)/Modules/_math.h
35213522
MODULE_PYEXPAT_DEPS=@LIBEXPAT_INTERNAL@
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Base64 encoding and decoding in :mod:`binascii` and :mod:`base64` now use
2+
NEON instructions on AArch64 and are up to 5x faster for large inputs.

‎Modules/binascii.c‎

Lines changed: 31 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -127,13 +127,31 @@ base64_encode_trio(const unsigned char *in, unsigned char *out,
127127
out[3] = table[combined & 0x3f];
128128
}
129129

130+
#include "binascii_neon.h"
131+
132+
#ifdef BINASCII_HAVE_NEON
133+
/* Shorter inputs are faster with the scalar loops alone. */
134+
# define BASE64_NEON_MIN_ENCODE 24
135+
# define BASE64_NEON_MIN_DECODE 32
136+
#endif
137+
130138
/* Encode multiple complete 3-byte groups.
131139
* Returns the number of input bytes processed (always a multiple of 3).
132140
*/
133141
static inline Py_ssize_t
134142
base64_encode_fast(const unsigned char *in, Py_ssize_t in_len,
135143
unsigned char *out, const unsigned char *table)
136144
{
145+
Py_ssize_t done = 0;
146+
#ifdef BINASCII_HAVE_NEON
147+
if (in_len >= BASE64_NEON_MIN_ENCODE) {
148+
done = base64_encode_neon(in, in_len, out, table);
149+
in += done;
150+
out += done / 3 * 4;
151+
in_len -= done;
152+
}
153+
#endif
154+
137155
Py_ssize_t n_trios = in_len / 3;
138156
const unsigned char *in_end = in + n_trios * 3;
139157

@@ -143,7 +161,7 @@ base64_encode_fast(const unsigned char *in, Py_ssize_t in_len,
143161
out += 4;
144162
}
145163

146-
return n_trios * 3;
164+
return done + n_trios * 3;
147165
}
148166

149167
/* Decode 4 base64 characters into 3 bytes.
@@ -176,6 +194,17 @@ static inline Py_ssize_t
176194
base64_decode_fast(const unsigned char *in, Py_ssize_t in_len,
177195
unsigned char *out, const unsigned char *table)
178196
{
197+
Py_ssize_t done = 0;
198+
#ifdef BINASCII_HAVE_NEON
199+
if (in_len >= BASE64_NEON_MIN_DECODE) {
200+
done = base64_decode_neon(in, in_len, out, table,
201+
table == table_a2b_base64);
202+
in += done;
203+
out += done / 4 * 3;
204+
in_len -= done;
205+
}
206+
#endif
207+
179208
Py_ssize_t n_quads = in_len / 4;
180209
Py_ssize_t i;
181210

@@ -185,7 +214,7 @@ base64_decode_fast(const unsigned char *in, Py_ssize_t in_len,
185214
}
186215
}
187216

188-
return i * 4;
217+
return done + i * 4;
189218
}
190219

191220

‎Modules/binascii_neon.h‎

Lines changed: 252 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,252 @@
1+
/* AArch64 NEON helpers for the base64 fast paths in binascii.c.
2+
*
3+
* Both functions process a prefix of the input and return how much they
4+
* consumed. base64_encode_fast() and base64_decode_fast() continue from
5+
* there with the scalar loops, which remain the reference for behaviour:
6+
* the tail, padding, invalid characters and error reporting are never
7+
* handled here.
8+
*
9+
* Neither function reads outside [in, in + in_len) or writes more than the
10+
* scalar code would for the consumed prefix.
11+
*/
12+
#ifndef BINASCII_NEON_H
13+
#define BINASCII_NEON_H
14+
15+
#if defined(__aarch64__) || defined(_M_ARM64)
16+
#define BINASCII_HAVE_NEON 1
17+
18+
#include <arm_neon.h>
19+
#include <stdint.h>
20+
21+
/* Encoding works for any 64-byte alphabet: the 6-bit indices are looked up
22+
* in the table with TBL, which takes four 16-byte registers.
23+
*
24+
* 48 input bytes -> 64 output characters. */
25+
static inline void
26+
b64neon_encode48(const unsigned char *in, unsigned char *out,
27+
uint8x16x4_t tbl)
28+
{
29+
uint8x16x3_t s = vld3q_u8(in);
30+
uint8x16x4_t d;
31+
uint8x16_t m = vdupq_n_u8(0x3f);
32+
33+
d.val[0] = vshrq_n_u8(s.val[0], 2);
34+
d.val[1] = vandq_u8(vsliq_n_u8(vshrq_n_u8(s.val[1], 4), s.val[0], 4), m);
35+
d.val[2] = vandq_u8(vsliq_n_u8(vshrq_n_u8(s.val[2], 6), s.val[1], 2), m);
36+
d.val[3] = vandq_u8(s.val[2], m);
37+
38+
d.val[0] = vqtbl4q_u8(tbl, d.val[0]);
39+
d.val[1] = vqtbl4q_u8(tbl, d.val[1]);
40+
d.val[2] = vqtbl4q_u8(tbl, d.val[2]);
41+
d.val[3] = vqtbl4q_u8(tbl, d.val[3]);
42+
vst4q_u8(out, d);
43+
}
44+
45+
/* 24 input bytes -> 32 output characters. */
46+
static inline void
47+
b64neon_encode24(const unsigned char *in, unsigned char *out,
48+
uint8x16x4_t tbl)
49+
{
50+
uint8x8x3_t s = vld3_u8(in);
51+
uint8x8x4_t d;
52+
uint8x8_t m = vdup_n_u8(0x3f);
53+
54+
d.val[0] = vshr_n_u8(s.val[0], 2);
55+
d.val[1] = vand_u8(vsli_n_u8(vshr_n_u8(s.val[1], 4), s.val[0], 4), m);
56+
d.val[2] = vand_u8(vsli_n_u8(vshr_n_u8(s.val[2], 6), s.val[1], 2), m);
57+
d.val[3] = vand_u8(s.val[2], m);
58+
59+
d.val[0] = vqtbl4_u8(tbl, d.val[0]);
60+
d.val[1] = vqtbl4_u8(tbl, d.val[1]);
61+
d.val[2] = vqtbl4_u8(tbl, d.val[2]);
62+
d.val[3] = vqtbl4_u8(tbl, d.val[3]);
63+
vst4_u8(out, d);
64+
}
65+
66+
/* Encode all complete 3-byte groups. Requires in_len >= 24.
67+
* Returns in_len rounded down to a multiple of 3.
68+
*
69+
* A length that is not a multiple of the block size is finished by encoding
70+
* one more block that overlaps the previous one. The overlapping part is
71+
* rewritten with the same characters, since block boundaries stay on 3-byte
72+
* group boundaries. */
73+
static inline Py_ssize_t
74+
base64_encode_neon(const unsigned char *in, Py_ssize_t in_len,
75+
unsigned char *out, const unsigned char *table)
76+
{
77+
Py_ssize_t n = in_len / 3 * 3;
78+
Py_ssize_t i = 0;
79+
uint8x16x4_t tbl = vld1q_u8_x4(table);
80+
81+
assert(n >= 24);
82+
if (n < 48) {
83+
b64neon_encode24(in, out, tbl);
84+
if (n > 24) {
85+
b64neon_encode24(in + n - 24, out + (n - 24) / 3 * 4, tbl);
86+
}
87+
return n;
88+
}
89+
90+
for (; i + 96 <= n; i += 96) {
91+
b64neon_encode48(in + i, out + i / 3 * 4, tbl);
92+
b64neon_encode48(in + i + 48, out + i / 3 * 4 + 64, tbl);
93+
}
94+
if (i + 48 <= n) {
95+
b64neon_encode48(in + i, out + i / 3 * 4, tbl);
96+
i += 48;
97+
}
98+
if (i < n) {
99+
b64neon_encode48(in + n - 48, out + (n - 48) / 3 * 4, tbl);
100+
}
101+
return n;
102+
}
103+
104+
/* Decoding with the standard alphabet validates and translates with nibble
105+
* lookups instead of the 256-byte table. The technique is described in
106+
* W. Mula and D. Lemire, "Faster Base64 Encoding and Decoding using AVX2
107+
* Instructions", ACM TOW 12(3), 2018.
108+
*
109+
* For each input byte, err is nonzero iff the byte is not in the alphabet. */
110+
static inline uint8x16_t
111+
b64neon_translate_std(uint8x16_t x, uint8x16_t *err)
112+
{
113+
static const uint8_t lut_lo[16] = {
114+
0x15, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11,
115+
0x11, 0x11, 0x13, 0x1A, 0x1B, 0x1B, 0x1B, 0x1A,
116+
};
117+
static const uint8_t lut_hi[16] = {
118+
0x10, 0x10, 0x01, 0x02, 0x04, 0x08, 0x04, 0x08,
119+
0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10,
120+
};
121+
static const uint8_t lut_roll[16] = {
122+
0, 16, 19, 4, (uint8_t)-65, (uint8_t)-65, (uint8_t)-71, (uint8_t)-71,
123+
0, 0, 0, 0, 0, 0, 0, 0,
124+
};
125+
uint8x16_t hi = vshrq_n_u8(x, 4);
126+
uint8x16_t lo = vandq_u8(x, vdupq_n_u8(0x0f));
127+
uint8x16_t e = vandq_u8(vqtbl1q_u8(vld1q_u8(lut_lo), lo),
128+
vqtbl1q_u8(vld1q_u8(lut_hi), hi));
129+
/* '/' shares its high nibble with '+' but needs a different offset;
130+
* vceqq_u8() gives -1 for it, which selects lut_roll[1]. */
131+
uint8x16_t idx = vaddq_u8(hi, vceqq_u8(x, vdupq_n_u8('/')));
132+
*err = vorrq_u8(*err, e);
133+
return vaddq_u8(x, vqtbl1q_u8(vld1q_u8(lut_roll), idx));
134+
}
135+
136+
typedef struct {
137+
uint8x16x4_t t[4];
138+
int high; /* nonzero if some byte >= 0x80 maps to a valid value */
139+
} b64neon_table;
140+
141+
/* Other alphabets use the 256-byte reverse table directly, 64 bytes per
142+
* TBL/TBX. The upper half is skipped when the table rejects every byte
143+
* >= 0x80, which is the case for every ASCII alphabet.
144+
*
145+
* The scalar code rejects a value with either of the top two bits set;
146+
* a valid value is <= 63, so any rejection makes the OR of err exceed 63. */
147+
static inline uint8x16_t
148+
b64neon_translate_table(uint8x16_t x, uint8x16_t *err,
149+
const b64neon_table *T)
150+
{
151+
uint8x16_t v = vqtbl4q_u8(T->t[0], x);
152+
v = vqtbx4q_u8(v, T->t[1], veorq_u8(x, vdupq_n_u8(0x40)));
153+
if (T->high) {
154+
v = vqtbx4q_u8(v, T->t[2], veorq_u8(x, vdupq_n_u8(0x80)));
155+
v = vqtbx4q_u8(v, T->t[3], veorq_u8(x, vdupq_n_u8(0xc0)));
156+
*err = vorrq_u8(*err, v);
157+
}
158+
else {
159+
*err = vorrq_u8(*err, vorrq_u8(v, vandq_u8(x, vdupq_n_u8(0x80))));
160+
}
161+
return v;
162+
}
163+
164+
/* Pack 16 6-bit values (4 quads) into 12 bytes and store exactly 12. */
165+
static inline void
166+
b64neon_pack16(uint8x16_t v, unsigned char *out)
167+
{
168+
static const uint8_t shuf[16] = {
169+
2, 1, 0, 6, 5, 4, 10, 9, 8, 14, 13, 12, 0xff, 0xff, 0xff, 0xff,
170+
};
171+
uint16x8_t w16 = vreinterpretq_u16_u8(v);
172+
w16 = vandq_u16(vsliq_n_u16(vshrq_n_u16(w16, 8), w16, 6),
173+
vdupq_n_u16(0x0fff));
174+
uint32x4_t w32 = vreinterpretq_u32_u16(w16);
175+
w32 = vsliq_n_u32(vshrq_n_u32(w32, 16), w32, 12);
176+
uint8x16_t r = vqtbl1q_u8(vreinterpretq_u8_u32(w32), vld1q_u8(shuf));
177+
vst1_u8(out, vget_low_u8(r));
178+
vst1q_lane_u32((uint32_t *)(void *)(out + 8), vreinterpretq_u32_u8(r), 2);
179+
}
180+
181+
#define B64NEON_TRANSLATE(x, errp) \
182+
(is_std ? b64neon_translate_std((x), (errp)) \
183+
: b64neon_translate_table((x), (errp), &T))
184+
185+
/* Decode blocks of 64, then 16, characters. Stops before the first block
186+
* containing a character the table rejects; the scalar loop then finds the
187+
* exact position. Returns the number of characters consumed, a multiple
188+
* of 4. is_std must be a constant so that each caller is specialized. */
189+
static inline Py_ssize_t
190+
b64neon_decode_blocks(const unsigned char *in, Py_ssize_t in_len,
191+
unsigned char *out, const unsigned char *table,
192+
const int is_std)
193+
{
194+
const unsigned char *const start = in;
195+
b64neon_table T = {0};
196+
197+
if (!is_std) {
198+
for (int i = 0; i < 4; i++) {
199+
T.t[i] = vld1q_u8_x4(table + 64 * i);
200+
}
201+
for (int i = 0x80; i < 0x100; i++) {
202+
if (!(table[i] & 0xc0)) {
203+
T.high = 1;
204+
break;
205+
}
206+
}
207+
}
208+
209+
for (; in_len >= 64; in += 64, out += 48, in_len -= 64) {
210+
uint8x16x4_t s = vld4q_u8(in);
211+
uint8x16_t e0 = vdupq_n_u8(0), e1 = vdupq_n_u8(0);
212+
uint8x16_t a = B64NEON_TRANSLATE(s.val[0], &e0);
213+
uint8x16_t b = B64NEON_TRANSLATE(s.val[1], &e1);
214+
uint8x16_t c = B64NEON_TRANSLATE(s.val[2], &e0);
215+
uint8x16_t q = B64NEON_TRANSLATE(s.val[3], &e1);
216+
uint8_t e = vmaxvq_u8(vorrq_u8(e0, e1));
217+
if (is_std ? e != 0 : e > 63) {
218+
break;
219+
}
220+
uint8x16x3_t d;
221+
d.val[0] = vsliq_n_u8(vshrq_n_u8(b, 4), a, 2);
222+
d.val[1] = vsliq_n_u8(vshrq_n_u8(c, 2), b, 4);
223+
d.val[2] = vsliq_n_u8(q, c, 6);
224+
vst3q_u8(out, d);
225+
}
226+
for (; in_len >= 16; in += 16, out += 12, in_len -= 16) {
227+
uint8x16_t e0 = vdupq_n_u8(0);
228+
uint8x16_t v = B64NEON_TRANSLATE(vld1q_u8(in), &e0);
229+
uint8_t e = vmaxvq_u8(e0);
230+
if (is_std ? e != 0 : e > 63) {
231+
break;
232+
}
233+
b64neon_pack16(v, out);
234+
}
235+
return in - start;
236+
}
237+
238+
#undef B64NEON_TRANSLATE
239+
240+
static inline Py_ssize_t
241+
base64_decode_neon(const unsigned char *in, Py_ssize_t in_len,
242+
unsigned char *out, const unsigned char *table,
243+
int is_std)
244+
{
245+
if (is_std) {
246+
return b64neon_decode_blocks(in, in_len, out, table, 1);
247+
}
248+
return b64neon_decode_blocks(in, in_len, out, table, 0);
249+
}
250+
251+
#endif /* __aarch64__ || _M_ARM64 */
252+
#endif /* BINASCII_NEON_H */

‎PCbuild/pythoncore.vcxproj‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -403,6 +403,7 @@
403403
<ClInclude Include="..\Include\unicodeobject.h" />
404404
<ClInclude Include="..\Include\weakrefobject.h" />
405405
<ClInclude Include="..\Modules\_math.h" />
406+
<ClInclude Include="..\Modules\binascii_neon.h" />
406407
<ClInclude Include="..\Modules\rotatingtree.h" />
407408
<ClInclude Include="..\Modules\_io\_iomodule.h" />
408409
<ClInclude Include="..\Modules\cjkcodecs\alg_jisx0201.h" />

‎PCbuild/pythoncore.vcxproj.filters‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -264,6 +264,9 @@
264264
<ClInclude Include="..\Modules\_math.h">
265265
<Filter>Modules</Filter>
266266
</ClInclude>
267+
<ClInclude Include="..\Modules\binascii_neon.h">
268+
<Filter>Modules</Filter>
269+
</ClInclude>
267270
<ClInclude Include="..\Modules\rotatingtree.h">
268271
<Filter>Modules</Filter>
269272
</ClInclude>

0 commit comments

Comments
 (0)