Struct tokenbucket::TokenBucket
source · pub struct TokenBucket { /* private fields */ }
Expand description
Represents a thread-safe token bucket object.
Implementations§
source§impl TokenBucket
impl TokenBucket
sourcepub fn new(r: f64, b: f64) -> TokenBucket
pub fn new(r: f64, b: f64) -> TokenBucket
Returns a new TokenBucket object.
§Arguments
-
r
- The number of tokens that should be added to the bucket every second. This can also be described as the maximum rate per second that the bucket can sustain before rate limiting. -
b
- The “burst” value for the bucket. This is the maximum number of tokens that can be consumed at one time when the bucket is full. It can also be desribed as the maximum volume of the bucket.
§Example
let mut tb = TokenBucket::new(5.0, 100.0);
sourcepub fn acquire(&mut self, count: f64) -> TokenAcquisitionResult
pub fn acquire(&mut self, count: f64) -> TokenAcquisitionResult
Attempts to acquire count
tokens from the bucket.
Returns a TokenAcquisitionResult.
Only one acquisition call can be performed per thread at any given time. Thread safety is maintained by an internal mutex.
Every time the acquire() function is called:
self.r
tokens will be added for every second that has elapsed since the last invocation of acquire().count
tokens will be removed from the bucket.- The tokens will never exceed the maximum burst value
configured in
self.b
, nor will it be less than 0.
ⓘ
self.tokens = min { b, max { 0, tokens + rS - count } }
§Arguments
count
- The number of tokens to attempt to acquire.
§Example
let mut token_bucket = TokenBucket::new(5.0, 100.0);
match token_bucket.acquire(1.0) {
Ok(rate) => println!("acquired: rate = {}", rate),
Err(rate) => println!("rate limited: rate = {}", rate),
};
Auto Trait Implementations§
impl Freeze for TokenBucket
impl RefUnwindSafe for TokenBucket
impl Send for TokenBucket
impl Sync for TokenBucket
impl Unpin 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