Vendor asic-rs 0.8.1 (280 crates, offline builds) + wxWidgets 3.3.3 (pristine + patch queue); UI spec + ADR-0003; M1 on asic-rs

This commit is contained in:
2026-09-15 10:41:00 -06:00
parent 6dc77e8eb0
commit a2b65bb47f
16427 changed files with 6972976 additions and 3 deletions
+411
View File
@@ -0,0 +1,411 @@
use crate::alphabet::Symbol;
use crate::{
engine::{general_purpose::INVALID_VALUE, DecodeEstimate, DecodeMetadata, DecodePaddingMode},
DecodeError, DecodeSliceError,
};
#[doc(hidden)]
pub struct GeneralPurposeEstimate {
/// input len % 4
rem: usize,
conservative_decoded_len: usize,
}
impl GeneralPurposeEstimate {
pub(crate) fn new(encoded_len: usize) -> Self {
let rem = encoded_len % 4;
Self {
rem,
conservative_decoded_len: (encoded_len / 4 + usize::from(rem > 0)) * 3,
}
}
}
impl DecodeEstimate for GeneralPurposeEstimate {
fn decoded_len_estimate(&self) -> usize {
self.conservative_decoded_len
}
}
/// Helper to avoid duplicating `num_chunks` calculation, which is costly on short inputs.
/// Returns the decode metadata, or an error.
// We're on the fragile edge of compiler heuristics here. If this is not inlined, slow. If this is
// inlined(always), a different slow. plain ol' inline makes the benchmarks happiest at the moment,
// but this is fragile and the best setting changes with only minor code modifications.
#[allow(clippy::too_many_arguments)]
#[inline]
pub(crate) fn decode_helper(
input: &[u8],
estimate: &GeneralPurposeEstimate,
output: &mut [u8],
decode_table: &[u8; 256],
decode_allow_trailing_bits: bool,
padding: Symbol,
padding_mode: DecodePaddingMode,
simd_prefix: impl FnOnce(&[u8], usize, &mut [u8]) -> (usize, usize),
) -> Result<DecodeMetadata, DecodeSliceError> {
let input_complete_nonterminal_quads_len =
complete_quads_len(input, estimate.rem, output.len(), decode_table, padding)?;
let output_complete_quad_len = input_complete_nonterminal_quads_len / 4 * 3;
// A SIMD backend, when applicable, decodes a leading prefix; the scalar loops decode the rest.
// `simd_prefix` returns `(input_consumed, output_written)` and must consume only whole, valid
// quads: `input_consumed % 4 == 0` and `<= input_complete_nonterminal_quads_len` (the terminal
// quad is left to `decode_suffix`), `output_written == input_consumed / 4 * 3`, and only those
// output bytes are written. It stops on the first invalid/ambiguous quad so the scalar decoder
// reports the precise error offset. `(0, 0)` (pure scalar) is always valid.
let (input_index, output_index) =
simd_prefix(input, input_complete_nonterminal_quads_len, output);
debug_assert!(input_index % 4 == 0, "prefix must consume whole quads");
debug_assert!(
input_index <= input_complete_nonterminal_quads_len,
"prefix must not consume the terminal quad"
);
debug_assert!(
output_index == input_index / 4 * 3,
"prefix output must match consumed input"
);
decode_complete_quads(
input,
input_index,
input_complete_nonterminal_quads_len,
decode_table,
output,
output_index,
)?;
super::decode_suffix::decode_suffix(
input,
input_complete_nonterminal_quads_len,
output,
output_complete_quad_len,
decode_table,
decode_allow_trailing_bits,
padding,
padding_mode,
)
}
/// Decode the complete non-terminal quads in `input[input_index_start..input_index_end]` (both
/// bounds multiples of 4), writing to `output` starting at `output_index_start`, which must equal
/// `input_index_start / 4 * 3`. Error offsets are reported in absolute input coordinates.
#[inline]
fn decode_complete_quads(
input: &[u8],
input_index_start: usize,
input_index_end: usize,
decode_table: &[u8; 256],
output: &mut [u8],
output_index_start: usize,
) -> Result<(), DecodeSliceError> {
debug_assert!(
input_index_start % 4 == 0,
"quad start must be quad-aligned"
);
debug_assert!(input_index_end % 4 == 0, "quad end must be quad-aligned");
debug_assert!(
output_index_start == input_index_start / 4 * 3,
"output start must match consumed input"
);
const UNROLLED_INPUT_CHUNK_SIZE: usize = 32;
const UNROLLED_OUTPUT_CHUNK_SIZE: usize = UNROLLED_INPUT_CHUNK_SIZE / 4 * 3;
let quads_len = input_index_end - input_index_start;
let unrolled_loop_len = quads_len - quads_len % UNROLLED_INPUT_CHUNK_SIZE;
let input_unrolled_loop_end = input_index_start + unrolled_loop_len;
// chunks of 32 bytes
for (chunk_index, chunk) in input[input_index_start..input_unrolled_loop_end]
.chunks_exact(UNROLLED_INPUT_CHUNK_SIZE)
.enumerate()
{
let input_index = input_index_start + chunk_index * UNROLLED_INPUT_CHUNK_SIZE;
let output_base = output_index_start + chunk_index * UNROLLED_OUTPUT_CHUNK_SIZE;
let chunk_output = &mut output[output_base..output_base + UNROLLED_OUTPUT_CHUNK_SIZE];
decode_chunk_8(
&chunk[0..8],
input_index,
decode_table,
&mut chunk_output[0..6],
)?;
decode_chunk_8(
&chunk[8..16],
input_index + 8,
decode_table,
&mut chunk_output[6..12],
)?;
decode_chunk_8(
&chunk[16..24],
input_index + 16,
decode_table,
&mut chunk_output[12..18],
)?;
decode_chunk_8(
&chunk[24..32],
input_index + 24,
decode_table,
&mut chunk_output[18..24],
)?;
}
// remaining quads, except for the last possibly partial one, as it may have padding
let output_after_unroll_start = output_index_start + unrolled_loop_len / 4 * 3;
for (chunk_index, chunk) in input[input_unrolled_loop_end..input_index_end]
.chunks_exact(4)
.enumerate()
{
let output_base = output_after_unroll_start + chunk_index * 3;
let chunk_output = &mut output[output_base..output_base + 3];
decode_chunk_4(
chunk,
input_unrolled_loop_end + chunk_index * 4,
decode_table,
chunk_output,
)?;
}
Ok(())
}
/// Returns the length of complete quads, except for the last one, even if it is complete.
///
/// Returns an error if the output len is not big enough for decoding those complete quads, or if
/// the input % 4 == 1, and that last byte is an invalid value other than a pad byte.
///
/// - `input` is the base64 input
/// - `input_len_rem` is input len % 4
/// - `output_len` is the length of the output slice
pub(crate) fn complete_quads_len(
input: &[u8],
input_len_rem: usize,
output_len: usize,
decode_table: &[u8; 256],
padding: Symbol,
) -> Result<usize, DecodeSliceError> {
debug_assert!(input.len() % 4 == input_len_rem);
// detect a trailing invalid byte, like a newline, as a user convenience
if input_len_rem == 1 {
let last_byte = input[input.len() - 1];
// exclude pad bytes; might be part of padding that extends from earlier in the input
if last_byte != padding.as_u8() && decode_table[usize::from(last_byte)] == INVALID_VALUE {
return Err(DecodeError::InvalidByte(input.len() - 1, last_byte).into());
}
};
// skip last quad, even if it's complete, as it may have padding
let input_complete_nonterminal_quads_len = input
.len()
.saturating_sub(input_len_rem)
// if rem was 0, subtract 4 to avoid padding
.saturating_sub(usize::from(input_len_rem == 0) * 4);
debug_assert!(
input.is_empty() || (1..=4).contains(&(input.len() - input_complete_nonterminal_quads_len))
);
// check that everything except the last quad handled by decode_suffix will fit
if output_len < input_complete_nonterminal_quads_len / 4 * 3 {
return Err(DecodeSliceError::OutputSliceTooSmall);
};
Ok(input_complete_nonterminal_quads_len)
}
/// Decode 8 bytes of input into 6 bytes of output.
///
/// `input` is the 8 bytes to decode.
/// `index_at_start_of_input` is the offset in the overall input (used for reporting errors
/// accurately)
/// `decode_table` is the lookup table for the particular base64 alphabet.
/// `output` will have its first 6 bytes overwritten
// yes, really inline (worth 30-50% speedup)
#[inline(always)]
fn decode_chunk_8(
input: &[u8],
index_at_start_of_input: usize,
decode_table: &[u8; 256],
output: &mut [u8],
) -> Result<(), DecodeError> {
let morsel = decode_table[usize::from(input[0])];
if morsel == INVALID_VALUE {
return Err(DecodeError::InvalidByte(index_at_start_of_input, input[0]));
}
let mut accum = u64::from(morsel) << 58;
let morsel = decode_table[usize::from(input[1])];
if morsel == INVALID_VALUE {
return Err(DecodeError::InvalidByte(
index_at_start_of_input + 1,
input[1],
));
}
accum |= u64::from(morsel) << 52;
let morsel = decode_table[usize::from(input[2])];
if morsel == INVALID_VALUE {
return Err(DecodeError::InvalidByte(
index_at_start_of_input + 2,
input[2],
));
}
accum |= u64::from(morsel) << 46;
let morsel = decode_table[usize::from(input[3])];
if morsel == INVALID_VALUE {
return Err(DecodeError::InvalidByte(
index_at_start_of_input + 3,
input[3],
));
}
accum |= u64::from(morsel) << 40;
let morsel = decode_table[usize::from(input[4])];
if morsel == INVALID_VALUE {
return Err(DecodeError::InvalidByte(
index_at_start_of_input + 4,
input[4],
));
}
accum |= u64::from(morsel) << 34;
let morsel = decode_table[usize::from(input[5])];
if morsel == INVALID_VALUE {
return Err(DecodeError::InvalidByte(
index_at_start_of_input + 5,
input[5],
));
}
accum |= u64::from(morsel) << 28;
let morsel = decode_table[usize::from(input[6])];
if morsel == INVALID_VALUE {
return Err(DecodeError::InvalidByte(
index_at_start_of_input + 6,
input[6],
));
}
accum |= u64::from(morsel) << 22;
let morsel = decode_table[usize::from(input[7])];
if morsel == INVALID_VALUE {
return Err(DecodeError::InvalidByte(
index_at_start_of_input + 7,
input[7],
));
}
accum |= u64::from(morsel) << 16;
output[..6].copy_from_slice(&accum.to_be_bytes()[..6]);
Ok(())
}
/// Like [`decode_chunk_8`] but for 4 bytes of input and 3 bytes of output.
#[inline(always)]
fn decode_chunk_4(
input: &[u8],
index_at_start_of_input: usize,
decode_table: &[u8; 256],
output: &mut [u8],
) -> Result<(), DecodeError> {
let morsel = decode_table[usize::from(input[0])];
if morsel == INVALID_VALUE {
return Err(DecodeError::InvalidByte(index_at_start_of_input, input[0]));
}
let mut accum = u32::from(morsel) << 26;
let morsel = decode_table[usize::from(input[1])];
if morsel == INVALID_VALUE {
return Err(DecodeError::InvalidByte(
index_at_start_of_input + 1,
input[1],
));
}
accum |= u32::from(morsel) << 20;
let morsel = decode_table[usize::from(input[2])];
if morsel == INVALID_VALUE {
return Err(DecodeError::InvalidByte(
index_at_start_of_input + 2,
input[2],
));
}
accum |= u32::from(morsel) << 14;
let morsel = decode_table[usize::from(input[3])];
if morsel == INVALID_VALUE {
return Err(DecodeError::InvalidByte(
index_at_start_of_input + 3,
input[3],
));
}
accum |= u32::from(morsel) << 8;
output[..3].copy_from_slice(&accum.to_be_bytes()[..3]);
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::engine::general_purpose::STANDARD;
#[test]
fn decode_chunk_8_writes_only_6_bytes() {
let input = b"Zm9vYmFy"; // "foobar"
let mut output = [0_u8, 1, 2, 3, 4, 5, 6, 7];
decode_chunk_8(&input[..], 0, &STANDARD.decode_table, &mut output).unwrap();
assert_eq!(&vec![b'f', b'o', b'o', b'b', b'a', b'r', 6, 7], &output);
}
#[test]
fn decode_chunk_4_writes_only_3_bytes() {
let input = b"Zm9v"; // "foobar"
let mut output = [0_u8, 1, 2, 3];
decode_chunk_4(&input[..], 0, &STANDARD.decode_table, &mut output).unwrap();
assert_eq!(&vec![b'f', b'o', b'o', 3], &output);
}
#[test]
fn estimate_short_lengths() {
for (range, decoded_len_estimate) in [
(0..=0, 0),
(1..=4, 3),
(5..=8, 6),
(9..=12, 9),
(13..=16, 12),
(17..=20, 15),
] {
for encoded_len in range {
let estimate = GeneralPurposeEstimate::new(encoded_len);
assert_eq!(decoded_len_estimate, estimate.decoded_len_estimate());
}
}
}
#[test]
fn estimate_via_u128_inflation() {
// cover both ends of usize
(0..1000)
.chain(usize::MAX - 1000..=usize::MAX)
.for_each(|encoded_len| {
// inflate to 128 bit type to be able to safely use the easy formulas
let len_128 = encoded_len as u128;
let estimate = GeneralPurposeEstimate::new(encoded_len);
assert_eq!(
(len_128 + 3) / 4 * 3,
estimate.conservative_decoded_len as u128
);
})
}
}
@@ -0,0 +1,170 @@
use crate::alphabet::Symbol;
use crate::{
engine::{general_purpose::INVALID_VALUE, DecodeMetadata, DecodePaddingMode},
DecodeError, DecodeSliceError,
};
/// Decode the last 0-4 bytes, checking for trailing set bits and padding per the provided
/// parameters.
///
/// Returns the decode metadata representing the total number of bytes decoded, including the ones
/// indicated as already written by `output_index`.
#[allow(clippy::too_many_arguments)]
pub(crate) fn decode_suffix(
input: &[u8],
input_index: usize,
output: &mut [u8],
mut output_index: usize,
decode_table: &[u8; 256],
decode_allow_trailing_bits: bool,
padding: Symbol,
padding_mode: DecodePaddingMode,
) -> Result<DecodeMetadata, DecodeSliceError> {
debug_assert!((input.len() - input_index) <= 4);
// Decode any leftovers that might not be a complete input chunk of 4 bytes.
// Use a u32 as a stack-resident 4 byte buffer.
let mut morsels_in_leftover = 0;
let mut padding_bytes_count = 0;
// offset from input_index
let mut first_padding_offset: usize = 0;
let mut last_symbol = 0_u8;
let mut last_symbol_value = 0_u8;
let mut morsels = [0_u8; 4];
for (leftover_index, &b) in input[input_index..].iter().enumerate() {
// '=' padding
if b == padding.as_u8() {
// There can be bad padding bytes in a few ways:
// 1 - Padding with non-padding characters after it
// 2 - Padding after zero or one characters in the current quad (should only
// be after 2 or 3 chars)
// 3 - More than two characters of padding. If 3 or 4 padding chars
// are in the same quad, that implies it will be caught by #2.
// If it spreads from one quad to another, it will be an invalid byte
// in the first quad.
// 4 - Non-canonical padding -- 1 byte when it should be 2, etc.
// Per config, non-canonical but still functional non- or partially-padded base64
// may be treated as an error condition.
if leftover_index < 2 {
// Check for error #2.
// Either the previous byte was padding, in which case we would have already hit
// this case, or it wasn't, in which case this is the first such error.
debug_assert!(
leftover_index == 0 || (leftover_index == 1 && padding_bytes_count == 0)
);
let bad_padding_index = input_index + leftover_index;
return Err(DecodeError::InvalidByte(bad_padding_index, b).into());
}
if padding_bytes_count == 0 {
first_padding_offset = leftover_index;
}
padding_bytes_count += 1;
continue;
}
// Check for case #1.
// To make '=' handling consistent with the main loop, don't allow
// non-suffix '=' in trailing chunk either. Report error as first
// erroneous padding.
if padding_bytes_count > 0 {
return Err(DecodeError::InvalidByte(
input_index + first_padding_offset,
padding.as_u8(),
)
.into());
}
last_symbol = b;
// can use up to 8 * 6 = 48 bits of the u64, if last chunk has no padding.
// Pack the leftovers from left to right.
let morsel = decode_table[b as usize];
last_symbol_value = morsel;
if morsel == INVALID_VALUE {
return Err(DecodeError::InvalidByte(input_index + leftover_index, b).into());
}
morsels[morsels_in_leftover] = morsel;
morsels_in_leftover += 1;
}
// If there was 1 trailing byte, and it was valid, and we got to this point without hitting
// an invalid byte, now we can report invalid length
if !input.is_empty() && morsels_in_leftover < 2 {
return Err(DecodeError::InvalidLength(input_index + morsels_in_leftover).into());
}
match padding_mode {
DecodePaddingMode::Indifferent => { /* everything we care about was already checked */ }
DecodePaddingMode::RequireCanonical => {
// allow empty input
if (padding_bytes_count + morsels_in_leftover) % 4 != 0 {
return Err(DecodeError::InvalidPadding.into());
}
}
DecodePaddingMode::RequireNone => {
if padding_bytes_count > 0 {
// check at the end to make sure we let the cases of padding that should be InvalidByte
// get hit
return Err(DecodeError::InvalidPadding.into());
}
}
}
// When encoding 1 trailing byte (e.g. 0xFF), 2 base64 bytes ("/w") are needed.
// / is the symbol for 63 (0x3F, bottom 6 bits all set) and w is 48 (0x30, top 2 bits
// of bottom 6 bits set).
// When decoding two symbols back to one trailing byte, any final symbol higher than
// w would still decode to the original byte because we only care about the top two
// bits in the bottom 6, but would be a non-canonical encoding. So, we calculate a
// mask based on how many bits are used for just the canonical encoding, and optionally
// error if any other bits are set. In the example of one encoded byte -> 2 symbols,
// 2 symbols can technically encode 12 bits, but the last 4 are non-canonical, and
// useless since there are no more symbols to provide the necessary 4 additional bits
// to finish the second original byte.
let leftover_bytes_to_append = morsels_in_leftover * 6 / 8;
// Put the up to 6 complete bytes as the high bytes.
// Gain a couple percent speedup from nudging these ORs to use more ILP with a two-way split.
let mut leftover_num = (u32::from(morsels[0]) << 26)
| (u32::from(morsels[1]) << 20)
| (u32::from(morsels[2]) << 14)
| (u32::from(morsels[3]) << 8);
// if there are bits set outside the bits we care about, last symbol encodes trailing bits that
// will not be included in the output
let mask = !0_u32 >> (leftover_bytes_to_append * 8);
if !decode_allow_trailing_bits && (leftover_num & mask) != 0 {
// last morsel is at `morsels_in_leftover` - 1
return Err(DecodeError::InvalidLastSymbol {
offset: input_index + morsels_in_leftover - 1,
symbol: last_symbol,
symbol_value: last_symbol_value,
}
.into());
}
// Strangely, this approach benchmarks better than writing bytes one at a time,
// or copy_from_slice into output.
for _ in 0..leftover_bytes_to_append {
let hi_byte = (leftover_num >> 24) as u8;
leftover_num <<= 8;
*output
.get_mut(output_index)
.ok_or(DecodeSliceError::OutputSliceTooSmall)? = hi_byte;
output_index += 1;
}
Ok(DecodeMetadata::new(
output_index,
if padding_bytes_count > 0 {
Some(input_index + first_padding_offset)
} else {
None
},
))
}
+508
View File
@@ -0,0 +1,508 @@
//! Provides the [`GeneralPurpose`] engine and associated config types.
//!
//! See preconfigured engines like [`STANDARD_NO_PAD`] or [`STANDARD_NO_PAD_INDIFFERENT`].
use crate::alphabet::Symbol;
use crate::{
alphabet,
alphabet::Alphabet,
engine::{Config, DecodeMetadata, DecodePaddingMode},
DecodeSliceError,
};
use core::convert::TryInto;
pub(crate) mod decode;
pub(crate) mod decode_suffix;
pub use decode::GeneralPurposeEstimate;
pub(crate) const INVALID_VALUE: u8 = 255;
/// A general-purpose base64 engine.
///
/// - It uses no vector CPU instructions, so it will work on any system. For a version that uses
/// SIMD where available, see the SIMD engines behind the `simd-unsafe` feature.
/// - It is reasonably fast (~2-3GiB/s).
/// - It is not constant-time, though, so it is vulnerable to timing side-channel attacks. For loading cryptographic keys, etc, it is suggested to use the forthcoming constant-time implementation.
#[derive(Debug, Clone)]
pub struct GeneralPurpose {
encode_table: [u8; 64],
decode_table: [u8; 256],
pub(crate) padding: Symbol,
config: GeneralPurposeConfig,
}
/// A purely scalar base64 engine that never uses hardware-specific vector instructions.
///
/// This is an alias for [`GeneralPurpose`], giving an explicit name for callers who want to
/// guarantee a scalar-only implementation.
pub type Scalar = GeneralPurpose;
impl GeneralPurpose {
/// Create a `GeneralPurpose` engine from an [Alphabet].
///
/// While not very expensive to initialize, ideally these should be cached
/// if the engine will be used repeatedly.
#[must_use]
pub const fn new(alphabet: &Alphabet, config: GeneralPurposeConfig) -> Self {
Self {
encode_table: encode_table(alphabet),
decode_table: decode_table(alphabet),
padding: alphabet.padding,
config,
}
}
/// The 6-bit-index-to-ASCII encode table.
#[cfg(all(
feature = "simd-unsafe",
any(
target_arch = "x86_64",
all(target_arch = "aarch64", target_feature = "neon")
)
))]
pub(crate) fn encode_table(&self) -> &[u8; 64] {
&self.encode_table
}
/// The ASCII-to-6-bit-value decode table.
#[cfg(all(
feature = "simd-unsafe",
any(
target_arch = "x86_64",
all(target_arch = "aarch64", target_feature = "neon")
)
))]
pub(crate) fn decode_table(&self) -> &[u8; 256] {
&self.decode_table
}
}
impl super::Engine for GeneralPurpose {
type Config = GeneralPurposeConfig;
type DecodeEstimate = GeneralPurposeEstimate;
fn internal_encode(&self, input: &[u8], output: &mut [u8]) -> usize {
encode_helper(&self.encode_table, input, output, |_, _| (0, 0))
}
fn internal_decoded_len_estimate(&self, input_len: usize) -> Self::DecodeEstimate {
GeneralPurposeEstimate::new(input_len)
}
fn internal_decode(
&self,
input: &[u8],
output: &mut [u8],
estimate: Self::DecodeEstimate,
) -> Result<DecodeMetadata, DecodeSliceError> {
decode::decode_helper(
input,
&estimate,
output,
&self.decode_table,
self.config.decode_allow_trailing_bits,
self.padding,
self.config.decode_padding_mode,
|_, _, _| (0, 0),
)
}
fn config(&self) -> &Self::Config {
&self.config
}
fn padding(&self) -> Symbol {
self.padding
}
}
/// Scalar base64 encode of `input` into `output`, returning the number of bytes written.
///
/// `simd_prefix` gets first crack at the input, returning `(input_consumed, output_written)`. It
/// must consume whole 3-byte groups: `input_consumed % 3 == 0`, `output_written == input_consumed /
/// 3 * 4`, both in bounds, and only those `output_written` bytes are written. `(0, 0)` (pure scalar)
/// is always valid.
#[inline]
pub(crate) fn encode_helper(
encode_table: &[u8; 64],
input: &[u8],
output: &mut [u8],
simd_prefix: impl FnOnce(&[u8], &mut [u8]) -> (usize, usize),
) -> usize {
let (input_index, output_index) = simd_prefix(input, output);
debug_assert!(
input_index % 3 == 0,
"prefix must consume whole 3-byte groups"
);
debug_assert!(
output_index == input_index / 3 * 4,
"prefix output must match consumed input"
);
debug_assert!(input_index <= input.len());
debug_assert!(output_index <= output.len());
encode_scalar_tail(encode_table, input, output, input_index, output_index)
}
/// Scalar encode of `input[input_index..]` into `output[output_index..]`, resuming from a 3-byte
/// group boundary. Returns the total number of output bytes written.
fn encode_scalar_tail(
encode_table: &[u8; 64],
input: &[u8],
output: &mut [u8],
mut input_index: usize,
mut output_index: usize,
) -> usize {
const BLOCKS_PER_FAST_LOOP: usize = 4;
const LOW_SIX_BITS: u64 = 0x3F;
// we read 8 bytes at a time (u64) but only actually consume 6 of those bytes. Thus, we need
// 2 trailing bytes to be available to read..
let last_fast_index = input.len().saturating_sub(BLOCKS_PER_FAST_LOOP * 6 + 2);
if last_fast_index > 0 {
while input_index <= last_fast_index {
// Major performance wins from letting the optimizer do the bounds check once, mostly
// on the output side
let input_chunk = &input[input_index..(input_index + (BLOCKS_PER_FAST_LOOP * 6 + 2))];
let output_chunk = &mut output[output_index..(output_index + BLOCKS_PER_FAST_LOOP * 8)];
// Hand-unrolling for 32 vs 16 or 8 bytes produces yields performance about equivalent
// to unsafe pointer code on a Xeon E5-1650v3. 64 byte unrolling was slightly better for
// large inputs but significantly worse for 50-byte input, unsurprisingly. I suspect
// that it's a not uncommon use case to encode smallish chunks of data (e.g. a 64-byte
// SHA-512 digest), so it would be nice if that fit in the unrolled loop at least once.
// Plus, single-digit percentage performance differences might well be quite different
// on different hardware.
let input_u64 = read_u64(&input_chunk[0..]);
output_chunk[0] = encode_table[((input_u64 >> 58) & LOW_SIX_BITS) as usize];
output_chunk[1] = encode_table[((input_u64 >> 52) & LOW_SIX_BITS) as usize];
output_chunk[2] = encode_table[((input_u64 >> 46) & LOW_SIX_BITS) as usize];
output_chunk[3] = encode_table[((input_u64 >> 40) & LOW_SIX_BITS) as usize];
output_chunk[4] = encode_table[((input_u64 >> 34) & LOW_SIX_BITS) as usize];
output_chunk[5] = encode_table[((input_u64 >> 28) & LOW_SIX_BITS) as usize];
output_chunk[6] = encode_table[((input_u64 >> 22) & LOW_SIX_BITS) as usize];
output_chunk[7] = encode_table[((input_u64 >> 16) & LOW_SIX_BITS) as usize];
let input_u64 = read_u64(&input_chunk[6..]);
output_chunk[8] = encode_table[((input_u64 >> 58) & LOW_SIX_BITS) as usize];
output_chunk[9] = encode_table[((input_u64 >> 52) & LOW_SIX_BITS) as usize];
output_chunk[10] = encode_table[((input_u64 >> 46) & LOW_SIX_BITS) as usize];
output_chunk[11] = encode_table[((input_u64 >> 40) & LOW_SIX_BITS) as usize];
output_chunk[12] = encode_table[((input_u64 >> 34) & LOW_SIX_BITS) as usize];
output_chunk[13] = encode_table[((input_u64 >> 28) & LOW_SIX_BITS) as usize];
output_chunk[14] = encode_table[((input_u64 >> 22) & LOW_SIX_BITS) as usize];
output_chunk[15] = encode_table[((input_u64 >> 16) & LOW_SIX_BITS) as usize];
let input_u64 = read_u64(&input_chunk[12..]);
output_chunk[16] = encode_table[((input_u64 >> 58) & LOW_SIX_BITS) as usize];
output_chunk[17] = encode_table[((input_u64 >> 52) & LOW_SIX_BITS) as usize];
output_chunk[18] = encode_table[((input_u64 >> 46) & LOW_SIX_BITS) as usize];
output_chunk[19] = encode_table[((input_u64 >> 40) & LOW_SIX_BITS) as usize];
output_chunk[20] = encode_table[((input_u64 >> 34) & LOW_SIX_BITS) as usize];
output_chunk[21] = encode_table[((input_u64 >> 28) & LOW_SIX_BITS) as usize];
output_chunk[22] = encode_table[((input_u64 >> 22) & LOW_SIX_BITS) as usize];
output_chunk[23] = encode_table[((input_u64 >> 16) & LOW_SIX_BITS) as usize];
let input_u64 = read_u64(&input_chunk[18..]);
output_chunk[24] = encode_table[((input_u64 >> 58) & LOW_SIX_BITS) as usize];
output_chunk[25] = encode_table[((input_u64 >> 52) & LOW_SIX_BITS) as usize];
output_chunk[26] = encode_table[((input_u64 >> 46) & LOW_SIX_BITS) as usize];
output_chunk[27] = encode_table[((input_u64 >> 40) & LOW_SIX_BITS) as usize];
output_chunk[28] = encode_table[((input_u64 >> 34) & LOW_SIX_BITS) as usize];
output_chunk[29] = encode_table[((input_u64 >> 28) & LOW_SIX_BITS) as usize];
output_chunk[30] = encode_table[((input_u64 >> 22) & LOW_SIX_BITS) as usize];
output_chunk[31] = encode_table[((input_u64 >> 16) & LOW_SIX_BITS) as usize];
output_index += BLOCKS_PER_FAST_LOOP * 8;
input_index += BLOCKS_PER_FAST_LOOP * 6;
}
}
// Encode what's left after the fast loop.
const LOW_SIX_BITS_U8: u8 = 0x3F;
let rem = input.len() % 3;
let start_of_rem = input.len() - rem;
// start at the first index not handled by fast loop, which may be 0.
while input_index < start_of_rem {
let input_chunk = &input[input_index..(input_index + 3)];
let output_chunk = &mut output[output_index..(output_index + 4)];
output_chunk[0] = encode_table[(input_chunk[0] >> 2) as usize];
output_chunk[1] =
encode_table[((input_chunk[0] << 4 | input_chunk[1] >> 4) & LOW_SIX_BITS_U8) as usize];
output_chunk[2] =
encode_table[((input_chunk[1] << 2 | input_chunk[2] >> 6) & LOW_SIX_BITS_U8) as usize];
output_chunk[3] = encode_table[(input_chunk[2] & LOW_SIX_BITS_U8) as usize];
input_index += 3;
output_index += 4;
}
if rem == 2 {
output[output_index] = encode_table[(input[start_of_rem] >> 2) as usize];
output[output_index + 1] = encode_table[((input[start_of_rem] << 4
| input[start_of_rem + 1] >> 4)
& LOW_SIX_BITS_U8) as usize];
output[output_index + 2] =
encode_table[((input[start_of_rem + 1] << 2) & LOW_SIX_BITS_U8) as usize];
output_index += 3;
} else if rem == 1 {
output[output_index] = encode_table[(input[start_of_rem] >> 2) as usize];
output[output_index + 1] =
encode_table[((input[start_of_rem] << 4) & LOW_SIX_BITS_U8) as usize];
output_index += 2;
}
output_index
}
/// Returns a table mapping a 6-bit index to the ASCII byte encoding of the index
pub(crate) const fn encode_table(alphabet: &Alphabet) -> [u8; 64] {
// the encode table is just the alphabet:
// 6-bit index lookup -> printable byte
let mut encode_table = [0_u8; 64];
{
let mut index = 0;
while index < 64 {
encode_table[index] = alphabet.symbols[index];
index += 1;
}
}
encode_table
}
/// Returns a table mapping base64 bytes as the lookup index to either:
/// - [`INVALID_VALUE`] for bytes that aren't members of the alphabet
/// - a byte whose lower 6 bits are the value that was encoded into the index byte
pub(crate) const fn decode_table(alphabet: &Alphabet) -> [u8; 256] {
let mut decode_table = [INVALID_VALUE; 256];
// Since the table is full of `INVALID_VALUE` already, we only need to overwrite
// the parts that are valid.
let mut index = 0_usize;
while index < 64 {
// The index in the alphabet is the 6-bit value we care about.
// Since the index is in 0-63, it is safe to cast to u8.
decode_table[alphabet.symbols[index] as usize] = index as u8;
index += 1;
}
decode_table
}
#[inline]
fn read_u64(s: &[u8]) -> u64 {
u64::from_be_bytes(s[..8].try_into().unwrap())
}
/// Contains configuration parameters for base64 encoding and decoding.
///
/// ```
/// # use base64::engine::GeneralPurposeConfig;
/// let config = GeneralPurposeConfig::new()
/// .with_encode_padding(false);
/// // further customize using `.with_*` methods as needed
/// ```
///
/// The constants [PAD] and [`NO_PAD`] cover most use cases.
///
/// To specify the characters used, see [Alphabet].
#[derive(Clone, Copy, Debug)]
pub struct GeneralPurposeConfig {
encode_padding: bool,
decode_allow_trailing_bits: bool,
decode_padding_mode: DecodePaddingMode,
}
impl GeneralPurposeConfig {
/// Create a new config with `padding` = `true`, `decode_allow_trailing_bits` = `false`, and
/// `decode_padding_mode = DecodePaddingMode::RequireCanonicalPadding`.
///
/// This probably matches most people's expectations, but consider disabling padding to save
/// a few bytes unless you specifically need it for compatibility with some legacy system.
#[must_use]
pub const fn new() -> Self {
Self {
// RFC states that padding must be applied by default
encode_padding: true,
decode_allow_trailing_bits: false,
decode_padding_mode: DecodePaddingMode::RequireCanonical,
}
}
/// Create a new config based on `self` with an updated `padding` setting.
///
/// If `padding` is `true`, encoding will append either 1 or 2 `=` padding characters as needed
/// to produce an output whose length is a multiple of 4.
///
/// Padding is not needed for correct decoding and only serves to waste bytes, but it's in the
/// [spec](https://datatracker.ietf.org/doc/html/rfc4648#section-3.2).
///
/// For new applications, consider not using padding if the decoders you're using don't require
/// padding to be present.
#[must_use]
pub const fn with_encode_padding(self, padding: bool) -> Self {
Self {
encode_padding: padding,
..self
}
}
/// Create a new config based on `self` with an updated `decode_allow_trailing_bits` setting.
///
/// Most users will not need to configure this. It's useful if you need to decode base64
/// produced by a buggy encoder that has bits set in the unused space on the last base64
/// character as per [forgiving-base64 decode](https://infra.spec.whatwg.org/#forgiving-base64-decode).
/// If invalid trailing bits are present and this is `true`, those bits will
/// be silently ignored, else `DecodeError::InvalidLastSymbol` will be emitted.
#[must_use]
pub const fn with_decode_allow_trailing_bits(self, allow: bool) -> Self {
Self {
decode_allow_trailing_bits: allow,
..self
}
}
/// Create a new config based on `self` with an updated `decode_padding_mode` setting.
///
/// Padding is not useful in terms of representing encoded data -- it makes no difference to
/// the decoder if padding is present or not, so if you have some un-padded input to decode, it
/// is perfectly fine to use `DecodePaddingMode::Indifferent` to prevent errors from being
/// emitted.
///
/// However, since in practice
/// [people who learned nothing from BER vs DER seem to expect base64 to have one canonical encoding](https://eprint.iacr.org/2022/361),
/// the default setting is the stricter `DecodePaddingMode::RequireCanonicalPadding`.
///
/// Or, if "canonical" in your circumstance means _no_ padding rather than padding to the
/// next multiple of four, there's `DecodePaddingMode::RequireNoPadding`.
#[must_use]
pub const fn with_decode_padding_mode(self, mode: DecodePaddingMode) -> Self {
Self {
decode_padding_mode: mode,
..self
}
}
}
impl Default for GeneralPurposeConfig {
/// Delegates to [`GeneralPurposeConfig::new`].
fn default() -> Self {
Self::new()
}
}
impl Config for GeneralPurposeConfig {
fn encode_padding(&self) -> bool {
self.encode_padding
}
}
#[cfg(all(
feature = "simd-unsafe",
any(
target_arch = "x86_64",
all(target_arch = "aarch64", target_feature = "neon")
)
))]
impl GeneralPurposeConfig {
/// Whether trailing bits are allowed when decoding.
pub(crate) fn decode_allow_trailing_bits(&self) -> bool {
self.decode_allow_trailing_bits
}
/// The decode padding mode.
pub(crate) fn decode_padding_mode(&self) -> DecodePaddingMode {
self.decode_padding_mode
}
}
/// A [`GeneralPurpose`] engine using the [`alphabet::STANDARD`] base64 alphabet and [`PAD`] config.
///
/// Does not allow trailing bits when decoding.
pub const STANDARD: GeneralPurpose = GeneralPurpose::new(&alphabet::STANDARD, PAD);
/// A [`GeneralPurpose`] engine using the [`alphabet::STANDARD`] base64 alphabet and
/// [`PAD_INDIFFERENT`] config.
///
/// Does not allow trailing bits when decoding.
pub const STANDARD_PAD_INDIFFERENT: GeneralPurpose =
GeneralPurpose::new(&alphabet::STANDARD, PAD_INDIFFERENT);
/// A [`GeneralPurpose`] engine using the [`alphabet::STANDARD`] base64 alphabet and [`NO_PAD`] config.
///
/// Does not allow trailing bits when decoding.
pub const STANDARD_NO_PAD: GeneralPurpose = GeneralPurpose::new(&alphabet::STANDARD, NO_PAD);
/// A [`GeneralPurpose`] engine using the [`alphabet::STANDARD`] base64 alphabet and
/// [`NO_PAD_INDIFFERENT`] config.
///
/// Does not allow trailing bits when decoding.
pub const STANDARD_NO_PAD_INDIFFERENT: GeneralPurpose =
GeneralPurpose::new(&alphabet::STANDARD, NO_PAD_INDIFFERENT);
/// A [`GeneralPurpose`] engine using the [`alphabet::URL_SAFE`] base64 alphabet and [`PAD`] config.
///
/// Does not allow trailing bits when decoding.
pub const URL_SAFE: GeneralPurpose = GeneralPurpose::new(&alphabet::URL_SAFE, PAD);
/// A [`GeneralPurpose`] engine using the [`alphabet::URL_SAFE`] base64 alphabet and
/// [`PAD_INDIFFERENT`] config.
///
/// Does not allow trailing bits when decoding.
pub const URL_SAFE_PAD_INDIFFERENT: GeneralPurpose =
GeneralPurpose::new(&alphabet::URL_SAFE, PAD_INDIFFERENT);
/// A [`GeneralPurpose`] engine using the [`alphabet::URL_SAFE`] base64 alphabet and [`NO_PAD`] config.
///
/// Does not allow trailing bits when decoding.
pub const URL_SAFE_NO_PAD: GeneralPurpose = GeneralPurpose::new(&alphabet::URL_SAFE, NO_PAD);
/// A [`GeneralPurpose`] engine using the [`alphabet::URL_SAFE`] base64 alphabet and
/// [`NO_PAD_INDIFFERENT`] config.
///
/// Does not allow trailing bits when decoding.
pub const URL_SAFE_NO_PAD_INDIFFERENT: GeneralPurpose =
GeneralPurpose::new(&alphabet::URL_SAFE, NO_PAD_INDIFFERENT);
/// Include padding bytes when encoding, and require that they be present when decoding.
///
/// Does not allow trailing bits when decoding.
///
/// This is the standard per the base64 RFC, but consider using [`NO_PAD`] or [`NO_PAD_INDIFFERENT`]
/// instead as padding serves little purpose in practice.
pub const PAD: GeneralPurposeConfig = GeneralPurposeConfig::new();
/// Include padding bytes when encoding, but allow input with or without padding when decoding.
///
/// Does not allow trailing bits when decoding.
pub const PAD_INDIFFERENT: GeneralPurposeConfig = GeneralPurposeConfig::new()
.with_encode_padding(true)
.with_decode_padding_mode(DecodePaddingMode::Indifferent);
/// Don't add padding when encoding, and require that there is no padding when decoding.
///
/// Does not allow trailing bits when decoding.
pub const NO_PAD: GeneralPurposeConfig = GeneralPurposeConfig::new()
.with_encode_padding(false)
.with_decode_padding_mode(DecodePaddingMode::RequireNone);
/// Don't add padding when encoding, and allow input with or without padding when decoding.
///
/// Does not allow trailing bits when decoding.
pub const NO_PAD_INDIFFERENT: GeneralPurposeConfig = GeneralPurposeConfig::new()
.with_encode_padding(false)
.with_decode_padding_mode(DecodePaddingMode::Indifferent);
+516
View File
@@ -0,0 +1,516 @@
//! Provides the [Engine] abstraction and out of the box implementations.
use crate::alphabet::Symbol;
#[cfg(any(feature = "alloc", test))]
use crate::chunked_encoder;
use crate::{
encode::{encode_with_padding, EncodeSliceError},
encoded_len, DecodeError, DecodeSliceError,
};
#[cfg(any(feature = "alloc", test))]
use alloc::vec::Vec;
#[cfg(any(feature = "alloc", test))]
use alloc::{string::String, vec};
pub mod general_purpose;
#[cfg(all(
feature = "simd-unsafe",
any(
target_arch = "x86_64",
all(target_arch = "aarch64", target_feature = "neon")
)
))]
pub mod simd;
#[cfg(test)]
mod naive;
#[cfg(test)]
mod tests;
pub use general_purpose::{GeneralPurpose, GeneralPurposeConfig, Scalar};
/// The runtime-detected SIMD engine. Requires the `simd-unsafe` feature.
#[cfg(all(
feature = "simd-unsafe",
feature = "std",
any(
target_arch = "x86_64",
all(target_arch = "aarch64", target_feature = "neon")
)
))]
pub use simd::Simd;
/// The AVX2 engine. Requires the `simd-unsafe` feature on an `x86_64` target.
#[cfg(all(feature = "simd-unsafe", target_arch = "x86_64"))]
pub use simd::Avx2;
/// The NEON engine. Requires the `simd-unsafe` feature on an `aarch64` target.
#[cfg(all(
feature = "simd-unsafe",
target_arch = "aarch64",
target_feature = "neon"
))]
pub use simd::Neon;
/// An `Engine` provides low-level encoding and decoding operations that all other higher-level parts of the API use. Users of the library will generally not need to implement this.
///
/// Different implementations offer different characteristics. The library currently ships with
/// [`GeneralPurpose`] that offers good speed and works on any CPU, with more choices
/// coming later, like a constant-time one when side channel resistance is called for, and vendor-specific vectorized ones for more speed.
///
/// See [`general_purpose::STANDARD_NO_PAD`] if you just want standard base64. Otherwise, when possible, it's
/// recommended to store the engine in a `const` so that references to it won't pose any lifetime
/// issues, and to avoid repeating the cost of engine setup.
///
/// Since almost nobody will need to implement `Engine`, docs for internal methods are hidden.
// When adding an implementation of Engine, include them in the engine test suite:
// - add an implementation of [engine::tests::EngineWrapper]
// - add the implementation to the `all_engines` macro
// All tests run on all engines listed in the macro.
pub trait Engine: Send + Sync {
/// The config type used by this engine
type Config: Config;
/// The decode estimate used by this engine
type DecodeEstimate: DecodeEstimate;
/// This is not meant to be called directly; it is only for `Engine` implementors.
/// See the other `encode*` functions on this trait.
///
/// Encode the `input` bytes into the `output` buffer based on the mapping in `encode_table`.
///
/// `output` will be long enough to hold the encoded data.
///
/// Returns the number of bytes written.
///
/// No padding should be written; that is handled separately.
///
/// Must not write any bytes into the output slice other than the encoded data.
#[doc(hidden)]
fn internal_encode(&self, input: &[u8], output: &mut [u8]) -> usize;
/// This is not meant to be called directly; it is only for `Engine` implementors.
///
/// As an optimization to prevent the decoded length from being calculated twice, it is
/// sometimes helpful to have a conservative estimate of the decoded size before doing the
/// decoding, so this calculation is done separately and passed to [Engine::decode()] as needed.
#[doc(hidden)]
fn internal_decoded_len_estimate(&self, input_len: usize) -> Self::DecodeEstimate;
/// This is not meant to be called directly; it is only for `Engine` implementors.
/// See the other `decode*` functions on this trait.
///
/// Decode `input` base64 bytes into the `output` buffer.
///
/// `decode_estimate` is the result of [Engine::internal_decoded_len_estimate()], which is passed in to avoid
/// calculating it again (expensive on short inputs).`
///
/// Each complete 4-byte chunk of encoded data decodes to 3 bytes of decoded data, but this
/// function must also handle the final possibly partial chunk.
/// If the input length is not a multiple of 4, or uses padding bytes to reach a multiple of 4,
/// the trailing 2 or 3 bytes must decode to 1 or 2 bytes, respectively, as per the
/// [RFC](https://tools.ietf.org/html/rfc4648#section-3.5).
///
/// Decoding must not write any bytes into the output slice other than the decoded data.
///
/// Non-canonical trailing bits in the final symbols or non-canonical padding must be reported as
/// errors unless the engine is configured otherwise.
#[doc(hidden)]
fn internal_decode(
&self,
input: &[u8],
output: &mut [u8],
decode_estimate: Self::DecodeEstimate,
) -> Result<DecodeMetadata, DecodeSliceError>;
/// Returns the config for this engine.
fn config(&self) -> &Self::Config;
/// Encode arbitrary octets as base64 using the provided `Engine`.
/// Returns a `String`.
///
/// # Example
///
/// ```rust
/// use base64::{Engine as _, engine::{self, general_purpose}, alphabet};
///
/// let b64 = general_purpose::STANDARD.encode(b"hello world~");
/// println!("{}", b64);
///
/// const CUSTOM_ENGINE: engine::GeneralPurpose =
/// engine::GeneralPurpose::new(&alphabet::URL_SAFE, general_purpose::NO_PAD);
///
/// let b64_url = CUSTOM_ENGINE.encode(b"hello internet~");
/// ```
#[cfg(any(feature = "alloc", test))]
#[inline]
fn encode<T: AsRef<[u8]>>(&self, input: T) -> String {
fn inner<E>(engine: &E, input_bytes: &[u8]) -> String
where
E: Engine + ?Sized,
{
let encoded_size = encoded_len(input_bytes.len(), engine.config().encode_padding())
.expect("integer overflow when calculating buffer size");
let mut buf = vec![0; encoded_size];
encode_with_padding(input_bytes, &mut buf[..], engine, encoded_size);
String::from_utf8(buf).expect("Invalid UTF8")
}
inner(self, input.as_ref())
}
/// Encode arbitrary octets as base64 into a supplied `String`.
/// Writes into the supplied `String`, which may allocate if its internal buffer isn't big enough.
///
/// # Example
///
/// ```rust
/// use base64::{Engine as _, engine::{self, general_purpose}, alphabet};
/// const CUSTOM_ENGINE: engine::GeneralPurpose =
/// engine::GeneralPurpose::new(&alphabet::URL_SAFE, general_purpose::NO_PAD);
///
/// fn main() {
/// let mut buf = String::new();
/// general_purpose::STANDARD.encode_string(b"hello world~", &mut buf);
/// println!("{}", buf);
///
/// buf.clear();
/// CUSTOM_ENGINE.encode_string(b"hello internet~", &mut buf);
/// println!("{}", buf);
/// }
/// ```
#[cfg(any(feature = "alloc", test))]
#[inline]
fn encode_string<T: AsRef<[u8]>>(&self, input: T, output_buf: &mut String) {
fn inner<E>(engine: &E, input_bytes: &[u8], output_buf: &mut String)
where
E: Engine + ?Sized,
{
let mut sink = chunked_encoder::StringSink::new(output_buf);
chunked_encoder::ChunkedEncoder::new(engine)
.encode(input_bytes, &mut sink)
.expect("Writing to a String shouldn't fail");
}
inner(self, input.as_ref(), output_buf);
}
/// Encode arbitrary octets as base64 into a supplied slice.
/// Writes into the supplied output buffer.
///
/// This is useful if you wish to avoid allocation entirely (e.g. encoding into a stack-resident
/// or statically-allocated buffer).
///
/// # Example
///
#[cfg_attr(feature = "alloc", doc = "```")]
#[cfg_attr(not(feature = "alloc"), doc = "```ignore")]
/// use base64::{Engine as _, engine::general_purpose};
/// let s = b"hello internet!";
/// let mut buf = Vec::new();
/// // make sure we'll have a slice big enough for base64 + padding
/// buf.resize(s.len() * 4 / 3 + 4, 0);
///
/// let bytes_written = general_purpose::STANDARD.encode_slice(s, &mut buf).unwrap();
///
/// // shorten our vec down to just what was written
/// buf.truncate(bytes_written);
///
/// assert_eq!(s, general_purpose::STANDARD.decode(&buf).unwrap().as_slice());
/// ```
#[inline]
fn encode_slice<T: AsRef<[u8]>>(
&self,
input: T,
output_buf: &mut [u8],
) -> Result<usize, EncodeSliceError> {
fn inner<E>(
engine: &E,
input_bytes: &[u8],
output_buf: &mut [u8],
) -> Result<usize, EncodeSliceError>
where
E: Engine + ?Sized,
{
let encoded_size = encoded_len(input_bytes.len(), engine.config().encode_padding())
.expect("usize overflow when calculating buffer size");
if output_buf.len() < encoded_size {
return Err(EncodeSliceError::OutputSliceTooSmall);
}
let b64_output = &mut output_buf[0..encoded_size];
encode_with_padding(input_bytes, b64_output, engine, encoded_size);
Ok(encoded_size)
}
inner(self, input.as_ref(), output_buf)
}
/// Decode the input into a new `Vec`.
///
/// # Example
///
/// ```rust
/// use base64::{Engine as _, alphabet, engine::{self, general_purpose}};
///
/// let bytes = general_purpose::STANDARD
/// .decode("aGVsbG8gd29ybGR+Cg==").unwrap();
/// println!("{:?}", bytes);
///
/// // custom engine setup
/// let bytes_url = engine::GeneralPurpose::new(
/// &alphabet::URL_SAFE,
/// general_purpose::NO_PAD)
/// .decode("aGVsbG8gaW50ZXJuZXR-Cg").unwrap();
/// println!("{:?}", bytes_url);
/// ```
#[cfg(any(feature = "alloc", test))]
#[inline]
fn decode<T: AsRef<[u8]>>(&self, input: T) -> Result<Vec<u8>, DecodeError> {
fn inner<E>(engine: &E, input_bytes: &[u8]) -> Result<Vec<u8>, DecodeError>
where
E: Engine + ?Sized,
{
let estimate = engine.internal_decoded_len_estimate(input_bytes.len());
let mut buffer = vec![0; estimate.decoded_len_estimate()];
let bytes_written = engine
.internal_decode(input_bytes, &mut buffer, estimate)
.map_err(|e| match e {
DecodeSliceError::DecodeError(e) => e,
DecodeSliceError::OutputSliceTooSmall => {
unreachable!("Vec is sized conservatively")
}
})?
.decoded_len;
buffer.truncate(bytes_written);
Ok(buffer)
}
inner(self, input.as_ref())
}
/// Decode the `input` into the supplied `buffer`.
///
/// Writes into the supplied `Vec`, which may allocate if its internal buffer isn't big enough.
/// Returns a `Result` containing an empty tuple, aka `()`.
///
/// # Example
///
/// ```rust
/// use base64::{Engine as _, alphabet, engine::{self, general_purpose}};
/// const CUSTOM_ENGINE: engine::GeneralPurpose =
/// engine::GeneralPurpose::new(&alphabet::URL_SAFE, general_purpose::PAD);
///
/// fn main() {
/// use base64::Engine;
/// let mut buffer = Vec::<u8>::new();
/// // with the default engine
/// general_purpose::STANDARD
/// .decode_vec("aGVsbG8gd29ybGR+Cg==", &mut buffer,).unwrap();
/// println!("{:?}", buffer);
///
/// buffer.clear();
///
/// // with a custom engine
/// CUSTOM_ENGINE.decode_vec(
/// "aGVsbG8gaW50ZXJuZXR-Cg==",
/// &mut buffer,
/// ).unwrap();
/// println!("{:?}", buffer);
/// }
/// ```
#[cfg(any(feature = "alloc", test))]
#[inline]
fn decode_vec<T: AsRef<[u8]>>(
&self,
input: T,
buffer: &mut Vec<u8>,
) -> Result<(), DecodeError> {
fn inner<E>(engine: &E, input_bytes: &[u8], buffer: &mut Vec<u8>) -> Result<(), DecodeError>
where
E: Engine + ?Sized,
{
let starting_output_len = buffer.len();
let estimate = engine.internal_decoded_len_estimate(input_bytes.len());
let total_len_estimate = estimate
.decoded_len_estimate()
.checked_add(starting_output_len)
.expect("Overflow when calculating output buffer length");
buffer.resize(total_len_estimate, 0);
let buffer_slice = &mut buffer.as_mut_slice()[starting_output_len..];
let bytes_written = engine
.internal_decode(input_bytes, buffer_slice, estimate)
.map_err(|e| match e {
DecodeSliceError::DecodeError(e) => e,
DecodeSliceError::OutputSliceTooSmall => {
unreachable!("Vec is sized conservatively")
}
})?
.decoded_len;
buffer.truncate(starting_output_len + bytes_written);
Ok(())
}
inner(self, input.as_ref(), buffer)
}
/// Decode the input into the provided output slice.
///
/// Returns the number of bytes written to the slice, or an error if `output` is smaller than
/// the estimated decoded length.
///
/// This will not write any bytes past exactly what is decoded (no stray garbage bytes at the end).
///
/// See [`crate::decoded_len_estimate`] for calculating buffer sizes.
///
/// See [`Engine::decode_slice_unchecked`] for a version that panics instead of returning an error
/// if the output buffer is too small.
#[inline]
fn decode_slice<T: AsRef<[u8]>>(
&self,
input: T,
output: &mut [u8],
) -> Result<usize, DecodeSliceError> {
fn inner<E>(
engine: &E,
input_bytes: &[u8],
output: &mut [u8],
) -> Result<usize, DecodeSliceError>
where
E: Engine + ?Sized,
{
engine
.internal_decode(
input_bytes,
output,
engine.internal_decoded_len_estimate(input_bytes.len()),
)
.map(|dm| dm.decoded_len)
}
inner(self, input.as_ref(), output)
}
/// Decode the input into the provided output slice.
///
/// Returns the number of bytes written to the slice.
///
/// This will not write any bytes past exactly what is decoded (no stray garbage bytes at the end).
///
/// See [`crate::decoded_len_estimate`] for calculating buffer sizes.
///
/// See [`Engine::decode_slice`] for a version that returns an error instead of panicking if the output
/// buffer is too small.
///
/// # Panics
///
/// Panics if the provided output buffer is too small for the decoded data.
#[inline]
fn decode_slice_unchecked<T: AsRef<[u8]>>(
&self,
input: T,
output: &mut [u8],
) -> Result<usize, DecodeError> {
fn inner<E>(engine: &E, input_bytes: &[u8], output: &mut [u8]) -> Result<usize, DecodeError>
where
E: Engine + ?Sized,
{
engine
.internal_decode(
input_bytes,
output,
engine.internal_decoded_len_estimate(input_bytes.len()),
)
.map(|dm| dm.decoded_len)
.map_err(|e| match e {
DecodeSliceError::DecodeError(e) => e,
DecodeSliceError::OutputSliceTooSmall => {
panic!("Output slice is too small")
}
})
}
inner(self, input.as_ref(), output)
}
/// Returns the symbol used for encode padding.
///
/// Typically this is `'='`, but weird alphabets may use other values.
fn padding(&self) -> Symbol;
}
/// The minimal level of configuration that engines must support.
pub trait Config {
/// Returns `true` if padding should be added after the encoded output.
///
/// Padding is added outside the engine's `encode()` since the engine may be used
/// to encode only a chunk of the overall output, so it can't always know when
/// the output is "done" and would therefore need padding (if configured).
// It could be provided as a separate parameter when encoding, but that feels like
// leaking an implementation detail to the user, and it's hopefully more convenient
// to have to only pass one thing (the engine) to any part of the API.
fn encode_padding(&self) -> bool;
}
/// The decode estimate used by an engine implementation. Users do not need to interact with this;
/// it is only for engine implementors.
///
/// Implementors may store relevant data here when constructing this to avoid having to calculate
/// them again during actual decoding.
pub trait DecodeEstimate {
/// Returns a conservative (err on the side of too big) estimate of the decoded length to use
/// for pre-allocating buffers, etc.
///
/// The estimate must be no larger than the next largest complete triple of decoded bytes.
/// That is, the final quad of symbols to decode may be assumed to be complete with no padding.
fn decoded_len_estimate(&self) -> usize;
}
/// Controls how pad bytes are handled when decoding.
///
/// Each [Engine] must support at least the behavior indicated by
/// [`DecodePaddingMode::RequireCanonical`], and may support other modes.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DecodePaddingMode {
/// Canonical padding is allowed, but any fewer padding bytes than that is also allowed.
Indifferent,
/// Padding must be canonical (0, 1, or 2 `=` as needed to produce a 4 byte suffix).
RequireCanonical,
/// Padding must be absent -- for when you want predictable padding, without any wasted bytes.
RequireNone,
}
/// Metadata about the result of a decode operation
#[derive(PartialEq, Eq, Debug)]
pub struct DecodeMetadata {
/// Number of decoded bytes output
pub(crate) decoded_len: usize,
/// Offset of the first padding byte in the input, if any
pub(crate) padding_offset: Option<usize>,
}
impl DecodeMetadata {
pub(crate) fn new(decoded_bytes: usize, padding_index: Option<usize>) -> Self {
Self {
decoded_len: decoded_bytes,
padding_offset: padding_index,
}
}
}
+204
View File
@@ -0,0 +1,204 @@
use crate::alphabet::Symbol;
use crate::{
alphabet::Alphabet,
engine::{
general_purpose::{self, decode_table, encode_table},
Config, DecodeEstimate, DecodeMetadata, DecodePaddingMode, Engine,
},
DecodeError, DecodeSliceError,
};
use std::ops::{BitAnd, BitOr, Shl, Shr};
/// Comparatively simple implementation that can be used as something to compare against in tests
pub struct Naive {
encode_table: [u8; 64],
decode_table: [u8; 256],
pub(crate) padding: Symbol,
config: NaiveConfig,
}
impl Naive {
const ENCODE_INPUT_CHUNK_SIZE: usize = 3;
const DECODE_INPUT_CHUNK_SIZE: usize = 4;
pub const fn new(alphabet: &Alphabet, config: NaiveConfig) -> Self {
Self {
encode_table: encode_table(alphabet),
decode_table: decode_table(alphabet),
padding: alphabet.padding,
config,
}
}
fn decode_byte_into_u32(&self, offset: usize, byte: u8) -> Result<u32, DecodeError> {
let decoded = self.decode_table[byte as usize];
if decoded == general_purpose::INVALID_VALUE {
return Err(DecodeError::InvalidByte(offset, byte));
}
Ok(decoded as u32)
}
}
impl Engine for Naive {
type Config = NaiveConfig;
type DecodeEstimate = NaiveEstimate;
fn internal_encode(&self, input: &[u8], output: &mut [u8]) -> usize {
// complete chunks first
const LOW_SIX_BITS: u32 = 0x3F;
let rem = input.len() % Self::ENCODE_INPUT_CHUNK_SIZE;
// will never underflow
let complete_chunk_len = input.len() - rem;
let mut input_index = 0_usize;
let mut output_index = 0_usize;
if let Some(last_complete_chunk_index) =
complete_chunk_len.checked_sub(Self::ENCODE_INPUT_CHUNK_SIZE)
{
while input_index <= last_complete_chunk_index {
let chunk = &input[input_index..input_index + Self::ENCODE_INPUT_CHUNK_SIZE];
// populate low 24 bits from 3 bytes
let chunk_int: u32 =
(chunk[0] as u32).shl(16) | (chunk[1] as u32).shl(8) | (chunk[2] as u32);
// encode 4x 6-bit output bytes
output[output_index] = self.encode_table[chunk_int.shr(18) as usize];
output[output_index + 1] =
self.encode_table[chunk_int.shr(12_u8).bitand(LOW_SIX_BITS) as usize];
output[output_index + 2] =
self.encode_table[chunk_int.shr(6_u8).bitand(LOW_SIX_BITS) as usize];
output[output_index + 3] =
self.encode_table[chunk_int.bitand(LOW_SIX_BITS) as usize];
input_index += Self::ENCODE_INPUT_CHUNK_SIZE;
output_index += 4;
}
}
// then leftovers
if rem == 2 {
let chunk = &input[input_index..input_index + 2];
// high six bits of chunk[0]
output[output_index] = self.encode_table[chunk[0].shr(2) as usize];
// bottom 2 bits of [0], high 4 bits of [1]
output[output_index + 1] =
self.encode_table[(chunk[0].shl(4_u8).bitor(chunk[1].shr(4_u8)) as u32)
.bitand(LOW_SIX_BITS) as usize];
// bottom 4 bits of [1], with the 2 bottom bits as zero
output[output_index + 2] =
self.encode_table[(chunk[1].shl(2_u8) as u32).bitand(LOW_SIX_BITS) as usize];
output_index += 3;
} else if rem == 1 {
let byte = input[input_index];
output[output_index] = self.encode_table[byte.shr(2) as usize];
output[output_index + 1] =
self.encode_table[(byte.shl(4_u8) as u32).bitand(LOW_SIX_BITS) as usize];
output_index += 2;
}
output_index
}
fn internal_decoded_len_estimate(&self, input_len: usize) -> Self::DecodeEstimate {
NaiveEstimate::new(input_len)
}
fn internal_decode(
&self,
input: &[u8],
output: &mut [u8],
estimate: Self::DecodeEstimate,
) -> Result<DecodeMetadata, DecodeSliceError> {
let complete_nonterminal_quads_len = general_purpose::decode::complete_quads_len(
input,
estimate.rem,
output.len(),
&self.decode_table,
self.padding,
)?;
const BOTTOM_BYTE: u32 = 0xFF;
for (chunk_index, chunk) in input[..complete_nonterminal_quads_len]
.chunks_exact(4)
.enumerate()
{
let input_index = chunk_index * 4;
let output_index = chunk_index * 3;
let decoded_int: u32 = self.decode_byte_into_u32(input_index, chunk[0])?.shl(18)
| self
.decode_byte_into_u32(input_index + 1, chunk[1])?
.shl(12)
| self.decode_byte_into_u32(input_index + 2, chunk[2])?.shl(6)
| self.decode_byte_into_u32(input_index + 3, chunk[3])?;
output[output_index] = decoded_int.shr(16_u8).bitand(BOTTOM_BYTE) as u8;
output[output_index + 1] = decoded_int.shr(8_u8).bitand(BOTTOM_BYTE) as u8;
output[output_index + 2] = decoded_int.bitand(BOTTOM_BYTE) as u8;
}
general_purpose::decode_suffix::decode_suffix(
input,
complete_nonterminal_quads_len,
output,
complete_nonterminal_quads_len / 4 * 3,
&self.decode_table,
self.config.decode_allow_trailing_bits,
self.padding,
self.config.decode_padding_mode,
)
}
fn config(&self) -> &Self::Config {
&self.config
}
fn padding(&self) -> Symbol {
self.padding
}
}
pub struct NaiveEstimate {
/// remainder from dividing input by `Naive::DECODE_CHUNK_SIZE`
rem: usize,
/// Length of input that is in complete `Naive::DECODE_CHUNK_SIZE`-length chunks
complete_chunk_len: usize,
}
impl NaiveEstimate {
fn new(input_len: usize) -> Self {
let rem = input_len % Naive::DECODE_INPUT_CHUNK_SIZE;
let complete_chunk_len = input_len - rem;
Self {
rem,
complete_chunk_len,
}
}
}
impl DecodeEstimate for NaiveEstimate {
fn decoded_len_estimate(&self) -> usize {
((self.complete_chunk_len / 4) + ((self.rem > 0) as usize)) * 3
}
}
#[derive(Clone, Copy, Debug)]
pub struct NaiveConfig {
pub encode_padding: bool,
pub decode_allow_trailing_bits: bool,
pub decode_padding_mode: DecodePaddingMode,
}
impl Config for NaiveConfig {
fn encode_padding(&self) -> bool {
self.encode_padding
}
}
+807
View File
@@ -0,0 +1,807 @@
//! SIMD-accelerated engines for the standard and URL-safe alphabets.
//!
//! These are gated behind the `simd-unsafe` feature because they use `unsafe`. Three engines are
//! provided:
//!
//! - `Simd` detects the best available instruction set at runtime and falls back to the scalar
//! [`GeneralPurpose`] engine when none is available. It requires `std` for the detection.
//! - `Avx2` and `Neon` target a specific instruction set with no runtime detection, so they can
//! be used in `no_std` builds when the target is known to support the instructions.
//!
//! Only the STANDARD and URL_SAFE alphabets are accelerated (they share indices `0..=61` and differ
//! only at `62`/`63`). Each engine therefore has dedicated `standard` / `url_safe` constructors
//! rather than taking an arbitrary [`Alphabet`](crate::alphabet::Alphabet); use [`GeneralPurpose`]
//! for any other alphabet.
//!
//! The kernels follow Wojciech Mula's vectorized base64 algorithms
//! (<http://0x80.pl/notesen/2016-01-17-sse-base64-decoding.html> and the companion encoding note).
//! AVX2 uses the multiply-based bit (de)interleave; NEON, which lacks the relevant multiplies, uses
//! the shift/mask variant. Both share the same per-alphabet lookup tables, expressed as the
//! associated constants of the `SimdAlphabet` trait so the kernels can inline them.
#![allow(unsafe_code)]
use crate::alphabet::Symbol;
#[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))]
use crate::{
engine::{
general_purpose::{
decode::decode_helper, encode_helper, GeneralPurpose, GeneralPurposeConfig,
GeneralPurposeEstimate,
},
DecodeMetadata, Engine,
},
DecodeSliceError,
};
/// A base64 alphabet family the SIMD kernels can accelerate.
///
/// Carries the per-alphabet lookup tables as associated constants. Private (hence sealed);
/// implemented only by [`Standard`] and [`UrlSafe`], selected at runtime by [`SimdKind`].
#[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))]
trait SimdAlphabet {
/// pshufb encode table: maps a reduced 6-bit index to `ascii - index`.
const ENCODE_LUT: [i8; 16];
/// pshufb decode table indexed by the high nibble; added to the byte to produce its 6-bit value.
const DECODE_SHIFT_LUT: [i8; 16];
/// pshufb decode table indexed by the low nibble; bit `hi` marks `(hi, lo)` as a valid symbol.
const DECODE_MASK_LUT: [u8; 16];
/// The high-`62`/`63` symbol whose shift needs the fixup below (`+`/`-`).
const DECODE_FIXUP_CHAR: i8;
/// The shift applied to [`DECODE_FIXUP_CHAR`](Self::DECODE_FIXUP_CHAR).
const DECODE_FIXUP_SHIFT: i8;
}
/// The STANDARD alphabet family (`+`/`/` at 62/63).
#[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))]
enum Standard {}
/// The URL_SAFE alphabet family (`-`/`_` at 62/63).
#[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))]
enum UrlSafe {}
#[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))]
impl SimdAlphabet for Standard {
const ENCODE_LUT: [i8; 16] = [
65, 71, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -19, -16, 0, 0,
];
const DECODE_SHIFT_LUT: [i8; 16] = [0, 0, 19, 4, -65, -65, -71, -71, 0, 0, 0, 0, 0, 0, 0, 0];
const DECODE_MASK_LUT: [u8; 16] = [
0xA8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF0, 0x54, 0x50, 0x50, 0x50,
0x54,
];
const DECODE_FIXUP_CHAR: i8 = 0x2F;
const DECODE_FIXUP_SHIFT: i8 = 16;
}
#[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))]
impl SimdAlphabet for UrlSafe {
const ENCODE_LUT: [i8; 16] = [
65, 71, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -17, 32, 0, 0,
];
const DECODE_SHIFT_LUT: [i8; 16] = [0, 0, 17, 4, -65, -65, -71, -71, 0, 0, 0, 0, 0, 0, 0, 0];
const DECODE_MASK_LUT: [u8; 16] = [
0xA8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF0, 0x50, 0x50, 0x54, 0x50,
0x70,
];
const DECODE_FIXUP_CHAR: i8 = 0x5F;
const DECODE_FIXUP_SHIFT: i8 = -32;
}
/// Which accelerated alphabet family an engine uses. Selects the kernel monomorphization at runtime.
#[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum SimdKind {
Standard,
UrlSafe,
}
/// Minimum input length before a SIMD path is used. Below these the setup cost outweighs the gain;
/// encode needs more data than decode to break even.
#[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))]
const SIMD_MIN_INPUT_ENCODE: usize = 128;
#[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))]
const SIMD_MIN_INPUT_DECODE: usize = 64;
/// pshufb decode validity table: maps a high nibble to a single set bit. Shared by both alphabets.
#[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))]
const BITPOS_LUT: [u8; 16] = [1, 2, 4, 8, 16, 32, 64, 128, 0, 0, 0, 0, 0, 0, 0, 0];
#[cfg(target_arch = "x86_64")]
mod avx2 {
use super::{SimdAlphabet, BITPOS_LUT, SIMD_MIN_INPUT_DECODE, SIMD_MIN_INPUT_ENCODE};
use core::arch::x86_64::*;
/// Encode leading whole 24-byte input groups (24 in -> 32 out per iteration).
///
/// # Safety
///
/// The running CPU must support AVX2.
#[target_feature(enable = "avx2")]
pub(super) unsafe fn encode_bulk<A: SimdAlphabet>(
input: &[u8],
output: &mut [u8],
) -> (usize, usize) {
if input.len() < SIMD_MIN_INPUT_ENCODE {
return (0, 0);
}
let lut_data = A::ENCODE_LUT;
// SAFETY: `lut_data` is a 16-byte array; `_mm_loadu_si128` reads exactly 16 bytes from it.
let lut = _mm256_broadcastsi128_si256(_mm_loadu_si128(lut_data.as_ptr().cast()));
#[rustfmt::skip]
let shuf = _mm256_setr_epi8(
1, 0, 2, 1, 4, 3, 5, 4, 7, 6, 8, 7, 10, 9, 11, 10,
1, 0, 2, 1, 4, 3, 5, 4, 7, 6, 8, 7, 10, 9, 11, 10,
);
let mask_hi = _mm256_set1_epi32(0x0fc0_fc00_u32 as i32);
let mul_hi = _mm256_set1_epi32(0x0400_0040);
let mask_lo = _mm256_set1_epi32(0x003f_03f0);
let mul_lo = _mm256_set1_epi32(0x0100_0010);
let const51 = _mm256_set1_epi8(51);
let const25 = _mm256_set1_epi8(25);
let mut i = 0usize;
let mut o = 0usize;
// A whole 32-byte vector is read but only 24 bytes are consumed, so 32 input bytes must be
// available; the store writes 32 output bytes.
while i + 32 <= input.len() && o + 32 <= output.len() {
// SAFETY: the loop guard ensures `input[i..i+32]` is in bounds, so this reads 32 valid
// bytes; `loadu` has no alignment requirement.
let data = _mm256_loadu_si256(input.as_ptr().add(i).cast());
// TODO https://arxiv.org/abs/1704.00605 doesn't seem to require this perm step, which
// costs 3 cycles, and is slightly different in the reduce phase as well.
// Rearrange dwords so low lane = bytes[0..16], high lane = bytes[12..28].
let perm = _mm256_permutevar8x32_epi32(data, _mm256_setr_epi32(0, 1, 2, 3, 3, 4, 5, 6));
let inb = _mm256_shuffle_epi8(perm, shuf);
let t0 = _mm256_and_si256(inb, mask_hi);
let t1 = _mm256_mulhi_epu16(t0, mul_hi);
let t2 = _mm256_and_si256(inb, mask_lo);
let t3 = _mm256_mullo_epi16(t2, mul_lo);
let indices = _mm256_or_si256(t1, t3); // one 6-bit value (0..=63) per byte
let reduced = _mm256_subs_epu8(indices, const51);
let gt25 = _mm256_cmpgt_epi8(indices, const25);
let reduced = _mm256_sub_epi8(reduced, gt25);
let ascii = _mm256_add_epi8(indices, _mm256_shuffle_epi8(lut, reduced));
// SAFETY: the loop guard ensures `output[o..o+32]` is in bounds; `storeu` writes 32
// bytes with no alignment requirement.
_mm256_storeu_si256(output.as_mut_ptr().add(o).cast(), ascii);
i += 24;
o += 32;
}
(i, o)
}
/// Decode leading whole 32-byte input blocks (32 in -> 24 out per iteration).
///
/// # Safety
///
/// The running CPU must support AVX2.
#[target_feature(enable = "avx2")]
pub(super) unsafe fn decode_bulk<A: SimdAlphabet>(
input: &[u8],
quads_end: usize,
output: &mut [u8],
) -> (usize, usize) {
if quads_end < SIMD_MIN_INPUT_DECODE {
return (0, 0);
}
let shift_data = A::DECODE_SHIFT_LUT;
let mask_data = A::DECODE_MASK_LUT;
// SAFETY: each LUT is a 16-byte array read in full by `_mm_loadu_si128`.
let shift_lut = _mm256_broadcastsi128_si256(_mm_loadu_si128(shift_data.as_ptr().cast()));
let mask_lut = _mm256_broadcastsi128_si256(_mm_loadu_si128(mask_data.as_ptr().cast()));
let bitpos_lut = _mm256_broadcastsi128_si256(_mm_loadu_si128(BITPOS_LUT.as_ptr().cast()));
let low_nibble_mask = _mm256_set1_epi8(0x0f);
let fixup_char = _mm256_set1_epi8(A::DECODE_FIXUP_CHAR);
let fixup_shift = _mm256_set1_epi8(A::DECODE_FIXUP_SHIFT);
let zero = _mm256_setzero_si256();
let merge_mul1 = _mm256_set1_epi32(0x0140_0140);
let merge_mul2 = _mm256_set1_epi32(0x0001_1000);
#[rustfmt::skip]
let pack_shuf = _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 lane_compact = _mm256_setr_epi32(0, 1, 2, 4, 5, 6, 6, 6);
let mut i = 0usize;
let mut o = 0usize;
// Need 32 input bytes available to load; the store writes exactly 24 output bytes.
while i + 32 <= quads_end && o + 24 <= output.len() {
// SAFETY: `i + 32 <= quads_end <= input.len()`, so this reads 32 in-bounds bytes;
// `loadu` needs no alignment.
let data = _mm256_loadu_si256(input.as_ptr().add(i).cast());
let hi_nibbles = _mm256_and_si256(_mm256_srli_epi32(data, 4), low_nibble_mask);
let lo_nibbles = _mm256_and_si256(data, low_nibble_mask);
let m = _mm256_shuffle_epi8(mask_lut, lo_nibbles);
let bit = _mm256_shuffle_epi8(bitpos_lut, hi_nibbles);
let non_match = _mm256_cmpeq_epi8(_mm256_and_si256(m, bit), zero);
if _mm256_movemask_epi8(non_match) != 0 {
// Invalid byte in this block; let the scalar decoder report the exact offset.
break;
}
let sh = _mm256_shuffle_epi8(shift_lut, hi_nibbles);
let eq_fixup = _mm256_cmpeq_epi8(data, fixup_char);
let shift = _mm256_blendv_epi8(sh, fixup_shift, eq_fixup);
let values = _mm256_add_epi8(data, shift); // 6-bit value per byte
let merged = _mm256_maddubs_epi16(values, merge_mul1);
let packed = _mm256_madd_epi16(merged, merge_mul2);
let shuffled = _mm256_shuffle_epi8(packed, pack_shuf);
let compact = _mm256_permutevar8x32_epi32(shuffled, lane_compact);
// Store exactly 24 bytes (16 + 8); a wider store would clobber an oversized output.
let lo = _mm256_castsi256_si128(compact);
let hi = _mm256_extracti128_si256(compact, 1);
// SAFETY: the loop guard ensures `o + 24 <= output.len()`, so the 16-byte store at `o`
// and the 8-byte store at `o + 16` are both in bounds; neither needs alignment.
_mm_storeu_si128(output.as_mut_ptr().add(o).cast(), lo);
_mm_storel_epi64(output.as_mut_ptr().add(o + 16).cast(), hi);
i += 32;
o += 24;
}
(i, o)
}
}
#[cfg(target_arch = "aarch64")]
mod neon {
use super::{SimdAlphabet, BITPOS_LUT, SIMD_MIN_INPUT_DECODE, SIMD_MIN_INPUT_ENCODE};
use core::arch::aarch64::*;
/// Encode leading whole 12-byte input groups (12 in -> 16 out per iteration).
///
/// # Safety
///
/// The running CPU must support NEON.
#[target_feature(enable = "neon")]
pub(super) unsafe fn encode_bulk<A: SimdAlphabet>(
input: &[u8],
output: &mut [u8],
) -> (usize, usize) {
if input.len() < SIMD_MIN_INPUT_ENCODE {
return (0, 0);
}
let lut_data = A::ENCODE_LUT;
let split_bytes: [u8; 16] = [1, 0, 2, 1, 4, 3, 5, 4, 7, 6, 8, 7, 10, 9, 11, 10];
// SAFETY: `split_bytes` and `lut_data` are 16-byte arrays, each read in full by `vld1q_u8`.
let split_shuf = vld1q_u8(split_bytes.as_ptr());
let translate = vld1q_u8(lut_data.as_ptr().cast());
// note the in-memory LE byte order will affect how these match the shuffled data bytes
let m1 = vdupq_n_u32(0x0000_fc00);
let m2 = vdupq_n_u32(0x0000_03f0);
let m3 = vdupq_n_u32(0x0fc0_0000);
let m4 = vdupq_n_u32(0x003f_0000);
let c51 = vdupq_n_u8(51);
let c25 = vdupq_n_s8(25);
let mut i = 0usize;
let mut o = 0usize;
// Reads a full 16-byte vector but consumes only 12 bytes, so 16 must be readable; writes
// exactly 16 output bytes.
while i + 16 <= input.len() && o + 16 <= output.len() {
// SAFETY: the loop guard ensures `input[i..i+16]` is in bounds, so this reads 16 valid
// bytes.
let data = vld1q_u8(input.as_ptr().add(i));
let x0 = vreinterpretq_u32_u8(vqtbl1q_u8(data, split_shuf));
// data now is 4 32-bit words in x0, each with the 3 bytes to encode in that word:
// 1 0 2 1
// 4 3 5 4
// 7 6 8 7
// a 9 b a
// select bits in chunks of 6 into their own bytes, treating the input as a bit sequence
// select the left 6 bits of [0, 3, 6, 9] (in byte 1 of the words) and shift until the
// 6 bits are the low 6 bits of byte 0, then cast to be in 2 byte words
let x1 = vshrq_n_u16::<10>(vreinterpretq_u16_u32(vandq_u32(x0, m1)));
// right 2 bits of [0 3 6 9], left 4 bits of [1 4 7 a], shifted to low bits
let x2 = vshlq_n_u16::<4>(vreinterpretq_u16_u32(vandq_u32(x0, m2)));
// right 4 bits of [1 4 7 a], left 2 bits of [2 5 8 b]
let x3 = vshrq_n_u16::<6>(vreinterpretq_u16_u32(vandq_u32(x0, m3)));
// right 6 bits of [2 5 8 b]
let x4 = vshlq_n_u16::<8>(vreinterpretq_u16_u32(vandq_u32(x0, m4)));
let indices = vreinterpretq_u8_u16(vorrq_u16(vorrq_u16(x1, x2), vorrq_u16(x3, x4)));
// reduce the 6-bit index to a translate-LUT index, then add the offset to get ascii
let reduced = vqsubq_u8(indices, c51);
let gt25 = vcgtq_s8(vreinterpretq_s8_u8(indices), c25);
let reduced = vsubq_u8(reduced, gt25); // subtracting 0xFF adds 1 where index > 25
let ascii = vaddq_u8(indices, vqtbl1q_u8(translate, reduced));
// SAFETY: the loop guard ensures `output[o..o+16]` is in bounds, so this writes 16 bytes
// in bounds.
vst1q_u8(output.as_mut_ptr().add(o), ascii);
i += 12;
o += 16;
}
(i, o)
}
/// Decode leading whole 16-byte input blocks (16 in -> 12 out per iteration).
///
/// # Safety
///
/// The running CPU must support NEON.
#[target_feature(enable = "neon")]
pub(super) unsafe fn decode_bulk<A: SimdAlphabet>(
input: &[u8],
quads_end: usize,
output: &mut [u8],
) -> (usize, usize) {
if quads_end < SIMD_MIN_INPUT_DECODE {
return (0, 0);
}
// SAFETY: each LUT is a 16-byte array read in full by `vld1q_u8`.
let shift_lut = vld1q_u8(A::DECODE_SHIFT_LUT.as_ptr().cast());
let mask_lut = vld1q_u8(A::DECODE_MASK_LUT.as_ptr());
let bitpos_lut = vld1q_u8(BITPOS_LUT.as_ptr());
let low_nibble_mask = vdupq_n_u8(0x0f);
let fixup_char_v = vdupq_n_u8(A::DECODE_FIXUP_CHAR as u8);
let fixup_shift_v = vdupq_n_u8(A::DECODE_FIXUP_SHIFT as u8);
let zero = vdupq_n_u8(0);
let mm1 = vdupq_n_u32(0x003f_003f);
let mm2 = vdupq_n_u32(0x3f00_3f00);
let out_mask = vdupq_n_u32(0x00ff_ffff);
let pack_bytes: [u8; 16] = [
2, 1, 0, 6, 5, 4, 10, 9, 8, 14, 13, 12, 0x80, 0x80, 0x80, 0x80,
];
// SAFETY: `pack_bytes` is a 16-byte array read in full by `vld1q_u8`.
let pack_shuf = vld1q_u8(pack_bytes.as_ptr());
let mut i = 0usize;
let mut o = 0usize;
// Need 16 input bytes to load; writes exactly 12 output bytes.
while i + 16 <= quads_end && o + 12 <= output.len() {
// SAFETY: `i + 16 <= quads_end <= input.len()`, so this reads 16 in-bounds bytes.
let data = vld1q_u8(input.as_ptr().add(i));
let hi = vshrq_n_u8::<4>(data);
let lo = vandq_u8(data, low_nibble_mask);
let m = vqtbl1q_u8(mask_lut, lo);
let bit = vqtbl1q_u8(bitpos_lut, hi);
let non_match = vceqq_u8(vandq_u8(m, bit), zero);
if vmaxvq_u8(non_match) != 0 {
// Invalid byte in this block; let the scalar decoder report the exact offset.
break;
}
let sh = vqtbl1q_u8(shift_lut, hi);
let eq_fixup = vceqq_u8(data, fixup_char_v);
let shift = vbslq_u8(eq_fixup, fixup_shift_v, sh);
let values = vaddq_u8(data, shift); // {00aaaaaa|00bbbbbb|00cccccc|00dddddd} x4
// merge 4x6 bits -> 3 bytes per quad via shift/mask (no multiplies on NEON)
let v = vreinterpretq_u32_u8(values);
let x1 = vandq_u32(v, mm1); // {00aaaaaa|00000000|00cccccc|00000000}
let x2 = vandq_u32(v, mm2); // {00000000|00bbbbbb|00000000|00dddddd}
let x3 = vorrq_u32(vshlq_n_u32::<18>(x1), vshrq_n_u32::<10>(x1));
let x4 = vorrq_u32(vshlq_n_u32::<4>(x2), vshrq_n_u32::<24>(x2));
let merged = vandq_u32(vorrq_u32(x3, x4), out_mask);
let packed = vqtbl1q_u8(vreinterpretq_u8_u32(merged), pack_shuf); // 12 bytes in [0..12)
// Store exactly 12 bytes (8 + 4); a wider store would clobber an oversized output.
// SAFETY: the loop guard ensures `o + 12 <= output.len()`, so the 8-byte store at `o`
// and the 4-byte store at `o + 8` are both in bounds.
vst1_u8(output.as_mut_ptr().add(o), vget_low_u8(packed));
// Can't use vst1q_lane_u32 to directly write the last lane as it requires 4-byte
// alignment, which we don't have.
// Could also shift words and then use vst1_u8 again, but this way is more direct and
// doesn't double-write the middle word.
let tail = vgetq_lane_u32::<2>(vreinterpretq_u32_u8(packed));
core::ptr::write_unaligned(output.as_mut_ptr().add(o + 8).cast::<u32>(), tail);
i += 16;
o += 12;
}
(i, o)
}
}
/// Dispatch the AVX2 encode kernel to the right alphabet monomorphization.
///
/// # Safety
///
/// The running CPU must support AVX2 (the requirement is forwarded to [`avx2::encode_bulk`]).
#[cfg(target_arch = "x86_64")]
#[inline]
unsafe fn avx2_encode(kind: SimdKind, input: &[u8], output: &mut [u8]) -> (usize, usize) {
match kind {
// SAFETY: this function's contract guarantees AVX2, which is all the kernel requires.
SimdKind::Standard => avx2::encode_bulk::<Standard>(input, output),
SimdKind::UrlSafe => avx2::encode_bulk::<UrlSafe>(input, output),
}
}
/// Dispatch the AVX2 decode kernel to the right alphabet monomorphization.
///
/// # Safety
///
/// The running CPU must support AVX2 (the requirement is forwarded to [`avx2::decode_bulk`]).
#[cfg(target_arch = "x86_64")]
#[inline]
unsafe fn avx2_decode(
kind: SimdKind,
input: &[u8],
quads_end: usize,
output: &mut [u8],
) -> (usize, usize) {
match kind {
// SAFETY: this function's contract guarantees AVX2, which is all the kernel requires.
SimdKind::Standard => avx2::decode_bulk::<Standard>(input, quads_end, output),
SimdKind::UrlSafe => avx2::decode_bulk::<UrlSafe>(input, quads_end, output),
}
}
/// Dispatch the NEON encode kernel to the right alphabet monomorphization.
///
/// # Safety
///
/// The running CPU must support NEON.
#[cfg(target_arch = "aarch64")]
#[inline]
unsafe fn neon_encode(kind: SimdKind, input: &[u8], output: &mut [u8]) -> (usize, usize) {
match kind {
// SAFETY: this function's contract guarantees NEON, which is all the kernel requires.
SimdKind::Standard => neon::encode_bulk::<Standard>(input, output),
SimdKind::UrlSafe => neon::encode_bulk::<UrlSafe>(input, output),
}
}
/// Dispatch the NEON decode kernel to the right alphabet monomorphization.
///
/// # Safety
///
/// The running CPU must support NEON.
#[cfg(target_arch = "aarch64")]
#[inline]
unsafe fn neon_decode(
kind: SimdKind,
input: &[u8],
quads_end: usize,
output: &mut [u8],
) -> (usize, usize) {
match kind {
// SAFETY: this function's contract guarantees NEON, which is all the kernel requires.
SimdKind::Standard => neon::decode_bulk::<Standard>(input, quads_end, output),
SimdKind::UrlSafe => neon::decode_bulk::<UrlSafe>(input, quads_end, output),
}
}
/// Which instruction set an engine dispatches to.
#[cfg(all(feature = "std", any(target_arch = "x86_64", target_arch = "aarch64")))]
#[derive(Clone, Copy, Debug)]
enum Backend {
Scalar,
#[cfg(target_arch = "x86_64")]
Avx2,
#[cfg(target_arch = "aarch64")]
Neon,
}
/// A base64 engine that uses the best SIMD instruction set detected at runtime, falling back to the
/// scalar [`GeneralPurpose`] engine.
///
/// Requires the `std` feature (for runtime CPU-feature detection) and an `x86_64` or `aarch64`
/// target. On other targets, use [`GeneralPurpose`] directly. Only the STANDARD and URL_SAFE
/// alphabets are accelerated, so it is constructed with [`Simd::standard`] / [`Simd::url_safe`].
#[cfg(all(feature = "std", any(target_arch = "x86_64", target_arch = "aarch64")))]
#[derive(Debug, Clone)]
pub struct Simd {
inner: GeneralPurpose,
kind: SimdKind,
backend: Backend,
}
#[cfg(all(feature = "std", any(target_arch = "x86_64", target_arch = "aarch64")))]
impl Simd {
/// Create a `Simd` engine for the STANDARD alphabet, detecting the instruction set once.
#[must_use]
pub fn standard(config: GeneralPurposeConfig) -> Self {
Self::new(SimdKind::Standard, &crate::alphabet::STANDARD, config)
}
/// Create a `Simd` engine for the URL_SAFE alphabet, detecting the instruction set once.
#[must_use]
pub fn url_safe(config: GeneralPurposeConfig) -> Self {
Self::new(SimdKind::UrlSafe, &crate::alphabet::URL_SAFE, config)
}
fn new(
kind: SimdKind,
alphabet: &crate::alphabet::Alphabet,
config: GeneralPurposeConfig,
) -> Self {
#[cfg(target_arch = "x86_64")]
let backend = if std::is_x86_feature_detected!("avx2") {
Backend::Avx2
} else {
Backend::Scalar
};
#[cfg(target_arch = "aarch64")]
let backend = if std::arch::is_aarch64_feature_detected!("neon") {
Backend::Neon
} else {
Backend::Scalar
};
Self {
inner: GeneralPurpose::new(alphabet, config),
kind,
backend,
}
}
}
#[cfg(all(feature = "std", any(target_arch = "x86_64", target_arch = "aarch64")))]
impl Engine for Simd {
type Config = GeneralPurposeConfig;
type DecodeEstimate = GeneralPurposeEstimate;
fn internal_encode(&self, input: &[u8], output: &mut [u8]) -> usize {
let kind = self.kind;
match self.backend {
Backend::Scalar => self.inner.internal_encode(input, output),
#[cfg(target_arch = "x86_64")]
Backend::Avx2 => encode_helper(self.inner.encode_table(), input, output, |i, o| {
// SAFETY: the Avx2 backend is only selected when AVX2 was detected.
unsafe { avx2_encode(kind, i, o) }
}),
#[cfg(target_arch = "aarch64")]
Backend::Neon => encode_helper(self.inner.encode_table(), input, output, |i, o| {
// SAFETY: the Neon backend is only selected when NEON was detected.
unsafe { neon_encode(kind, i, o) }
}),
}
}
fn internal_decoded_len_estimate(&self, input_len: usize) -> Self::DecodeEstimate {
self.inner.internal_decoded_len_estimate(input_len)
}
fn internal_decode(
&self,
input: &[u8],
output: &mut [u8],
estimate: Self::DecodeEstimate,
) -> Result<DecodeMetadata, DecodeSliceError> {
let kind = self.kind;
match self.backend {
Backend::Scalar => self.inner.internal_decode(input, output, estimate),
#[cfg(target_arch = "x86_64")]
Backend::Avx2 => decode_helper(
input,
&estimate,
output,
self.inner.decode_table(),
self.inner.config().decode_allow_trailing_bits(),
self.inner.padding(),
self.inner.config().decode_padding_mode(),
// SAFETY: the Avx2 backend is only selected when AVX2 was detected.
|i, end, o| unsafe { avx2_decode(kind, i, end, o) },
),
#[cfg(target_arch = "aarch64")]
Backend::Neon => decode_helper(
input,
&estimate,
output,
self.inner.decode_table(),
self.inner.config().decode_allow_trailing_bits(),
self.inner.padding(),
self.inner.config().decode_padding_mode(),
// SAFETY: the Neon backend is only selected when NEON was detected.
|i, end, o| unsafe { neon_decode(kind, i, end, o) },
),
}
}
fn config(&self) -> &Self::Config {
self.inner.config()
}
fn padding(&self) -> Symbol {
self.inner.padding()
}
}
/// A base64 engine that unconditionally uses AVX2, without runtime detection.
///
/// This works in `no_std` builds. Because it does not check for AVX2 support, it must only be used
/// on a CPU that has it. Only the STANDARD and URL_SAFE alphabets are accelerated, so it is
/// constructed with the [`Avx2::standard`] / [`Avx2::url_safe`] (checked) or
/// [`Avx2::standard_unchecked`] / [`Avx2::url_safe_unchecked`] constructors.
#[cfg(target_arch = "x86_64")]
#[derive(Debug, Clone)]
pub struct Avx2 {
inner: GeneralPurpose,
kind: SimdKind,
}
#[cfg(target_arch = "x86_64")]
impl Avx2 {
/// Create an `Avx2` engine for the STANDARD alphabet if the running CPU supports AVX2, else
/// `None`.
///
/// Requires the `std` feature for the detection; in `no_std` use [`Avx2::standard_unchecked`].
#[cfg(feature = "std")]
#[must_use]
pub fn standard(config: GeneralPurposeConfig) -> Option<Self> {
if std::is_x86_feature_detected!("avx2") {
// SAFETY: AVX2 support was just verified.
Some(unsafe { Self::standard_unchecked(config) })
} else {
None
}
}
/// Create an `Avx2` engine for the URL_SAFE alphabet if the running CPU supports AVX2, else
/// `None`.
///
/// Requires the `std` feature for the detection; in `no_std` use [`Avx2::url_safe_unchecked`].
#[cfg(feature = "std")]
#[must_use]
pub fn url_safe(config: GeneralPurposeConfig) -> Option<Self> {
if std::is_x86_feature_detected!("avx2") {
// SAFETY: AVX2 support was just verified.
Some(unsafe { Self::url_safe_unchecked(config) })
} else {
None
}
}
/// Create an `Avx2` engine for the STANDARD alphabet without checking for AVX2 support.
///
/// # Safety
///
/// The CPU that will run encode/decode must support AVX2. Using the engine on a CPU without
/// AVX2 is undefined behavior.
#[must_use]
pub const unsafe fn standard_unchecked(config: GeneralPurposeConfig) -> Self {
Self {
inner: GeneralPurpose::new(&crate::alphabet::STANDARD, config),
kind: SimdKind::Standard,
}
}
/// Create an `Avx2` engine for the URL_SAFE alphabet without checking for AVX2 support.
///
/// # Safety
///
/// The CPU that will run encode/decode must support AVX2. Using the engine on a CPU without
/// AVX2 is undefined behavior.
#[must_use]
pub const unsafe fn url_safe_unchecked(config: GeneralPurposeConfig) -> Self {
Self {
inner: GeneralPurpose::new(&crate::alphabet::URL_SAFE, config),
kind: SimdKind::UrlSafe,
}
}
}
#[cfg(target_arch = "x86_64")]
impl Engine for Avx2 {
type Config = GeneralPurposeConfig;
type DecodeEstimate = GeneralPurposeEstimate;
fn internal_encode(&self, input: &[u8], output: &mut [u8]) -> usize {
let kind = self.kind;
encode_helper(self.inner.encode_table(), input, output, |i, o| {
// SAFETY: constructing this engine asserts AVX2 support.
unsafe { avx2_encode(kind, i, o) }
})
}
fn internal_decoded_len_estimate(&self, input_len: usize) -> Self::DecodeEstimate {
self.inner.internal_decoded_len_estimate(input_len)
}
fn internal_decode(
&self,
input: &[u8],
output: &mut [u8],
estimate: Self::DecodeEstimate,
) -> Result<DecodeMetadata, DecodeSliceError> {
let kind = self.kind;
decode_helper(
input,
&estimate,
output,
self.inner.decode_table(),
self.inner.config().decode_allow_trailing_bits(),
self.inner.padding(),
self.inner.config().decode_padding_mode(),
// SAFETY: constructing this engine asserts AVX2 support.
|i, end, o| unsafe { avx2_decode(kind, i, end, o) },
)
}
fn config(&self) -> &Self::Config {
self.inner.config()
}
fn padding(&self) -> Symbol {
self.inner.padding()
}
}
/// A base64 engine that unconditionally uses NEON, without runtime detection.
///
/// This engine is available on aarch64 targets compiled with NEON support and works in `no_std`.
#[cfg(target_arch = "aarch64")]
#[derive(Debug, Clone)]
pub struct Neon {
inner: GeneralPurpose,
kind: SimdKind,
}
#[cfg(target_arch = "aarch64")]
impl Neon {
/// Create a `Neon` engine for the STANDARD alphabet on a target compiled with NEON support.
#[must_use]
pub const fn standard(config: GeneralPurposeConfig) -> Self {
Self {
inner: GeneralPurpose::new(&crate::alphabet::STANDARD, config),
kind: SimdKind::Standard,
}
}
/// Create a `Neon` engine for the URL_SAFE alphabet on a target compiled with NEON support.
#[must_use]
pub const fn url_safe(config: GeneralPurposeConfig) -> Self {
Self {
inner: GeneralPurpose::new(&crate::alphabet::URL_SAFE, config),
kind: SimdKind::UrlSafe,
}
}
}
#[cfg(target_arch = "aarch64")]
impl Engine for Neon {
type Config = GeneralPurposeConfig;
type DecodeEstimate = GeneralPurposeEstimate;
fn internal_encode(&self, input: &[u8], output: &mut [u8]) -> usize {
let kind = self.kind;
encode_helper(self.inner.encode_table(), input, output, |i, o| {
// SAFETY: this module is only compiled for targets with NEON enabled.
unsafe { neon_encode(kind, i, o) }
})
}
fn internal_decoded_len_estimate(&self, input_len: usize) -> Self::DecodeEstimate {
self.inner.internal_decoded_len_estimate(input_len)
}
fn internal_decode(
&self,
input: &[u8],
output: &mut [u8],
estimate: Self::DecodeEstimate,
) -> Result<DecodeMetadata, DecodeSliceError> {
let kind = self.kind;
decode_helper(
input,
&estimate,
output,
self.inner.decode_table(),
self.inner.config().decode_allow_trailing_bits(),
self.inner.padding(),
self.inner.config().decode_padding_mode(),
// SAFETY: this module is only compiled for targets with NEON enabled.
|i, end, o| unsafe { neon_decode(kind, i, end, o) },
)
}
fn config(&self) -> &Self::Config {
self.inner.config()
}
fn padding(&self) -> Symbol {
self.inner.padding()
}
}
+2182
View File
File diff suppressed because it is too large Load Diff