[−][src]Struct throttle::Throttle
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
impl Sync for Throttle
impl Unpin for Throttle
impl Send for Throttle
impl UnwindSafe for Throttle
impl RefUnwindSafe for Throttle
Blanket Implementations
impl<T, U> Into<U> for T where
U: From<T>,
[src]
U: From<T>,
impl<T> From<T> for T
[src]
impl<T, U> TryFrom<U> for T where
U: Into<T>,
[src]
U: Into<T>,
type Error = Infallible
The type returned in the event of a conversion error.
fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
[src]
impl<T, U> TryInto<U> for T where
U: TryFrom<T>,
[src]
U: TryFrom<T>,
type Error = <U as TryFrom<T>>::Error
The type returned in the event of a conversion error.
fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>
[src]
impl<T> Borrow<T> for T where
T: ?Sized,
[src]
T: ?Sized,
impl<T> BorrowMut<T> for T where
T: ?Sized,
[src]
T: ?Sized,
fn borrow_mut(&mut self) -> &mut T
[src]
impl<T> Any for T where
T: 'static + ?Sized,
[src]
T: 'static + ?Sized,