use super::ByteClass;
const OUTSIDE: u8 = 0xFF;
#[derive(Debug)]
pub struct Alphabet {
decode: [u8; 256],
low: [u8; 16],
roll: [u8; 16],
odd: u8,
}
pub static STANDARD: Alphabet = Alphabet::new(
b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
b'/',
);
pub static URL_SAFE: Alphabet = Alphabet::new(
b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",
b'_',
);
impl Alphabet {
#[allow(clippy::cast_possible_truncation, reason = "a value is below 64")]
const fn new(symbols: &[u8; 64], odd: u8) -> Self {
let mut decode = [OUTSIDE; 256];
let mut roll = [0_u8; 16];
let mut ascii = 0_u128;
let mut value = 0;
while value < 64 {
let symbol = symbols[value];
decode[symbol as usize] = value as u8;
ascii |= 1 << symbol;
let slot = if symbol == odd {
symbol >> 4 | 8
} else {
symbol >> 4
};
roll[slot as usize] = (value as u8).wrapping_sub(symbol);
value += 1;
}
Self {
decode,
low: ByteClass::new(ascii).low,
roll,
odd,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Failure {
Malformed {
offset: usize,
reason: &'static str,
},
Limit,
}
const fn bad(offset: usize, reason: &'static str) -> Failure {
Failure::Malformed { offset, reason }
}
const fn is_space(byte: u8) -> bool {
matches!(byte, b' ' | b'\t' | b'\n' | b'\r' | 0x0C)
}
pub fn decode(
alphabet: &Alphabet,
text: &[u8],
skip_space: bool,
out: &mut Vec<u8>,
cap: usize,
) -> Result<(), Failure> {
let start = out.len();
let limit = start.saturating_add(cap);
let result = if skip_space {
by_table(alphabet, text, true, 0, out, limit)
} else {
by_vector_then_table(alphabet, text, out, cap, limit)
};
if result.is_err() {
out.truncate(start);
}
result
}
fn by_vector_then_table(
alphabet: &Alphabet,
text: &[u8],
out: &mut Vec<u8>,
cap: usize,
limit: usize,
) -> Result<(), Failure> {
let padding = text
.iter()
.rev()
.take(2)
.take_while(|&&b| b == b'=')
.count();
let symbols = &text[..text.len() - padding];
let decoded = symbols.len() / 4 * 3 + symbols.len() % 4 * 3 / 4;
if decoded > cap {
return Err(Failure::Limit);
}
out.reserve(decoded + SLACK);
let done = vector_steps(alphabet, symbols, out);
by_table(alphabet, &text[done..], false, done, out, limit)
}
const SLACK: usize = 8;
pub(super) fn by_table(
alphabet: &Alphabet,
text: &[u8],
skip_space: bool,
base: usize,
out: &mut Vec<u8>,
limit: usize,
) -> Result<(), Failure> {
let mut held = 0_u32;
let mut count = 0_usize;
let mut padding = 0_usize;
let mut last = 0_usize;
for (i, &byte) in text.iter().enumerate() {
let at = base + i;
if skip_space && is_space(byte) {
continue;
}
if byte == b'=' {
padding += 1;
if padding > 2 {
return Err(bad(at, "more than two padding bytes"));
}
continue;
}
if padding > 0 {
return Err(bad(at, "a symbol after the padding"));
}
let value = alphabet.decode[usize::from(byte)];
if value == OUTSIDE {
return Err(bad(at, "not a base64 symbol"));
}
held = held << 6 | u32::from(value);
count += 1;
last = at;
if count == 4 {
if out.len() + 3 > limit {
return Err(Failure::Limit);
}
let [_, a, b, c] = held.to_be_bytes();
out.extend_from_slice(&[a, b, c]);
held = 0;
count = 0;
}
}
let end = base + text.len();
let tail = match (count, padding) {
(0, 0) => return Ok(()),
(0, _) => return Err(bad(end, "padding after a whole group")),
(1, _) => return Err(bad(last, "one symbol left over")),
(2, _) if held.trailing_zeros() >= 4 => &(held >> 4).to_be_bytes()[3..],
(3, 0 | 1) if held.trailing_zeros() >= 2 => &(held >> 2).to_be_bytes()[2..],
(2, _) | (3, 0 | 1) => return Err(bad(last, "bits left over in the last symbol")),
_ => return Err(bad(end, "more padding than the group lacks")),
};
if out.len() + tail.len() > limit {
return Err(Failure::Limit);
}
out.extend_from_slice(tail);
Ok(())
}
fn vector_steps(alphabet: &Alphabet, symbols: &[u8], out: &mut Vec<u8>) -> usize {
#[cfg(target_arch = "x86_64")]
{
x86::steps(alphabet, symbols, out)
}
#[cfg(all(
target_arch = "aarch64",
target_endian = "little",
target_feature = "neon"
))]
{
neon::steps(alphabet, symbols, out)
}
#[cfg(not(any(
target_arch = "x86_64",
all(
target_arch = "aarch64",
target_endian = "little",
target_feature = "neon"
)
)))]
{
let _ = (alphabet, symbols, out);
0
}
}
#[cfg(any(
target_arch = "x86_64",
all(
target_arch = "aarch64",
target_endian = "little",
target_feature = "neon"
)
))]
#[allow(
clippy::inline_always,
reason = "a step can inline only into a caller that has its target features"
)]
#[inline(always)]
fn blocks<const IN: usize, const OUT: usize>(
symbols: &[u8],
out: &mut Vec<u8>,
mut step: impl FnMut(&[u8; IN], &mut [u8; OUT]) -> bool,
) -> usize {
let base = out.len();
let room = symbols.len() / IN * (IN / 4 * 3) + (OUT - IN / 4 * 3);
out.resize(base + room, 0);
let mut taken = 0;
let mut wrote = 0;
while let Some(block) = symbols.get(taken..).and_then(<[u8]>::first_chunk::<IN>)
&& let Some(dst) = out
.get_mut(base + wrote..)
.and_then(<[u8]>::first_chunk_mut::<OUT>)
&& step(block, dst)
{
taken += IN;
wrote += IN / 4 * 3;
}
out.truncate(base + wrote);
taken
}
#[cfg(target_arch = "x86_64")]
pub(super) mod x86 {
use std::arch::x86_64::{
__m128i, __m256i, _mm_add_epi8, _mm_and_si128, _mm_cmpeq_epi8, _mm_madd_epi16,
_mm_maddubs_epi16, _mm_movemask_epi8, _mm_or_si128, _mm_set1_epi8, _mm_set1_epi32,
_mm_setr_epi8, _mm_setzero_si128, _mm_shuffle_epi8, _mm_srli_epi16, _mm_storeu_si128,
_mm256_add_epi8, _mm256_and_si256, _mm256_broadcastsi128_si256, _mm256_cmpeq_epi8,
_mm256_madd_epi16, _mm256_maddubs_epi16, _mm256_movemask_epi8, _mm256_or_si256,
_mm256_permutevar8x32_epi32, _mm256_set1_epi8, _mm256_set1_epi32, _mm256_setr_epi8,
_mm256_setr_epi32, _mm256_setzero_si256, _mm256_shuffle_epi8, _mm256_srli_epi16,
_mm256_storeu_si256,
};
use super::{Alphabet, blocks};
use crate::kernel::x86::{HIGH, load16, load32};
#[allow(
unsafe_code,
reason = "a #[target_feature] function is called only after its feature is detected"
)]
pub(in crate::kernel) fn steps(
alphabet: &Alphabet,
symbols: &[u8],
out: &mut Vec<u8>,
) -> usize {
if is_x86_feature_detected!("avx2") {
return unsafe { avx2(alphabet, symbols, out) };
}
if is_x86_feature_detected!("ssse3") {
return unsafe { ssse3(alphabet, symbols, out) };
}
0
}
#[target_feature(enable = "avx2")]
pub(in crate::kernel) fn avx2(alphabet: &Alphabet, symbols: &[u8], out: &mut Vec<u8>) -> usize {
let low = _mm256_broadcastsi128_si256(load16(&alphabet.low));
let high = _mm256_broadcastsi128_si256(load16(&HIGH));
let roll = _mm256_broadcastsi128_si256(load16(&alphabet.roll));
let odd = _mm256_set1_epi8(alphabet.odd.cast_signed());
let nibble = _mm256_set1_epi8(0x0F);
let eight = _mm256_set1_epi8(8);
let pairs = _mm256_set1_epi32(0x0140_0140);
let quads = _mm256_set1_epi32(0x0001_1000);
let order = _mm256_setr_epi8(
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, -1,
);
let join = _mm256_setr_epi32(0, 1, 2, 4, 5, 6, 3, 7);
let taken = blocks::<32, 32>(symbols, out, |block, dst| {
let text = load32(block);
let hi = _mm256_and_si256(_mm256_srli_epi16(text, 4), nibble);
let lo = _mm256_and_si256(text, nibble);
let member =
_mm256_and_si256(_mm256_shuffle_epi8(low, lo), _mm256_shuffle_epi8(high, hi));
if _mm256_movemask_epi8(_mm256_cmpeq_epi8(member, _mm256_setzero_si256())) != 0 {
return false;
}
let odd_slot = _mm256_and_si256(_mm256_cmpeq_epi8(text, odd), eight);
let values = _mm256_add_epi8(
text,
_mm256_shuffle_epi8(roll, _mm256_or_si256(hi, odd_slot)),
);
let packed = _mm256_madd_epi16(_mm256_maddubs_epi16(values, pairs), quads);
let bytes = _mm256_permutevar8x32_epi32(_mm256_shuffle_epi8(packed, order), join);
store32(dst, bytes);
true
});
let rest = symbols.get(taken..).unwrap_or_default();
taken + ssse3(alphabet, rest, out)
}
#[target_feature(enable = "ssse3")]
pub(in crate::kernel) fn ssse3(
alphabet: &Alphabet,
symbols: &[u8],
out: &mut Vec<u8>,
) -> usize {
let low = load16(&alphabet.low);
let high = load16(&HIGH);
let roll = load16(&alphabet.roll);
let odd = _mm_set1_epi8(alphabet.odd.cast_signed());
let nibble = _mm_set1_epi8(0x0F);
let eight = _mm_set1_epi8(8);
let pairs = _mm_set1_epi32(0x0140_0140);
let quads = _mm_set1_epi32(0x0001_1000);
let order = _mm_setr_epi8(2, 1, 0, 6, 5, 4, 10, 9, 8, 14, 13, 12, -1, -1, -1, -1);
blocks::<16, 16>(symbols, out, |block, dst| {
let text = load16(block);
let hi = _mm_and_si128(_mm_srli_epi16(text, 4), nibble);
let lo = _mm_and_si128(text, nibble);
let member = _mm_and_si128(_mm_shuffle_epi8(low, lo), _mm_shuffle_epi8(high, hi));
if _mm_movemask_epi8(_mm_cmpeq_epi8(member, _mm_setzero_si128())) != 0 {
return false;
}
let odd_slot = _mm_and_si128(_mm_cmpeq_epi8(text, odd), eight);
let values = _mm_add_epi8(text, _mm_shuffle_epi8(roll, _mm_or_si128(hi, odd_slot)));
let packed = _mm_madd_epi16(_mm_maddubs_epi16(values, pairs), quads);
store16(dst, _mm_shuffle_epi8(packed, order));
true
})
}
#[allow(
unsafe_code,
reason = "an unaligned vector store has no safe form that compiles to one store"
)]
#[inline]
#[target_feature(enable = "sse2")]
fn store16(dst: &mut [u8; 16], bytes: __m128i) {
unsafe { _mm_storeu_si128(std::ptr::from_mut(dst).cast(), bytes) }
}
#[allow(
unsafe_code,
reason = "an unaligned vector store has no safe form that compiles to one store"
)]
#[inline]
#[target_feature(enable = "avx")]
fn store32(dst: &mut [u8; 32], bytes: __m256i) {
unsafe { _mm256_storeu_si256(std::ptr::from_mut(dst).cast(), bytes) }
}
#[cfg(test)]
pub(in crate::kernel) type Tier = fn(&Alphabet, &[u8], &mut Vec<u8>) -> usize;
#[cfg(test)]
#[allow(
unsafe_code,
reason = "a #[target_feature] function is called only after its feature is detected"
)]
pub(in crate::kernel) fn tiers() -> Vec<(&'static str, Tier)> {
let mut tiers: Vec<(&'static str, Tier)> = Vec::new();
if is_x86_feature_detected!("avx2") {
tiers.push(("avx2", |a, s, o| unsafe { avx2(a, s, o) }));
}
if is_x86_feature_detected!("ssse3") {
tiers.push(("ssse3", |a, s, o| unsafe { ssse3(a, s, o) }));
}
tiers
}
}
#[cfg(all(
target_arch = "aarch64",
target_endian = "little",
target_feature = "neon"
))]
pub(super) mod neon {
use std::arch::aarch64::{
uint8x16_t, uint8x16x3_t, uint8x16x4_t, vaddq_u8, vandq_u8, vceqq_u8, vceqzq_u8,
vdupq_n_u8, vld4q_u8, vmaxvq_u8, vorrq_u8, vqtbl1q_u8, vshlq_n_u8, vshrq_n_u8, vst3q_u8,
};
use super::{Alphabet, blocks};
use crate::kernel::neon::{HIGH, load16};
#[allow(
unsafe_code,
reason = "a #[target_feature] function is called only where its feature is compiled in"
)]
pub(in crate::kernel) fn steps(
alphabet: &Alphabet,
symbols: &[u8],
out: &mut Vec<u8>,
) -> usize {
unsafe { whole_steps(alphabet, symbols, out) }
}
#[target_feature(enable = "neon")]
fn whole_steps(alphabet: &Alphabet, symbols: &[u8], out: &mut Vec<u8>) -> usize {
let low = load16(&alphabet.low);
let high = load16(&HIGH);
let roll = load16(&alphabet.roll);
let odd = vdupq_n_u8(alphabet.odd);
let nibble = vdupq_n_u8(0x0F);
let eight = vdupq_n_u8(8);
let value = |text: uint8x16_t| {
let hi = vshrq_n_u8::<4>(text);
let member = vandq_u8(
vqtbl1q_u8(low, vandq_u8(text, nibble)),
vqtbl1q_u8(high, hi),
);
let slot = vorrq_u8(hi, vandq_u8(vceqq_u8(text, odd), eight));
(vaddq_u8(text, vqtbl1q_u8(roll, slot)), vceqzq_u8(member))
};
blocks::<64, 48>(symbols, out, |block, dst| {
let text = load4(block);
let (a, a_out) = value(text.0);
let (b, b_out) = value(text.1);
let (c, c_out) = value(text.2);
let (d, d_out) = value(text.3);
if vmaxvq_u8(vorrq_u8(vorrq_u8(a_out, b_out), vorrq_u8(c_out, d_out))) != 0 {
return false;
}
let bytes = uint8x16x3_t(
vorrq_u8(vshlq_n_u8::<2>(a), vshrq_n_u8::<4>(b)),
vorrq_u8(vshlq_n_u8::<4>(b), vshrq_n_u8::<2>(c)),
vorrq_u8(vshlq_n_u8::<6>(c), d),
);
store3(dst, bytes);
true
})
}
#[allow(
unsafe_code,
reason = "a vector load from a pointer has no safe form that compiles to one load"
)]
#[inline]
#[target_feature(enable = "neon")]
fn load4(bytes: &[u8; 64]) -> uint8x16x4_t {
unsafe { vld4q_u8(bytes.as_ptr()) }
}
#[allow(
unsafe_code,
reason = "a vector store to a pointer has no safe form that compiles to one store"
)]
#[inline]
#[target_feature(enable = "neon")]
fn store3(dst: &mut [u8; 48], bytes: uint8x16x3_t) {
unsafe { vst3q_u8(dst.as_mut_ptr(), bytes) }
}
#[cfg(test)]
pub(in crate::kernel) type Tier = fn(&Alphabet, &[u8], &mut Vec<u8>) -> usize;
#[cfg(test)]
pub(in crate::kernel) fn tiers() -> Vec<(&'static str, Tier)> {
vec![("neon", steps)]
}
}