[][src]Struct throttle::Throttle

pub struct Throttle { /* fields omitted */ }

Throttle is a simple utility for rate-limiting operations.

use std::time::Duration;
use throttle::Throttle;

let unit = Duration::from_millis(100); // we use 100ms to have sufficient time elapse
let mut throttle = Throttle::new(unit * 4, 3);

throttle.accept().expect("The throttle is empty");
assert_eq!(throttle.size(), 1);
std::thread::sleep(unit * 2); // we sleep for 2t, still not expired

assert_eq!(throttle.size(), 1);
throttle.accept().expect("The throttle has one more space");
assert_eq!(throttle.size(), 2);
std::thread::sleep(unit); // time is now +3t

assert_eq!(throttle.size(), 2);
throttle.accept().expect("The last accept before throttle is full");
assert_eq!(throttle.size(), 3);
throttle.accept().expect_err("The throttle should be full");
assert_eq!(throttle.size(), 3);

std::thread::sleep(unit * 2); // time is now +5t, and the first accept should have expired
assert_eq!(throttle.size(), 2);
throttle.accept().expect("The first accept should have expired");
assert_eq!(throttle.size(), 3);
throttle.accept().expect_err("The second accept should not have expired yet");
assert_eq!(throttle.size(), 3);

std::thread::sleep(unit * 10); // time is now +10t, and all accepts should have expired
assert_eq!(throttle.size(), 0);

Methods

impl Throttle[src]

pub fn new(timeout: Duration, threshold: usize) -> Throttle[src]

Creates a new Throttle

pub fn size(&mut self) -> usize[src]

Returns the number of remaining items in the throttle

pub fn accept(&mut self) -> Result<(), Instant>[src]

Attempts to accept an operation and increment the throttle.

On success, Ok is returned and the counter increments.

On failure, Err is returned with an Instant indicating the time that the throttle is available again.

Auto Trait Implementations

Blanket Implementations

impl<T, U> Into<U> for T where
    U: From<T>, 
[src]

impl<T> From<T> for T[src]

impl<T, U> TryFrom<U> for T where
    U: Into<T>, 
[src]

type Error = Infallible

The type returned in the event of a conversion error.

impl<T, U> TryInto<U> for T where
    U: TryFrom<T>, 
[src]

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

The type returned in the event of a conversion error.

impl<T> Borrow<T> for T where
    T: ?Sized
[src]

impl<T> BorrowMut<T> for T where
    T: ?Sized
[src]

impl<T> Any for T where
    T: 'static + ?Sized
[src]