pub struct Limiter<C: Clock = StandardClock> { /* private fields */ }
Expand description

A type to control the maximum speed limit of multiple streams.

When a Limiter is cloned, the instances would share the same queue. Multiple tasks can cooperatively respect a global speed limit via clones. Cloning a Limiter is cheap (equals to cloning two Arcs).

The speed limit is imposed by awaiting consume(). The method returns a future which sleeps until rate falls below the limit.

Examples

Upload some small files atomically in parallel, while maintaining a global speed limit of 1 MiB/s.

use async_speed_limit::Limiter;
use futures_util::future::try_join_all;

let limiter = <Limiter>::new(1_048_576.0);
let processes = files
    .iter()
    .map(|file| {
        let limiter = limiter.clone();
        async move {
            limiter.consume(file.len()).await;
            upload(file).await?;
            Ok(())
        }
    });
try_join_all(processes).await?;

Implementations§

source§

impl<C: Clock> Limiter<C>

source

pub fn new(speed_limit: f64) -> Self

Creates a new speed limiter.

Use infinity to make the speed unlimited.

source

pub fn builder(speed_limit: f64) -> Builder<C>

Makes a Builder for further configurating this limiter.

Use infinity to make the speed unlimited.

source

pub fn clock(&self) -> &C

Returns the clock associated with this limiter.

source

pub fn set_speed_limit(&self, speed_limit: f64)

Dynamically changes the speed limit. The new limit applies to all clones of this instance.

Use infinity to make the speed unlimited.

This change will not affect any tasks scheduled before this call.

source

pub fn speed_limit(&self) -> f64

Returns the current speed limit.

This method returns infinity if the speed is unlimited.

source

pub fn total_bytes_consumed(&self) -> usize

Obtains the total number of bytes consumed by this limiter so far.

If more than usize::MAX bytes have been consumed, the count will wrap around.

source

pub fn reset_statistics(&self)

Resets the total number of bytes consumed to 0.

source

pub fn consume_duration(&self, byte_size: usize) -> Duration

Consumes several bytes from the speed limiter, returns the duration needed to sleep to maintain the speed limit.

source

pub fn unconsume(&self, byte_size: usize)

Reverts the consumption of the given bytes size.

source

pub fn consume(&self, byte_size: usize) -> Consume<C, ()>

Consumes several bytes from the speed limiter.

The consumption happens at the beginning, before the speed limit is applied. The returned future is fulfilled after the speed limit is satified.

source

pub fn limit<R>(self, resource: R) -> Resource<R, C>

Wraps a streaming resource with speed limiting. See documentation of Resource for details.

If you want to reuse the limiter after calling this function, clone() the limiter first.

source§

impl<C: BlockingClock> Limiter<C>

source

pub fn blocking_consume(&self, byte_size: usize)

Consumes several bytes, and sleeps the current thread to maintain the speed limit.

The consumption happens at the beginning, before the speed limit is applied. This method blocks the current thread (e.g. using std::thread::sleep() given a StandardClock), and must not be used in async context.

Prefer using this method instead of futures_executor::block_on(limiter.consume(size)).

Trait Implementations§

source§

impl<C: Clone + Clock> Clone for Limiter<C>where C::Instant: Clone,

source§

fn clone(&self) -> Limiter<C>

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl<C: Debug + Clock> Debug for Limiter<C>where C::Instant: Debug,

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl<C> RefUnwindSafe for Limiter<C>where C: RefUnwindSafe,

§

impl<C> Send for Limiter<C>where C: Send, <C as Clock>::Instant: Send,

§

impl<C> Sync for Limiter<C>where C: Sync, <C as Clock>::Instant: Send,

§

impl<C> Unpin for Limiter<C>where C: Unpin,

§

impl<C> UnwindSafe for Limiter<C>where C: UnwindSafe,

Blanket Implementations§

source§

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

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

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

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for Twhere 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 Twhere 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> ToOwned for Twhere T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T, U> TryFrom<U> for Twhere 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 Twhere 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.