pub struct TokenBucket {
pub tokens: f64,
pub max_tokens: f64,
pub refill_rate: f64,
pub last_refill: Instant,
}Expand description
A token-bucket rate limiter.
Tokens refill continuously at refill_rate tokens/sec up to max_tokens.
Each try_acquire consumes one token. Thread-safe when wrapped in DashMap
(exterior mutability via get_mut).
Fields§
§tokens: f64§max_tokens: f64§refill_rate: f64§last_refill: InstantImplementations§
Source§impl TokenBucket
impl TokenBucket
Sourcepub fn new_at(max_tokens: f64, refill_rate: f64, now: Instant) -> Self
pub fn new_at(max_tokens: f64, refill_rate: f64, now: Instant) -> Self
Create a bucket with a specific start time (useful for testing).
Sourcepub fn try_acquire(&mut self) -> bool
pub fn try_acquire(&mut self) -> bool
Refill tokens based on elapsed time, then try to consume one token.
Returns true if the token was acquired, false if bucket is empty.
Sourcepub fn try_acquire_at(&mut self, now: Instant) -> bool
pub fn try_acquire_at(&mut self, now: Instant) -> bool
Same as try_acquire but accepts a timestamp (for deterministic testing).
Trait Implementations§
Source§impl Clone for TokenBucket
impl Clone for TokenBucket
Source§fn clone(&self) -> TokenBucket
fn clone(&self) -> TokenBucket
Returns a duplicate of the value. Read more
1.0.0 · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
Performs copy-assignment from
source. Read moreAuto Trait Implementations§
impl Freeze for TokenBucket
impl RefUnwindSafe for TokenBucket
impl Send for TokenBucket
impl Sync for TokenBucket
impl Unpin for TokenBucket
impl UnsafeUnpin for TokenBucket
impl UnwindSafe for TokenBucket
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more