Skip to main content

vector_core/simd/
base64.rs

1//! Base64 (RFC 4648) encode and decode: NEON on ARM64, AVX2/SSSE3 on x86_64, scalar elsewhere.
2//!
3//! Decoding is strict: no whitespace, padding exactly as the engine says, and the unused bits of
4//! the last group must be zero, so every byte string has one accepted encoding.
5//!
6//! # Performance (x86_64 AVX2, `encode_to_string` / `decode_to_vec`, allocation included)
7//!
8//! | bytes | encode | decode | decode, base64-simd 0.8 |
9//! |------:|-------:|-------:|------------------------:|
10//! |    48 |  20 ns |  17 ns |                   25 ns |
11//! |   600 |  71 ns |  55 ns |                   93 ns |
12//! |  64 K | 6.2 µs | 4.9 µs |                  8.5 µs |
13//!
14//! Encoding is level with base64-simd from 32 bytes up.
15//!
16//! # Algorithm
17//!
18//! **NEON:** `vld3`/`vst4` de-interleave 48 bytes into 64 indices, and a 64-entry `tbl4` maps
19//! them to the alphabet. Decoding runs the same in reverse over a 128-entry `tbl4`/`tbx4` table.
20//!
21//! **SSSE3/AVX2:** Muła and Lemire's multiply-shift split and `pshufb` offset lookup. Decode
22//! validation classifies each byte by nibble pair (`lut_lo[lo] & lut_hi[hi]`), with tables built
23//! at compile time from the alphabet, so the URL-safe engine uses the same code.
24
25#[cfg(target_arch = "aarch64")]
26use std::arch::aarch64::*;
27
28#[cfg(target_arch = "x86_64")]
29use std::arch::x86_64::*;
30
31const STANDARD_CHARSET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
32const URL_SAFE_CHARSET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
33
34/// The standard alphabet, padded.
35pub const STANDARD: Engine = Engine::new(STANDARD_CHARSET, true);
36/// The URL-safe alphabet, unpadded.
37pub const URL_SAFE_NO_PAD: Engine = Engine::new(URL_SAFE_CHARSET, false);
38
39#[derive(Debug, Clone, Copy, PartialEq, Eq)]
40pub struct DecodeError;
41
42impl std::fmt::Display for DecodeError {
43    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
44        f.write_str("invalid base64")
45    }
46}
47
48impl std::error::Error for DecodeError {}
49
50pub struct Engine {
51    charset: &'static [u8; 64],
52    /// Byte to 6-bit value; 0xff for anything outside the alphabet.
53    decode: [u8; 256],
54    pad: bool,
55    #[allow(dead_code)]
56    x86: X86Luts,
57}
58
59/// The SSSE3/AVX2 tables, as plain bytes so `Engine` stays const-constructible.
60#[allow(dead_code)]
61struct X86Luts {
62    /// Index-to-ASCII offsets for encoding, by `saturating_sub(idx, 51)` (13 for A-Z).
63    encode_shift: [u8; 16],
64    /// Bit classes: a byte is invalid iff `lo[byte & 15] & hi[byte >> 4] != 0`.
65    lo: [u8; 16],
66    hi: [u8; 16],
67    /// ASCII-to-value offsets by high nibble; slot 1 (never valid) holds `special`'s.
68    roll: [u8; 16],
69    /// The one character whose offset differs from the rest of its high-nibble row.
70    special: u8,
71    /// Added to `special`'s high nibble to reach slot 1.
72    delta: u8,
73}
74
75const ROLL_SLOT: u8 = 1;
76
77impl Engine {
78    const fn new(charset: &'static [u8; 64], pad: bool) -> Engine {
79        let mut decode = [0xffu8; 256];
80        let mut i = 0;
81        while i < 64 {
82            decode[charset[i] as usize] = i as u8;
83            i += 1;
84        }
85        Engine { charset, decode, pad, x86: X86Luts::new(charset, &decode) }
86    }
87
88    /// The encoded length of `n` bytes.
89    pub const fn encoded_len(&self, n: usize) -> usize {
90        if self.pad {
91            n.div_ceil(3) * 4
92        } else {
93            n / 3 * 4 + [0, 2, 3][n % 3]
94        }
95    }
96
97    pub fn encode_to_string(&self, data: impl AsRef<[u8]>) -> String {
98        let mut out = String::new();
99        self.encode_append(data, &mut out);
100        out
101    }
102
103    pub fn encode_append(&self, data: impl AsRef<[u8]>, out: &mut String) {
104        let src = data.as_ref();
105        let len = self.encoded_len(src.len());
106        // SAFETY: the encoder writes exactly `len` bytes, all from the ASCII alphabet or '='.
107        unsafe {
108            let v = out.as_mut_vec();
109            v.reserve(len);
110            self.encode_raw(src, v.as_mut_ptr().add(v.len()), Level::best());
111            v.set_len(v.len() + len);
112        }
113    }
114
115    pub fn decode_to_vec(&self, data: impl AsRef<[u8]>) -> Result<Vec<u8>, DecodeError> {
116        self.decode_with(data.as_ref(), Level::best())
117    }
118
119    fn decode_with(&self, src: &[u8], level: Level) -> Result<Vec<u8>, DecodeError> {
120        let (n, m) = self.decoded_len(src)?;
121        // Slack for the 8-byte scalar and the 16/32-byte SIMD stores, which overrun what they produce.
122        let mut out = Vec::with_capacity(m + 8);
123        // SAFETY: `decode_raw` writes `m` bytes and stays within `m + 8`.
124        unsafe {
125            self.decode_raw(&src[..n], out.as_mut_ptr(), level)?;
126            out.set_len(m);
127        }
128        Ok(out)
129    }
130
131    /// (characters before padding, decoded bytes).
132    fn decoded_len(&self, src: &[u8]) -> Result<(usize, usize), DecodeError> {
133        let len = src.len();
134        if len == 0 {
135            return Ok((0, 0));
136        }
137        let n = if self.pad {
138            if len % 4 != 0 {
139                return Err(DecodeError);
140            }
141            len - (src[len - 1] == b'=') as usize - (src[len - 1] == b'=' && src[len - 2] == b'=') as usize
142        } else {
143            len
144        };
145        let m = match n % 4 {
146            0 => n / 4 * 3,
147            2 => n / 4 * 3 + 1,
148            3 => n / 4 * 3 + 2,
149            _ => return Err(DecodeError),
150        };
151        Ok((n, m))
152    }
153
154    /// # Safety
155    /// `dst` must have room for `self.encoded_len(src.len())` bytes.
156    unsafe fn encode_raw(&self, src: &[u8], dst: *mut u8, level: Level) {
157        let (i, o) = match level {
158            #[cfg(target_arch = "aarch64")]
159            Level::Neon => encode_neon(src, dst, self.charset),
160            #[cfg(target_arch = "x86_64")]
161            Level::Avx2 => encode_avx2(src, dst, &self.x86.encode_shift),
162            #[cfg(target_arch = "x86_64")]
163            Level::Ssse3 => encode_ssse3(src, dst, &self.x86.encode_shift),
164            Level::Scalar => (0, 0),
165        };
166        self.encode_scalar(&src[i..], dst.add(o));
167    }
168
169    unsafe fn encode_scalar(&self, src: &[u8], dst: *mut u8) {
170        let cs = self.charset;
171        let mut o = 0;
172        let mut chunks = src.chunks_exact(3);
173        for c in &mut chunks {
174            let w = (c[0] as u32) << 16 | (c[1] as u32) << 8 | c[2] as u32;
175            let out = u32::from_le_bytes([
176                *cs.get_unchecked((w >> 18) as usize),
177                *cs.get_unchecked((w >> 12 & 63) as usize),
178                *cs.get_unchecked((w >> 6 & 63) as usize),
179                *cs.get_unchecked((w & 63) as usize),
180            ]);
181            dst.add(o).cast::<u32>().write_unaligned(out);
182            o += 4;
183        }
184        match *chunks.remainder() {
185            [a] => {
186                *dst.add(o) = cs[(a >> 2) as usize];
187                *dst.add(o + 1) = cs[((a & 3) << 4) as usize];
188                if self.pad {
189                    *dst.add(o + 2) = b'=';
190                    *dst.add(o + 3) = b'=';
191                }
192            }
193            [a, b] => {
194                *dst.add(o) = cs[(a >> 2) as usize];
195                *dst.add(o + 1) = cs[((a & 3) << 4 | b >> 4) as usize];
196                *dst.add(o + 2) = cs[((b & 15) << 2) as usize];
197                if self.pad {
198                    *dst.add(o + 3) = b'=';
199                }
200            }
201            _ => {}
202        }
203    }
204
205    /// Decodes `src` (padding already stripped) into `dst`.
206    ///
207    /// # Safety
208    /// `dst` must have room for the decoded length plus 8.
209    unsafe fn decode_raw(&self, src: &[u8], dst: *mut u8, level: Level) -> Result<(), DecodeError> {
210        let (i, o, ok) = match level {
211            #[cfg(target_arch = "aarch64")]
212            Level::Neon => decode_neon(src, dst, &self.decode),
213            #[cfg(target_arch = "x86_64")]
214            Level::Avx2 => decode_avx2(src, dst, &self.x86),
215            #[cfg(target_arch = "x86_64")]
216            Level::Ssse3 => decode_ssse3(src, dst, &self.x86),
217            Level::Scalar => (0, 0, true),
218        };
219        if !ok {
220            return Err(DecodeError);
221        }
222        self.decode_scalar(&src[i..], dst.add(o))
223    }
224
225    unsafe fn decode_scalar(&self, src: &[u8], dst: *mut u8) -> Result<(), DecodeError> {
226        let t = &self.decode;
227        let mut bad = 0u8;
228        let mut o = 0;
229        let mut chunks = src.chunks_exact(8);
230        for c in &mut chunks {
231            let mut w = 0u64;
232            for (k, &ch) in c.iter().enumerate() {
233                let v = t[ch as usize];
234                bad |= v;
235                w |= (v as u64) << (58 - 6 * k);
236            }
237            dst.add(o).cast::<u64>().write_unaligned(w.to_be());
238            o += 6;
239        }
240        let rest = chunks.remainder();
241        let mut quads = rest.chunks_exact(4);
242        for c in &mut quads {
243            let (a, b, c2, d) = (t[c[0] as usize], t[c[1] as usize], t[c[2] as usize], t[c[3] as usize]);
244            bad |= a | b | c2 | d;
245            let w = (a as u32) << 18 | (b as u32) << 12 | (c2 as u32) << 6 | d as u32;
246            *dst.add(o) = (w >> 16) as u8;
247            *dst.add(o + 1) = (w >> 8) as u8;
248            *dst.add(o + 2) = w as u8;
249            o += 3;
250        }
251        match *quads.remainder() {
252            [] => {}
253            [a, b] => {
254                let (a, b) = (t[a as usize], t[b as usize]);
255                bad |= a | b | if b & 0x0f != 0 { 0xff } else { 0 };
256                *dst.add(o) = a << 2 | b >> 4;
257            }
258            [a, b, c] => {
259                let (a, b, c) = (t[a as usize], t[b as usize], t[c as usize]);
260                bad |= a | b | c | if c & 0x03 != 0 { 0xff } else { 0 };
261                *dst.add(o) = a << 2 | b >> 4;
262                *dst.add(o + 1) = b << 4 | c >> 2;
263            }
264            _ => return Err(DecodeError),
265        }
266        // Valid values are 0..=63; 0xff marks a byte outside the alphabet.
267        if bad & 0xc0 != 0 {
268            return Err(DecodeError);
269        }
270        Ok(())
271    }
272}
273
274#[derive(Debug, Clone, Copy, PartialEq, Eq)]
275enum Level {
276    Scalar,
277    #[cfg(target_arch = "x86_64")]
278    Ssse3,
279    #[cfg(target_arch = "x86_64")]
280    Avx2,
281    #[cfg(target_arch = "aarch64")]
282    Neon,
283}
284
285impl Level {
286    #[inline]
287    fn best() -> Level {
288        #[cfg(target_arch = "aarch64")]
289        return Level::Neon;
290        #[cfg(target_arch = "x86_64")]
291        {
292            if is_x86_feature_detected!("avx2") {
293                return Level::Avx2;
294            }
295            if is_x86_feature_detected!("ssse3") {
296                return Level::Ssse3;
297            }
298        }
299        #[allow(unreachable_code)]
300        Level::Scalar
301    }
302}
303
304impl X86Luts {
305    const fn new(charset: &[u8; 64], decode: &[u8; 256]) -> X86Luts {
306        // Both alphabets share A-Z a-z 0-9; only the last two characters differ.
307        let mut encode_shift = [0u8; 16];
308        encode_shift[0] = b'a'.wrapping_sub(26);
309        let mut k = 1;
310        while k <= 10 {
311            encode_shift[k] = b'0'.wrapping_sub(52);
312            k += 1;
313        }
314        encode_shift[11] = charset[62].wrapping_sub(62);
315        encode_shift[12] = charset[63].wrapping_sub(63);
316        encode_shift[13] = b'A';
317
318        // Each distinct per-row validity pattern gets a class bit.
319        let mut patterns = [0u16; 8];
320        let mut count = 0;
321        let mut row_class = [0u8; 16];
322        let mut h = 0;
323        while h < 16 {
324            let mut valid = 0u16;
325            let mut l = 0;
326            while l < 16 {
327                if decode[h << 4 | l] != 0xff {
328                    valid |= 1 << l;
329                }
330                l += 1;
331            }
332            let mut p = 0;
333            while p < count && patterns[p] != valid {
334                p += 1;
335            }
336            if p == count {
337                assert!(count < 8, "base64 alphabet needs more than 8 nibble classes");
338                patterns[p] = valid;
339                count += 1;
340            }
341            row_class[h] = p as u8;
342            h += 1;
343        }
344        let mut lo = [0u8; 16];
345        let mut hi = [0u8; 16];
346        let mut h = 0;
347        while h < 16 {
348            hi[h] = 1 << row_class[h];
349            h += 1;
350        }
351        let mut l = 0;
352        while l < 16 {
353            let mut p = 0;
354            while p < count {
355                if patterns[p] & (1 << l) == 0 {
356                    lo[l] |= 1 << p;
357                }
358                p += 1;
359            }
360            l += 1;
361        }
362
363        // One offset per high nibble, except for at most one character, which goes to slot 1.
364        let mut roll = [0u8; 16];
365        let mut set = [false; 16];
366        let mut special = 0u8;
367        let mut has_special = false;
368        let mut c = 0;
369        while c < 128 {
370            let v = decode[c];
371            if v != 0xff {
372                let off = v.wrapping_sub(c as u8);
373                let row = c >> 4;
374                if !set[row] {
375                    roll[row] = off;
376                    set[row] = true;
377                } else if roll[row] != off {
378                    assert!(!has_special, "base64 alphabet has two characters off their row's offset");
379                    special = c as u8;
380                    has_special = true;
381                    roll[ROLL_SLOT as usize] = off;
382                }
383            }
384            c += 1;
385        }
386        assert!(!set[ROLL_SLOT as usize], "base64 alphabet uses the roll slot's row");
387        let delta = ROLL_SLOT.wrapping_sub(special >> 4);
388        X86Luts { encode_shift, lo, hi, roll, special, delta }
389    }
390}
391
392// ============================================================================
393// x86_64
394// ============================================================================
395
396#[cfg(target_arch = "x86_64")]
397#[inline(always)]
398unsafe fn lut128(t: &[u8; 16]) -> __m128i {
399    _mm_loadu_si128(t.as_ptr().cast())
400}
401
402// The loops carry the target feature too, so the kernels inline and their constants hoist.
403// Each finishes its full groups with one block overlapping what it already wrote, rewriting
404// those bytes with the same values, so only the last partial group is left to scalar code.
405
406#[cfg(target_arch = "x86_64")]
407#[target_feature(enable = "avx2")]
408unsafe fn encode_avx2(src: &[u8], dst: *mut u8, shift: &[u8; 16]) -> (usize, usize) {
409    let (mut i, mut o) = (0, 0);
410    if src.len() >= 24 {
411        encode24_avx2(src.as_ptr(), dst, shift);
412        (i, o) = (24, 32);
413        while src.len() - i >= 28 {
414            encode24_back_avx2(src.as_ptr().add(i - 4), dst.add(o), shift);
415            i += 24;
416            o += 32;
417        }
418    }
419    encode_tail_ssse3(src, dst, shift, i, o)
420}
421
422#[cfg(target_arch = "x86_64")]
423#[target_feature(enable = "ssse3")]
424unsafe fn encode_ssse3(src: &[u8], dst: *mut u8, shift: &[u8; 16]) -> (usize, usize) {
425    encode_tail_ssse3(src, dst, shift, 0, 0)
426}
427
428/// 12-byte blocks from `i` on, then one block overlapping the last full triples.
429#[cfg(target_arch = "x86_64")]
430#[inline]
431#[target_feature(enable = "ssse3")]
432unsafe fn encode_tail_ssse3(src: &[u8], dst: *mut u8, shift: &[u8; 16], mut i: usize, mut o: usize) -> (usize, usize) {
433    let full = src.len() / 3 * 3;
434    while full - i >= 12 {
435        encode12_at(src, i, dst.add(o), shift);
436        i += 12;
437        o += 16;
438    }
439    if full > i && full >= 12 {
440        let s = full - 12;
441        encode12_at(src, s, dst.add(s / 3 * 4), shift);
442        (i, o) = (full, full / 3 * 4);
443    }
444    (i, o)
445}
446
447/// Encodes `src[at..at + 12]` with whichever 16-byte load stays inside `src`.
448#[cfg(target_arch = "x86_64")]
449#[inline]
450#[target_feature(enable = "ssse3")]
451unsafe fn encode12_at(src: &[u8], at: usize, dst: *mut u8, shift: &[u8; 16]) {
452    if at >= 4 {
453        encode12_ssse3::<true>(src.as_ptr().add(at - 4), dst, shift);
454    } else if src.len() - at >= 16 {
455        encode12_ssse3::<false>(src.as_ptr().add(at), dst, shift);
456    } else {
457        let mut buf = [0u8; 16];
458        buf[4..].copy_from_slice(&src[at..at + 12]);
459        encode12_ssse3::<true>(buf.as_ptr(), dst, shift);
460    }
461}
462
463#[cfg(target_arch = "x86_64")]
464#[target_feature(enable = "avx2")]
465unsafe fn decode_avx2(src: &[u8], dst: *mut u8, l: &X86Luts) -> (usize, usize, bool) {
466    let full = src.len() / 4 * 4;
467    let (mut i, mut o) = (0, 0);
468    while full - i >= 32 {
469        if !decode32_avx2(src.as_ptr().add(i), dst.add(o), l) {
470            return (i, o, false);
471        }
472        i += 32;
473        o += 24;
474    }
475    decode_tail_ssse3(src, dst, l, i, o)
476}
477
478#[cfg(target_arch = "x86_64")]
479#[target_feature(enable = "ssse3")]
480unsafe fn decode_ssse3(src: &[u8], dst: *mut u8, l: &X86Luts) -> (usize, usize, bool) {
481    decode_tail_ssse3(src, dst, l, 0, 0)
482}
483
484#[cfg(target_arch = "x86_64")]
485#[inline]
486#[target_feature(enable = "ssse3")]
487unsafe fn decode_tail_ssse3(src: &[u8], dst: *mut u8, l: &X86Luts, mut i: usize, mut o: usize) -> (usize, usize, bool) {
488    let full = src.len() / 4 * 4;
489    while full - i >= 16 {
490        if !decode16_ssse3(src.as_ptr().add(i), dst.add(o), l) {
491            return (i, o, false);
492        }
493        i += 16;
494        o += 12;
495    }
496    if full > i && full >= 16 {
497        let s = full - 16;
498        if !decode16_ssse3(src.as_ptr().add(s), dst.add(s / 4 * 3), l) {
499            return (i, o, false);
500        }
501        (i, o) = (full, full / 4 * 3);
502    }
503    (i, o, true)
504}
505
506#[cfg(target_arch = "x86_64")]
507const SPLIT_AT_0: [i8; 16] = [1, 0, 2, 1, 4, 3, 5, 4, 7, 6, 8, 7, 10, 9, 11, 10];
508#[cfg(target_arch = "x86_64")]
509const SPLIT_AT_4: [i8; 16] = [5, 4, 6, 5, 8, 7, 9, 8, 11, 10, 12, 11, 14, 13, 15, 14];
510
511/// Encodes 12 bytes into 16 characters. The 16-byte load starts 4 bytes early when `BACK`.
512#[cfg(target_arch = "x86_64")]
513#[inline]
514#[target_feature(enable = "ssse3")]
515unsafe fn encode12_ssse3<const BACK: bool>(load: *const u8, dst: *mut u8, shift: &[u8; 16]) {
516    let split = if BACK { &SPLIT_AT_4 } else { &SPLIT_AT_0 };
517    let x = _mm_shuffle_epi8(_mm_loadu_si128(load.cast()), _mm_loadu_si128(split.as_ptr().cast()));
518    let t0 = _mm_mulhi_epu16(_mm_and_si128(x, _mm_set1_epi32(0x0fc0fc00)), _mm_set1_epi32(0x04000040));
519    let t1 = _mm_mullo_epi16(_mm_and_si128(x, _mm_set1_epi32(0x003f03f0)), _mm_set1_epi32(0x01000010));
520    let idx = _mm_or_si128(t0, t1);
521    let less = _mm_cmpgt_epi8(_mm_set1_epi8(26), idx);
522    let r = _mm_or_si128(_mm_subs_epu8(idx, _mm_set1_epi8(51)), _mm_and_si128(less, _mm_set1_epi8(13)));
523    let r = _mm_add_epi8(_mm_shuffle_epi8(lut128(shift), r), idx);
524    _mm_storeu_si128(dst.cast(), r);
525}
526
527/// Encodes 24 bytes into 32 characters, reading exactly those 24.
528#[cfg(target_arch = "x86_64")]
529#[inline]
530#[target_feature(enable = "avx2")]
531unsafe fn encode24_avx2(src: *const u8, dst: *mut u8, shift: &[u8; 16]) {
532    let lo = _mm_loadu_si128(src.cast());
533    let hi = _mm_loadu_si128(src.add(8).cast());
534    let x = _mm256_inserti128_si256(_mm256_castsi128_si256(lo), hi, 1);
535    let split = _mm256_inserti128_si256(
536        _mm256_castsi128_si256(_mm_loadu_si128(SPLIT_AT_0.as_ptr().cast())),
537        _mm_loadu_si128(SPLIT_AT_4.as_ptr().cast()),
538        1,
539    );
540    let x = _mm256_shuffle_epi8(x, split);
541    let t0 = _mm256_mulhi_epu16(_mm256_and_si256(x, _mm256_set1_epi32(0x0fc0fc00)), _mm256_set1_epi32(0x04000040));
542    let t1 = _mm256_mullo_epi16(_mm256_and_si256(x, _mm256_set1_epi32(0x003f03f0)), _mm256_set1_epi32(0x01000010));
543    let idx = _mm256_or_si256(t0, t1);
544    let less = _mm256_cmpgt_epi8(_mm256_set1_epi8(26), idx);
545    let r = _mm256_or_si256(_mm256_subs_epu8(idx, _mm256_set1_epi8(51)), _mm256_and_si256(less, _mm256_set1_epi8(13)));
546    let r = _mm256_add_epi8(_mm256_shuffle_epi8(_mm256_broadcastsi128_si256(lut128(shift)), r), idx);
547    _mm256_storeu_si256(dst.cast(), r);
548}
549
550/// Encodes the 24 bytes 4 past `load` into 32 characters, from one 32-byte load.
551#[cfg(target_arch = "x86_64")]
552#[inline]
553#[target_feature(enable = "avx2")]
554unsafe fn encode24_back_avx2(load: *const u8, dst: *mut u8, shift: &[u8; 16]) {
555    let x = _mm256_loadu_si256(load.cast());
556    let x = _mm256_permutevar8x32_epi32(x, _mm256_setr_epi32(0, 1, 2, 3, 3, 4, 5, 6));
557    let x = _mm256_shuffle_epi8(x, _mm256_broadcastsi128_si256(_mm_loadu_si128(SPLIT_AT_4.as_ptr().cast())));
558    let t0 = _mm256_mulhi_epu16(_mm256_and_si256(x, _mm256_set1_epi32(0x0fc0fc00)), _mm256_set1_epi32(0x04000040));
559    let t1 = _mm256_mullo_epi16(_mm256_and_si256(x, _mm256_set1_epi32(0x003f03f0)), _mm256_set1_epi32(0x01000010));
560    let idx = _mm256_or_si256(t0, t1);
561    let less = _mm256_cmpgt_epi8(_mm256_set1_epi8(26), idx);
562    let r = _mm256_or_si256(_mm256_subs_epu8(idx, _mm256_set1_epi8(51)), _mm256_and_si256(less, _mm256_set1_epi8(13)));
563    let r = _mm256_add_epi8(_mm256_shuffle_epi8(_mm256_broadcastsi128_si256(lut128(shift)), r), idx);
564    _mm256_storeu_si256(dst.cast(), r);
565}
566
567/// Decodes 16 characters into 12 bytes, storing 16; false if any is outside the alphabet.
568#[cfg(target_arch = "x86_64")]
569#[target_feature(enable = "ssse3")]
570#[inline]
571unsafe fn decode16_ssse3(src: *const u8, dst: *mut u8, l: &X86Luts) -> bool {
572    let c = _mm_loadu_si128(src.cast());
573    let nib = _mm_set1_epi8(0x0f);
574    let hi = _mm_and_si128(_mm_srli_epi32(c, 4), nib);
575    let lo = _mm_and_si128(c, nib);
576    let class = _mm_and_si128(_mm_shuffle_epi8(lut128(&l.lo), lo), _mm_shuffle_epi8(lut128(&l.hi), hi));
577    if _mm_movemask_epi8(_mm_cmpeq_epi8(class, _mm_setzero_si128())) != 0xffff {
578        return false;
579    }
580    let eq = _mm_cmpeq_epi8(c, _mm_set1_epi8(l.special as i8));
581    let slot = _mm_add_epi8(hi, _mm_and_si128(eq, _mm_set1_epi8(l.delta as i8)));
582    let v = _mm_add_epi8(c, _mm_shuffle_epi8(lut128(&l.roll), slot));
583    let v = _mm_madd_epi16(_mm_maddubs_epi16(v, _mm_set1_epi32(0x01400140)), _mm_set1_epi32(0x00011000));
584    let v = _mm_shuffle_epi8(v, _mm_setr_epi8(2, 1, 0, 6, 5, 4, 10, 9, 8, 14, 13, 12, -1, -1, -1, -1));
585    _mm_storeu_si128(dst.cast(), v);
586    true
587}
588
589/// Decodes 32 characters into 24 bytes, storing 32; false if any is outside the alphabet.
590#[cfg(target_arch = "x86_64")]
591#[target_feature(enable = "avx2")]
592#[inline]
593unsafe fn decode32_avx2(src: *const u8, dst: *mut u8, l: &X86Luts) -> bool {
594    let c = _mm256_loadu_si256(src.cast());
595    let nib = _mm256_set1_epi8(0x0f);
596    let hi = _mm256_and_si256(_mm256_srli_epi32(c, 4), nib);
597    let lo = _mm256_and_si256(c, nib);
598    let class = _mm256_and_si256(
599        _mm256_shuffle_epi8(_mm256_broadcastsi128_si256(lut128(&l.lo)), lo),
600        _mm256_shuffle_epi8(_mm256_broadcastsi128_si256(lut128(&l.hi)), hi),
601    );
602    if _mm256_movemask_epi8(_mm256_cmpeq_epi8(class, _mm256_setzero_si256())) != -1 {
603        return false;
604    }
605    let eq = _mm256_cmpeq_epi8(c, _mm256_set1_epi8(l.special as i8));
606    let slot = _mm256_add_epi8(hi, _mm256_and_si256(eq, _mm256_set1_epi8(l.delta as i8)));
607    let v = _mm256_add_epi8(c, _mm256_shuffle_epi8(_mm256_broadcastsi128_si256(lut128(&l.roll)), slot));
608    let v = _mm256_madd_epi16(_mm256_maddubs_epi16(v, _mm256_set1_epi32(0x01400140)), _mm256_set1_epi32(0x00011000));
609    let v = _mm256_shuffle_epi8(
610        v,
611        _mm256_setr_epi8(
612            2, 1, 0, 6, 5, 4, 10, 9, 8, 14, 13, 12, -1, -1, -1, -1, 2, 1, 0, 6, 5, 4, 10, 9, 8, 14, 13, 12, -1, -1, -1,
613            -1,
614        ),
615    );
616    let v = _mm256_permutevar8x32_epi32(v, _mm256_setr_epi32(0, 1, 2, 4, 5, 6, 3, 7));
617    _mm256_storeu_si256(dst.cast(), v);
618    true
619}
620
621// ============================================================================
622// ARM64
623// ============================================================================
624
625#[cfg(target_arch = "aarch64")]
626#[inline(always)]
627unsafe fn neon_table64(p: *const u8) -> uint8x16x4_t {
628    uint8x16x4_t(vld1q_u8(p), vld1q_u8(p.add(16)), vld1q_u8(p.add(32)), vld1q_u8(p.add(48)))
629}
630
631/// 48- then 24-byte blocks, finishing with one 24-byte block overlapping what is already written.
632#[cfg(target_arch = "aarch64")]
633#[inline(always)]
634unsafe fn encode_neon(src: &[u8], dst: *mut u8, charset: &[u8; 64]) -> (usize, usize) {
635    let table = neon_table64(charset.as_ptr());
636    let p = src.as_ptr();
637    let full = src.len() / 3 * 3;
638    let (mut i, mut o) = (0, 0);
639    while full - i >= 48 {
640        encode48_neon(p.add(i), dst.add(o), table);
641        i += 48;
642        o += 64;
643    }
644    while full - i >= 24 {
645        encode24_neon(p.add(i), dst.add(o), table);
646        i += 24;
647        o += 32;
648    }
649    if full > i && full >= 24 {
650        let s = full - 24;
651        encode24_neon(p.add(s), dst.add(s / 3 * 4), table);
652        (i, o) = (full, full / 3 * 4);
653    }
654    (i, o)
655}
656
657#[cfg(target_arch = "aarch64")]
658#[inline(always)]
659unsafe fn decode_neon(src: &[u8], dst: *mut u8, decode: &[u8; 256]) -> (usize, usize, bool) {
660    let (lo, hi) = (neon_table64(decode.as_ptr()), neon_table64(decode.as_ptr().add(64)));
661    let p = src.as_ptr();
662    let full = src.len() / 4 * 4;
663    let (mut i, mut o) = (0, 0);
664    while full - i >= 64 {
665        if !decode64_neon(p.add(i), dst.add(o), lo, hi) {
666            return (i, o, false);
667        }
668        i += 64;
669        o += 48;
670    }
671    while full - i >= 32 {
672        if !decode32_neon(p.add(i), dst.add(o), lo, hi) {
673            return (i, o, false);
674        }
675        i += 32;
676        o += 24;
677    }
678    if full > i && full >= 32 {
679        let s = full - 32;
680        if !decode32_neon(p.add(s), dst.add(s / 4 * 3), lo, hi) {
681            return (i, o, false);
682        }
683        (i, o) = (full, full / 4 * 3);
684    }
685    (i, o, true)
686}
687
688#[cfg(target_arch = "aarch64")]
689#[inline(always)]
690unsafe fn encode48_neon(src: *const u8, dst: *mut u8, table: uint8x16x4_t) {
691    let x = vld3q_u8(src);
692    let m = vdupq_n_u8(63);
693    let i0 = vshrq_n_u8(x.0, 2);
694    let i1 = vandq_u8(vorrq_u8(vshlq_n_u8(x.0, 4), vshrq_n_u8(x.1, 4)), m);
695    let i2 = vandq_u8(vorrq_u8(vshlq_n_u8(x.1, 2), vshrq_n_u8(x.2, 6)), m);
696    let i3 = vandq_u8(x.2, m);
697    vst4q_u8(
698        dst,
699        uint8x16x4_t(vqtbl4q_u8(table, i0), vqtbl4q_u8(table, i1), vqtbl4q_u8(table, i2), vqtbl4q_u8(table, i3)),
700    );
701}
702
703#[cfg(target_arch = "aarch64")]
704#[inline(always)]
705unsafe fn encode24_neon(src: *const u8, dst: *mut u8, table: uint8x16x4_t) {
706    let x = vld3_u8(src);
707    let m = vdup_n_u8(63);
708    let i0 = vshr_n_u8(x.0, 2);
709    let i1 = vand_u8(vorr_u8(vshl_n_u8(x.0, 4), vshr_n_u8(x.1, 4)), m);
710    let i2 = vand_u8(vorr_u8(vshl_n_u8(x.1, 2), vshr_n_u8(x.2, 6)), m);
711    let i3 = vand_u8(x.2, m);
712    vst4_u8(dst, uint8x8x4_t(vqtbl4_u8(table, i0), vqtbl4_u8(table, i1), vqtbl4_u8(table, i2), vqtbl4_u8(table, i3)));
713}
714
715/// Decodes 64 characters into 48 bytes; false if any is outside the alphabet.
716#[cfg(target_arch = "aarch64")]
717#[inline(always)]
718unsafe fn decode64_neon(src: *const u8, dst: *mut u8, lo: uint8x16x4_t, hi: uint8x16x4_t) -> bool {
719    let c = vld4q_u8(src);
720    // Bytes below 64 hit `lo`; 64..128 fall through to `hi`; 128+ keep 0 and are caught by their top bit.
721    let look = |c: uint8x16_t| vqtbx4q_u8(vqtbl4q_u8(lo, c), hi, vsubq_u8(c, vdupq_n_u8(64)));
722    let (v0, v1, v2, v3) = (look(c.0), look(c.1), look(c.2), look(c.3));
723    let high = vandq_u8(vorrq_u8(vorrq_u8(c.0, c.1), vorrq_u8(c.2, c.3)), vdupq_n_u8(0x80));
724    if vmaxvq_u8(vorrq_u8(vorrq_u8(vorrq_u8(v0, v1), vorrq_u8(v2, v3)), high)) > 63 {
725        return false;
726    }
727    let o0 = vorrq_u8(vshlq_n_u8(v0, 2), vshrq_n_u8(v1, 4));
728    let o1 = vorrq_u8(vshlq_n_u8(v1, 4), vshrq_n_u8(v2, 2));
729    let o2 = vorrq_u8(vshlq_n_u8(v2, 6), v3);
730    vst3q_u8(dst, uint8x16x3_t(o0, o1, o2));
731    true
732}
733
734/// Decodes 32 characters into 24 bytes; false if any is outside the alphabet.
735#[cfg(target_arch = "aarch64")]
736#[inline(always)]
737unsafe fn decode32_neon(src: *const u8, dst: *mut u8, lo: uint8x16x4_t, hi: uint8x16x4_t) -> bool {
738    let c = vld4_u8(src);
739    let look = |c: uint8x8_t| vqtbx4_u8(vqtbl4_u8(lo, c), hi, vsub_u8(c, vdup_n_u8(64)));
740    let (v0, v1, v2, v3) = (look(c.0), look(c.1), look(c.2), look(c.3));
741    let high = vand_u8(vorr_u8(vorr_u8(c.0, c.1), vorr_u8(c.2, c.3)), vdup_n_u8(0x80));
742    if vmaxv_u8(vorr_u8(vorr_u8(vorr_u8(v0, v1), vorr_u8(v2, v3)), high)) > 63 {
743        return false;
744    }
745    let o0 = vorr_u8(vshl_n_u8(v0, 2), vshr_n_u8(v1, 4));
746    let o1 = vorr_u8(vshl_n_u8(v1, 4), vshr_n_u8(v2, 2));
747    let o2 = vorr_u8(vshl_n_u8(v2, 6), v3);
748    vst3_u8(dst, uint8x8x3_t(o0, o1, o2));
749    true
750}
751
752#[cfg(test)]
753mod tests {
754    use super::*;
755
756    pub(super) fn levels() -> Vec<Level> {
757        #[allow(unused_mut)]
758        let mut v = vec![Level::Scalar];
759        #[cfg(target_arch = "x86_64")]
760        {
761            if is_x86_feature_detected!("ssse3") {
762                v.push(Level::Ssse3);
763            }
764            if is_x86_feature_detected!("avx2") {
765                v.push(Level::Avx2);
766            }
767        }
768        #[cfg(target_arch = "aarch64")]
769        v.push(Level::Neon);
770        v
771    }
772
773    fn encode_with(e: &Engine, src: &[u8], level: Level) -> String {
774        let len = e.encoded_len(src.len());
775        let mut v = Vec::with_capacity(len);
776        unsafe {
777            e.encode_raw(src, v.as_mut_ptr(), level);
778            v.set_len(len);
779        }
780        String::from_utf8(v).unwrap()
781    }
782
783    /// A deterministic byte stream (xorshift), so failures reproduce.
784    fn bytes(seed: u64, n: usize) -> Vec<u8> {
785        let mut s = seed | 1;
786        (0..n)
787            .map(|_| {
788                s ^= s << 13;
789                s ^= s >> 7;
790                s ^= s << 17;
791                s as u8
792            })
793            .collect()
794    }
795
796    #[test]
797    fn rfc4648_vectors() {
798        for (raw, enc) in [("", ""), ("f", "Zg=="), ("fo", "Zm8="), ("foo", "Zm9v"), ("foob", "Zm9vYg=="), ("fooba", "Zm9vYmE="), ("foobar", "Zm9vYmFy")] {
799            assert_eq!(STANDARD.encode_to_string(raw), enc);
800            assert_eq!(STANDARD.decode_to_vec(enc).unwrap(), raw.as_bytes());
801            let bare = enc.trim_end_matches('=');
802            assert_eq!(URL_SAFE_NO_PAD.encode_to_string(raw), bare);
803            assert_eq!(URL_SAFE_NO_PAD.decode_to_vec(bare).unwrap(), raw.as_bytes());
804        }
805        assert_eq!(STANDARD.encode_to_string([0xfb, 0xff]), "+/8=");
806        assert_eq!(URL_SAFE_NO_PAD.encode_to_string([0xfb, 0xff]), "-_8");
807    }
808
809    #[test]
810    fn every_level_matches_the_reference_for_every_length() {
811        use base64::Engine as _;
812        let std_ref = base64::engine::general_purpose::STANDARD;
813        let url_ref = base64::engine::general_purpose::URL_SAFE_NO_PAD;
814        for n in 0..400 {
815            let data = bytes(n as u64 + 7, n);
816            let (s, u) = (std_ref.encode(&data), url_ref.encode(&data));
817            for level in levels() {
818                assert_eq!(encode_with(&STANDARD, &data, level), s, "{level:?} n={n}");
819                assert_eq!(encode_with(&URL_SAFE_NO_PAD, &data, level), u, "{level:?} n={n}");
820                assert_eq!(STANDARD.decode_with(s.as_bytes(), level).unwrap(), data, "{level:?} n={n}");
821                assert_eq!(URL_SAFE_NO_PAD.decode_with(u.as_bytes(), level).unwrap(), data, "{level:?} n={n}");
822            }
823        }
824    }
825
826    #[test]
827    fn every_level_rejects_exactly_what_the_reference_rejects() {
828        use base64::Engine as _;
829        let std_ref = base64::engine::general_purpose::STANDARD;
830        let url_ref = base64::engine::general_purpose::URL_SAFE_NO_PAD;
831        // One byte of a valid encoding replaced, at every position, by every byte value.
832        for n in [1usize, 2, 3, 12, 13, 47, 48, 49, 95, 96, 100] {
833            let data = bytes(n as u64, n);
834            for (engine, reference) in [(&STANDARD, &std_ref), (&URL_SAFE_NO_PAD, &url_ref)] {
835                let good = reference.encode(&data).into_bytes();
836                for pos in 0..good.len() {
837                    for b in 0..=255u8 {
838                        let mut s = good.clone();
839                        s[pos] = b;
840                        let want = reference.decode(&s).ok();
841                        for level in levels() {
842                            assert_eq!(engine.decode_with(&s, level).ok(), want, "{level:?} n={n} pos={pos} byte={b}");
843                        }
844                    }
845                }
846            }
847        }
848    }
849
850    #[test]
851    fn padding_and_length_rules() {
852        for bad in ["A", "AB", "ABC", "A===", "AB=C", "====", "AB==C===", "Zg==Zg==", "Zh==", "Zm9=", " Zg=", "Zg==\n"] {
853            assert!(STANDARD.decode_to_vec(bad).is_err(), "{bad:?}");
854        }
855        for bad in ["A", "Zg==", "Zh", "Zm9", "AAAAA"] {
856            assert!(URL_SAFE_NO_PAD.decode_to_vec(bad).is_err(), "{bad:?}");
857        }
858    }
859
860    #[test]
861    fn append_keeps_what_was_there() {
862        let mut s = String::from("data:image/png;base64,");
863        STANDARD.encode_append(b"foobar", &mut s);
864        assert_eq!(s, "data:image/png;base64,Zm9vYmFy");
865    }
866}