pub struct TokenBucket { /* private fields */ }Expand description
Token bucket algorithm implementation for bandwidth limiting.
This implementation uses atomic operations for thread safety and provides async token acquisition with proper rate limiting.
The adaptive version can dynamically adjust the refill rate based on network conditions and congestion control algorithms.
Implementations§
Source§impl TokenBucket
impl TokenBucket
Sourcepub fn new(capacity: u64, refill_rate: u64) -> Self
pub fn new(capacity: u64, refill_rate: u64) -> Self
Create a new TokenBucket with the specified capacity and refill rate.
§Arguments
capacity- Maximum number of tokens the bucket can hold (in bytes)refill_rate- Rate at which tokens are refilled (in bytes per second)
Sourcepub fn new_adaptive(
capacity: u64,
refill_rate: u64,
config: AdaptiveConfig,
) -> Self
pub fn new_adaptive( capacity: u64, refill_rate: u64, config: AdaptiveConfig, ) -> Self
Create a new adaptive TokenBucket with custom configuration.
§Arguments
capacity- Maximum number of tokens the bucket can hold (in bytes)refill_rate- Initial rate at which tokens are refilled (in bytes per second)config- Adaptive configuration for rate adjustments
Sourcepub async fn acquire(&self, bytes: usize)
pub async fn acquire(&self, bytes: usize)
Acquire the specified number of tokens, waiting if necessary.
This method will block until enough tokens are available.
§Arguments
bytes- Number of tokens (bytes) to acquire
Sourcepub fn try_acquire(&self, bytes: usize) -> bool
pub fn try_acquire(&self, bytes: usize) -> bool
Try to acquire tokens without waiting.
Returns true if tokens were acquired, false otherwise.
§Arguments
bytes- Number of tokens (bytes) to acquire
Sourcepub fn available_tokens(&self) -> u64
pub fn available_tokens(&self) -> u64
Get the current number of tokens in the bucket.
Sourcepub fn current_rate(&self) -> u64
pub fn current_rate(&self) -> u64
Get the current refill rate.
Sourcepub fn check_and_adjust_rate(&self)
pub fn check_and_adjust_rate(&self)
Check network conditions and adjust the refill rate accordingly.
Sourcepub fn get_metrics(&self) -> &RateMetrics
pub fn get_metrics(&self) -> &RateMetrics
Get current metrics for monitoring.