token-bucket 11.0.0

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

/// Immutable configuration for a lock-free atomic token-bucket rate limiter.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct TokenBucketConfig {
    /// Maximum token capacity of the bucket (`1..=u32::MAX`).
    pub(crate) capacity: u64,
    /// Tokens replenished per reduced refill step (`>= 1`).
    pub(crate) step_tokens: u64,
    /// Duration of one reduced refill step in nanoseconds (`>= 1`).
    pub(crate) step_ns: u64,
    /// Precomputed reciprocal divider for `step_ns`.
    pub(crate) step_ns_div: FastDivU64,
    /// Precomputed reciprocal divider for `step_tokens`.
    pub(crate) step_tokens_div: FastDivU64,
    /// Bit width reserved for the available token counter (`1..=32`).
    pub(crate) token_bits: u32,
    /// Bitmask extracting the token counter from the packed state word.
    pub(crate) token_mask: u64,
    /// Bitmask extracting the wrapped refill step index from the packed state word.
    pub(crate) step_mask: u64,
    /// Half-ring threshold for monotonic modular step comparison.
    pub(crate) step_half: u64,
}

/// Lock-free single-`AtomicU64` token-bucket state cell packing `(last_step, tokens)`.
#[derive(Debug)]
pub struct TokenBucketCell {
    /// Packed `(last_step << token_bits) | tokens` atomic state word.
    pub(crate) packed: AtomicU64,
}

/// Lock-free atomic token-bucket rate limiter with an embedded monotonic clock.
#[derive(Debug)]
pub struct TokenBucketLimiter {
    /// Validated token-bucket configuration.
    pub(crate) config: TokenBucketConfig,
    /// Monotonic nanosecond clock anchored at limiter creation.
    pub(crate) clock: MonotonicClock,
    /// Atomic packed step and token count cell.
    pub(crate) cell: TokenBucketCell,
}