token-bucket 11.2.0

Zero-dependency, lock-free atomic GCRA, Fixed-Window, Token-Bucket, and 64-way sharded bounded keyed rate-limiting engine.
Documentation
use super::*;

/// Construction and branchless quotient evaluation for `FastDivU64`.
impl FastDivU64 {
    /// Precomputes Granlund-Montgomery reciprocal parameters for any positive divisor.
    ///
    /// # Arguments
    ///
    /// - `u64` - Positive divisor (`0` is clamped to `1`).
    ///
    /// # Returns
    ///
    /// - `Self` - Precomputed exact divider.
    #[inline(always)]
    pub(crate) const fn new(divisor: u64) -> Self {
        let d: u64 = if divisor == 0 { 1 } else { divisor };
        if d == 1 {
            return Self {
                mul: 0,
                sh1: 0,
                sh2: 0,
            };
        }
        let l: u32 = 64 - (d - 1).leading_zeros();
        let sh1: u32 = 1;
        let sh2: u32 = l - 1;
        let num: u128 = (1u128 << 64) * ((1u128 << l) - (d as u128));
        let mul: u64 = ((num / (d as u128)) as u64) + 1;
        Self { mul, sh1, sh2 }
    }

    /// Returns the reciprocal multiplier.
    ///
    /// # Returns
    ///
    /// - `u64` - Magic multiplier.
    #[inline(always)]
    pub(crate) fn get_mul(&self) -> u64 {
        self.mul
    }

    /// Returns the first right shift count.
    ///
    /// # Returns
    ///
    /// - `u32` - First shift count.
    #[inline(always)]
    pub(crate) fn get_sh1(&self) -> u32 {
        self.sh1
    }

    /// Returns the final right shift count.
    ///
    /// # Returns
    ///
    /// - `u32` - Final shift count.
    #[inline(always)]
    pub(crate) fn get_sh2(&self) -> u32 {
        self.sh2
    }

    /// Computes exact `n / divisor` without hardware integer division.
    ///
    /// # Arguments
    ///
    /// - `u64` - Unsigned dividend.
    ///
    /// # Returns
    ///
    /// - `u64` - Exact unsigned quotient.
    #[inline(always)]
    pub(crate) fn div(&self, n: u64) -> u64 {
        let t1: u64 = (((self.get_mul() as u128).wrapping_mul(n as u128)) >> 64) as u64;
        (((n.wrapping_sub(t1)) >> self.get_sh1()).wrapping_add(t1)) >> self.get_sh2()
    }
}

/// Core hashing primitives for `FastHasher`.
impl FastHasher {
    /// Creates a new `FastHasher` initialized with `seed`.
    ///
    /// # Arguments
    ///
    /// - `u64` - Initial 64-bit seed.
    #[inline(always)]
    pub(crate) fn new(seed: u64) -> Self {
        Self { state: seed }
    }

    /// Returns the current rolling hash accumulator value.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The hasher instance.
    ///
    /// # Returns
    ///
    /// - `u64` - Current accumulator state.
    #[inline(always)]
    pub(crate) fn get_state(&self) -> u64 {
        self.state
    }

    /// Updates the rolling hash accumulator state.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The hasher instance.
    /// - `u64` - New accumulator state.
    #[inline(always)]
    pub(crate) fn set_state(&mut self, value: u64) {
        self.state = value;
    }

    /// Applies a SplitMix64 avalanche finalizer to produce uniform 64-bit hash dispersion.
    ///
    /// # Arguments
    ///
    /// - `u64` - Input accumulator value.
    ///
    /// # Returns
    ///
    /// - `u64` - Fully avalanched 64-bit hash.
    #[inline(always)]
    pub(crate) fn avalanche(mut x: u64) -> u64 {
        x ^= x >> AVALANCHE_SHIFT_1;
        x = x.wrapping_mul(MIX_PRIME_B);
        x ^= x >> AVALANCHE_SHIFT_2;
        x = x.wrapping_mul(MIX_PRIME_C);
        x ^ (x >> AVALANCHE_SHIFT_3)
    }
}

/// Internal helper methods on `u64` avoided by using direct associated helper on `FastHasher`.
impl FastBuildHasher {
    /// Creates a new `FastBuildHasher` with an explicit 64-bit seed.
    ///
    /// # Arguments
    ///
    /// - `u64` - Per-instance seed value.
    #[inline(always)]
    pub(crate) fn new(seed: u64) -> Self {
        Self {
            seed: FastHasher::avalanche(seed ^ MIX_PRIME_A),
        }
    }

    /// Returns the stored 64-bit seed.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The builder instance.
    ///
    /// # Returns
    ///
    /// - `u64` - The 64-bit hash seed.
    #[inline(always)]
    pub(crate) fn get_seed(&self) -> u64 {
        self.seed
    }

    /// Computes a single-shot 64-bit hash for any `Hash` value.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The build hasher.
    /// - `&T` - Value to hash.
    ///
    /// # Returns
    ///
    /// - `u64` - Avalanched 64-bit hash value.
    #[inline(always)]
    pub(crate) fn hash_value<T>(&self, value: &T) -> u64
    where
        T: Hash + ?Sized,
    {
        self.hash_one(value)
    }
}

/// Implements `BuildHasher` for `FastBuildHasher`.
impl BuildHasher for FastBuildHasher {
    type Hasher = FastHasher;

    /// Instantiates a fresh `FastHasher` seeded from this builder.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The builder instance.
    ///
    /// # Returns
    ///
    /// - `Self::Hasher` - Newly seeded `FastHasher`.
    #[inline(always)]
    fn build_hasher(&self) -> Self::Hasher {
        FastHasher::new(self.get_seed())
    }
}

/// Implements `Hasher` for `FastHasher`.
impl Hasher for FastHasher {
    /// Finalizes and returns the avalanched 64-bit hash digest.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The hasher instance.
    ///
    /// # Returns
    ///
    /// - `u64` - Final 64-bit hash digest.
    #[inline(always)]
    fn finish(&self) -> u64 {
        Self::avalanche(self.get_state())
    }

    /// Feeds an arbitrary byte slice into the hasher in 8-byte chunks plus tail bytes.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The hasher instance.
    /// - `&[u8]` - Input byte slice.
    #[inline(always)]
    fn write(&mut self, bytes: &[u8]) {
        let len: usize = bytes.len();
        let mut state: u64 = self.get_state();
        let ptr: *const u8 = bytes.as_ptr();
        if len <= 16 {
            if len >= WORD_BYTES {
                let w0: u64 = u64::from_le(unsafe { ptr.cast::<u64>().read_unaligned() });
                state = (state.rotate_left(MIX_ROTATE_BITS) ^ w0).wrapping_mul(MIX_PRIME_A);
                if len > WORD_BYTES {
                    let w1: u64 = u64::from_le(unsafe {
                        ptr.add(len - WORD_BYTES).cast::<u64>().read_unaligned()
                    });
                    state = (state.rotate_left(MIX_ROTATE_BITS) ^ w1).wrapping_mul(MIX_PRIME_A);
                }
            } else if len >= 4 {
                let lo: u64 = u32::from_le(unsafe { ptr.cast::<u32>().read_unaligned() }) as u64;
                let hi: u64 =
                    u32::from_le(unsafe { ptr.add(len - 4).cast::<u32>().read_unaligned() }) as u64;
                let word: u64 = lo | (hi << 32);
                state = (state.rotate_left(MIX_ROTATE_BITS) ^ word).wrapping_mul(MIX_PRIME_A);
            } else if len > 0 {
                let word: u64 = (bytes[0] as u64)
                    | ((bytes[len >> 1] as u64) << 8)
                    | ((bytes[len - 1] as u64) << 16);
                state = (state.rotate_left(MIX_ROTATE_BITS) ^ word).wrapping_mul(MIX_PRIME_A);
            }
            self.set_state((state ^ (len as u64)).wrapping_mul(MIX_PRIME_B));
            return;
        }
        let mut idx: usize = 0;
        while idx + WORD_BYTES <= len {
            let word: u64 = u64::from_le(unsafe { ptr.add(idx).cast::<u64>().read_unaligned() });
            state = (state.rotate_left(MIX_ROTATE_BITS) ^ word).wrapping_mul(MIX_PRIME_A);
            idx += WORD_BYTES;
        }
        if idx < len {
            let tail_word: u64 =
                u64::from_le(unsafe { ptr.add(len - WORD_BYTES).cast::<u64>().read_unaligned() });
            state = (state.rotate_left(MIX_ROTATE_BITS) ^ tail_word).wrapping_mul(MIX_PRIME_A);
        }
        self.set_state((state ^ (len as u64)).wrapping_mul(MIX_PRIME_B));
    }

    /// Mixes a `u8` directly into the hash state.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The hasher instance.
    /// - `u8` - Byte value to hash.
    #[inline(always)]
    fn write_u8(&mut self, value: u8) {
        let mixed: u64 = (self.get_state().rotate_left(MIX_ROTATE_BITS) ^ (value as u64))
            .wrapping_mul(MIX_PRIME_A);
        self.set_state(mixed);
    }

    /// Mixes a `u16` directly into the hash state.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The hasher instance.
    /// - `u16` - 16-bit integer to hash.
    #[inline(always)]
    fn write_u16(&mut self, value: u16) {
        let mixed: u64 = (self.get_state().rotate_left(MIX_ROTATE_BITS) ^ (value as u64))
            .wrapping_mul(MIX_PRIME_A);
        self.set_state(mixed);
    }

    /// Mixes a `u32` directly into the hash state.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The hasher instance.
    /// - `u32` - 32-bit integer to hash.
    #[inline(always)]
    fn write_u32(&mut self, value: u32) {
        let mixed: u64 = (self.get_state().rotate_left(MIX_ROTATE_BITS) ^ (value as u64))
            .wrapping_mul(MIX_PRIME_A);
        self.set_state(mixed);
    }

    /// Mixes a `u64` directly into the hash state.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The hasher instance.
    /// - `u64` - 64-bit integer to hash.
    #[inline(always)]
    fn write_u64(&mut self, value: u64) {
        let mixed: u64 =
            (self.get_state().rotate_left(MIX_ROTATE_BITS) ^ value).wrapping_mul(MIX_PRIME_A);
        self.set_state(mixed);
    }

    /// Mixes a `u128` directly into the hash state as two 64-bit words.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The hasher instance.
    /// - `u128` - 128-bit integer to hash.
    #[inline(always)]
    fn write_u128(&mut self, value: u128) {
        self.write_u64(value as u64);
        self.write_u64((value >> 64) as u64);
    }

    /// Mixes a `usize` directly into the hash state.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The hasher instance.
    /// - `usize` - Pointer-sized integer to hash.
    #[inline(always)]
    fn write_usize(&mut self, value: usize) {
        self.write_u64(value as u64);
    }
}