arcium-primitives 0.4.0

Arcium primitives
Documentation
//! Utility module for rate limiting mechanisms

pub mod token_bucket;

use std::sync::{
    atomic::{AtomicU64, Ordering},
    Arc,
};

pub use token_bucket::{TokenBucket, TokenBucketConfig};

pub trait RateLimiter: Send + Sync {
    /// The numerical type used to count tokens
    type TokenType;

    /// Try to consume a specified number of tokens
    /// Returns true if successful, false if not enough tokens available
    /// (thus not consuming any tokens)
    fn try_consume(&self, tokens: Self::TokenType) -> bool;

    /// Get the number of available tokens
    fn available_tokens(&self) -> Self::TokenType;
}

impl RateLimiter for Arc<AtomicU64> {
    type TokenType = u64;

    fn try_consume(&self, tokens: u64) -> bool {
        self.fetch_update(Ordering::AcqRel, Ordering::Acquire, |current| {
            if current >= tokens {
                Some(current - tokens)
            } else {
                None
            }
        })
        .is_ok()
    }

    fn available_tokens(&self) -> u64 {
        self.load(Ordering::Acquire)
    }
}