grippo 0.2.0

Parse, match and scrub data faster and more efficiently.
Documentation
// Project:   grippo
// File:      src/kernel.rs
// Purpose:   The crate's unsafe module: SIMD class runs, and base64 and hex decoding
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! How many bytes at the start of a slice belong to a set of ASCII bytes.
//!
//! This is the one module with `unsafe`. A vector step tests 16 or 32 bytes
//! with two nibble lookups, after aho-corasick's Teddy (`members1`): AVX2 or
//! SSSE3 on x86-64, found at run time, and NEON on aarch64. A byte loop over
//! a 256-entry table takes a run's first bytes, the bytes after the last whole
//! step, and every CPU with no vector tier.
//! `benches/class_run.rs` measures one against the other by run length.
//!
//! The base64 and hex decoders' vector steps live here too, in [`base64`]
//! and [`hex`].

#[cfg(feature = "decode-base64")]
pub mod base64;
#[cfg(feature = "decode-hex")]
pub mod hex;

/// A set of ASCII bytes.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ByteClass {
    /// Whether each byte value is a member. No byte past ASCII is.
    member: [bool; 256],
    /// For each low nibble: bit `n` is set when byte `n << 4 | low` is a
    /// member.
    low: [u8; 16],
}

impl ByteClass {
    /// The set whose members are the bits of `ascii`, bit `b` for byte `b`.
    #[must_use]
    pub const fn new(ascii: u128) -> Self {
        let mut member = [false; 256];
        let mut low = [0_u8; 16];
        let mut byte = 0_usize;
        while byte < 128 {
            if ascii >> byte & 1 == 1 {
                member[byte] = true;
                low[byte & 15] |= 1 << (byte >> 4);
            }
            byte += 1;
        }
        Self { member, low }
    }

    /// Whether `byte` is a member. A byte past ASCII never is.
    #[must_use]
    pub const fn has(&self, byte: u8) -> bool {
        self.member[byte as usize]
    }

    /// Bytes at the start of `h` that are members. It stops at the first
    /// byte that isn't, a byte past ASCII included.
    ///
    /// Whole steps go by vector where `h` holds one and the CPU has a tier,
    /// and the table takes it from wherever that stopped. A run of a byte
    /// or two costs more this way than by [`Self::run_by_table`], and a run
    /// of 8 or more costs less: `benches/class_run.rs` has both.
    #[must_use]
    pub fn run(&self, h: &[u8]) -> usize {
        #[cfg(target_arch = "x86_64")]
        let at = if h.len() < x86::STEP {
            0
        } else {
            x86::whole_steps(&self.low, h)
        };
        #[cfg(all(
            target_arch = "aarch64",
            target_endian = "little",
            target_feature = "neon"
        ))]
        let at = if h.len() < neon::STEP {
            0
        } else {
            neon::run_steps(&self.low, h)
        };
        #[cfg(not(any(
            target_arch = "x86_64",
            all(
                target_arch = "aarch64",
                target_endian = "little",
                target_feature = "neon"
            )
        )))]
        let at = 0;
        at + self.run_by_table(h.get(at..).unwrap_or_default())
    }

    /// The same, a byte at a time: the quicker way for a class whose runs
    /// are a few bytes.
    #[must_use]
    pub fn run_by_table(&self, h: &[u8]) -> usize {
        h.iter().take_while(|&&b| self.has(b)).count()
    }
}

#[cfg(target_arch = "x86_64")]
mod x86 {
    use std::arch::x86_64::{
        __m128i, __m256i, _mm_and_si128, _mm_cmpeq_epi8, _mm_loadu_si128, _mm_movemask_epi8,
        _mm_set1_epi8, _mm_setzero_si128, _mm_shuffle_epi8, _mm_srli_epi16, _mm256_and_si256,
        _mm256_broadcastsi128_si256, _mm256_cmpeq_epi8, _mm256_loadu_si256, _mm256_movemask_epi8,
        _mm256_set1_epi8, _mm256_setzero_si256, _mm256_shuffle_epi8, _mm256_srli_epi16,
    };

    /// For each high nibble: its bit, and none for a byte past ASCII.
    pub(super) const HIGH: [u8; 16] = [1, 2, 4, 8, 16, 32, 64, 128, 0, 0, 0, 0, 0, 0, 0, 0];

    /// The shortest slice a vector step reads.
    pub(super) const STEP: usize = 16;

    /// How far into `h` the run goes by whole vector steps: the place of the
    /// first non-member a step saw, or the end of the last whole step. 0 on
    /// a CPU with no tier.
    #[allow(
        unsafe_code,
        reason = "a #[target_feature] function is called only after its feature is detected"
    )]
    pub(super) fn whole_steps(low: &[u8; 16], h: &[u8]) -> usize {
        if is_x86_feature_detected!("avx2") {
            // SAFETY: this CPU has AVX2, by the check on the line above.
            return unsafe { avx2(low, h) };
        }
        if is_x86_feature_detected!("ssse3") {
            // SAFETY: this CPU has SSSE3, by the check on the line above.
            return unsafe { ssse3(low, h) };
        }
        0
    }

    /// Whole steps of 32 bytes, then of 16.
    #[target_feature(enable = "avx2")]
    pub(super) fn avx2(low: &[u8; 16], h: &[u8]) -> usize {
        let wide_low = _mm256_broadcastsi128_si256(load16(low));
        let wide_high = _mm256_broadcastsi128_si256(load16(&HIGH));
        let nibble = _mm256_set1_epi8(0x0F);
        let mut at = 0;
        while let Some(step) = h.get(at..).and_then(<[u8]>::first_chunk::<32>) {
            let bytes = load32(step);
            // A shuffle reads the low four bits of each index, so the high
            // nibble is shifted down and the bits its neighbour lent masked off.
            let by_low = _mm256_shuffle_epi8(wide_low, _mm256_and_si256(bytes, nibble));
            let high_nibbles = _mm256_and_si256(_mm256_srli_epi16(bytes, 4), nibble);
            let by_high = _mm256_shuffle_epi8(wide_high, high_nibbles);
            let member = _mm256_and_si256(by_low, by_high);
            // Bit `i` is set when byte `i` of the step is not a member.
            let outside = _mm256_movemask_epi8(_mm256_cmpeq_epi8(member, _mm256_setzero_si256()))
                .cast_unsigned();
            if outside != 0 {
                return at + outside.trailing_zeros() as usize;
            }
            at += 32;
        }
        at + ssse3(low, h.get(at..).unwrap_or_default())
    }

    /// Whole steps of 16 bytes.
    #[target_feature(enable = "ssse3")]
    pub(super) fn ssse3(low: &[u8; 16], h: &[u8]) -> usize {
        let low = load16(low);
        let high = load16(&HIGH);
        let nibble = _mm_set1_epi8(0x0F);
        let mut at = 0;
        while let Some(step) = h.get(at..).and_then(<[u8]>::first_chunk::<16>) {
            let bytes = load16(step);
            let by_low = _mm_shuffle_epi8(low, _mm_and_si128(bytes, nibble));
            let high_nibbles = _mm_and_si128(_mm_srli_epi16(bytes, 4), nibble);
            let by_high = _mm_shuffle_epi8(high, high_nibbles);
            let member = _mm_and_si128(by_low, by_high);
            let outside =
                _mm_movemask_epi8(_mm_cmpeq_epi8(member, _mm_setzero_si128())).cast_unsigned();
            if outside != 0 {
                return at + outside.trailing_zeros() as usize;
            }
            at += 16;
        }
        at
    }

    #[allow(
        unsafe_code,
        reason = "an unaligned vector load has no safe form that compiles to one load"
    )]
    #[inline]
    #[target_feature(enable = "sse2")]
    pub(super) fn load16(bytes: &[u8; 16]) -> __m128i {
        // SAFETY: `bytes` is 16 readable bytes, and this load needs no
        // alignment.
        unsafe { _mm_loadu_si128(std::ptr::from_ref(bytes).cast()) }
    }

    #[allow(
        unsafe_code,
        reason = "an unaligned vector load has no safe form that compiles to one load"
    )]
    #[inline]
    #[target_feature(enable = "avx")]
    pub(super) fn load32(bytes: &[u8; 32]) -> __m256i {
        // SAFETY: `bytes` is 32 readable bytes, and this load needs no
        // alignment.
        unsafe { _mm256_loadu_si256(std::ptr::from_ref(bytes).cast()) }
    }

    /// One tier's run, by a class's low-nibble table.
    #[cfg(test)]
    pub(super) type Tier = fn(&[u8; 16], &[u8]) -> usize;

    /// Each vector tier this CPU can run, by name, for the tests.
    #[cfg(test)]
    #[allow(
        unsafe_code,
        reason = "a #[target_feature] function is called only after its feature is detected"
    )]
    pub(super) fn tiers() -> Vec<(&'static str, Tier)> {
        let mut tiers: Vec<(&'static str, Tier)> = Vec::new();
        if is_x86_feature_detected!("avx2") {
            // SAFETY: this CPU has AVX2, by the check on the line above.
            tiers.push(("avx2", |low, h| unsafe { avx2(low, h) }));
        }
        if is_x86_feature_detected!("ssse3") {
            // SAFETY: this CPU has SSSE3, by the check on the line above.
            tiers.push(("ssse3", |low, h| unsafe { ssse3(low, h) }));
        }
        tiers
    }
}

/// The same steps on aarch64, where NEON is part of the base instruction set.
#[cfg(all(
    target_arch = "aarch64",
    target_endian = "little",
    target_feature = "neon"
))]
mod neon {
    use std::arch::aarch64::{
        uint8x16_t, vandq_u8, vceqzq_u8, vdupq_n_u8, vget_lane_u64, vld1q_u8, vqtbl1q_u8,
        vreinterpret_u64_u8, vreinterpretq_u16_u8, vshrn_n_u16, vshrq_n_u8,
    };

    /// For each high nibble: its bit, and none for a byte past ASCII.
    pub(super) const HIGH: [u8; 16] = [1, 2, 4, 8, 16, 32, 64, 128, 0, 0, 0, 0, 0, 0, 0, 0];

    /// The shortest slice a vector step reads.
    pub(super) const STEP: usize = 16;

    /// [`whole_steps`], from a caller that has NEON only by this build's
    /// `cfg`.
    #[allow(
        unsafe_code,
        reason = "a #[target_feature] function is called only where its feature is compiled in"
    )]
    pub(super) fn run_steps(low: &[u8; 16], h: &[u8]) -> usize {
        // SAFETY: this module builds only with `target_feature = "neon"`, so
        // every CPU this binary runs on has NEON.
        unsafe { whole_steps(low, h) }
    }

    /// How far into `h` the run goes by whole steps of 16 bytes: the place of
    /// the first non-member a step saw, or the end of the last whole step.
    #[target_feature(enable = "neon")]
    pub(super) fn whole_steps(low: &[u8; 16], h: &[u8]) -> usize {
        let low = load16(low);
        let high = load16(&HIGH);
        let nibble = vdupq_n_u8(0x0F);
        let mut at = 0;
        while let Some(step) = h.get(at..).and_then(<[u8]>::first_chunk::<16>) {
            let bytes = load16(step);
            // A table lookup gives 0 for an index past 15, so the low nibble
            // is masked and the high one shifted down whole.
            let by_low = vqtbl1q_u8(low, vandq_u8(bytes, nibble));
            let by_high = vqtbl1q_u8(high, vshrq_n_u8::<4>(bytes));
            // 0xFF in each lane whose byte is not a member.
            let outside = vceqzq_u8(vandq_u8(by_low, by_high));
            // Four bits a lane, as memchr's aarch64 code does in place of a
            // movemask.
            let mask = vget_lane_u64::<0>(vreinterpret_u64_u8(vshrn_n_u16::<4>(
                vreinterpretq_u16_u8(outside),
            )));
            if mask != 0 {
                return at + (mask.trailing_zeros() / 4) as usize;
            }
            at += 16;
        }
        at
    }

    #[allow(
        unsafe_code,
        reason = "a vector load from a pointer has no safe form that compiles to one load"
    )]
    #[inline]
    #[target_feature(enable = "neon")]
    pub(super) fn load16(bytes: &[u8; 16]) -> uint8x16_t {
        // SAFETY: `bytes` is 16 readable bytes, and this load needs no
        // alignment.
        unsafe { vld1q_u8(bytes.as_ptr()) }
    }

    /// One tier's run, by a class's low-nibble table.
    #[cfg(test)]
    pub(super) type Tier = fn(&[u8; 16], &[u8]) -> usize;

    /// The vector tier, by name, for the tests.
    #[cfg(test)]
    pub(super) fn tiers() -> Vec<(&'static str, Tier)> {
        vec![("neon", run_steps)]
    }
}

#[cfg(test)]
mod tests;