pub struct TokenBucket { /* private fields */ }
Expand description

Represents a thread-safe token bucket object.

Implementations§

source§

impl TokenBucket

source

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);
source

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:

  1. self.r tokens will be added for every second that has elapsed since the last invocation of acquire().
  2. count tokens will be removed from the bucket.
  3. 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§

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.