pub struct TokenBucket { /* private fields */ }Expand description
A sans-IO token bucket: spend units at a bounded Rate with a
configurable burst capacity.
The bucket never reads a clock: the caller provides now as
monotonic nanoseconds from any epoch, as long as it is consistent
across calls. This keeps the bucket no_std, deterministic to test
and embeddable in other sans-IO state machines.
Internally the level is stored scaled by the period (in nanoseconds), so refills are exact integer arithmetic with zero drift.
§Examples
use rama_utils::rate::{Acquire, Rate, TokenBucket};
let mut bucket = TokenBucket::from_rate(Rate::per_sec(2));
assert_eq!(bucket.try_acquire(0, 1), Acquire::Granted);
assert_eq!(bucket.try_acquire(0, 1), Acquire::Granted);
// bucket is empty: the next unit refills after half a period
assert_eq!(bucket.try_acquire(0, 1), Acquire::RetryAt(500_000_000));
assert_eq!(bucket.try_acquire(500_000_000, 1), Acquire::Granted);Implementations§
Source§impl TokenBucket
impl TokenBucket
Sourcepub fn new(rate: Rate, burst: u64) -> Self
pub fn new(rate: Rate, burst: u64) -> Self
Create a new TokenBucket with the given Rate and
burst capacity (the maximum units spendable at once).
The bucket starts full.
§Panics
Panics if burst is zero.
Sourcepub fn from_rate(rate: Rate) -> Self
pub fn from_rate(rate: Rate) -> Self
Create a new TokenBucket with a burst capacity of one
period worth of units (rate.units()): a plain smooth rate.
Sourcepub fn try_acquire(&mut self, now: u64, n: u64) -> Acquire
pub fn try_acquire(&mut self, now: u64, n: u64) -> Acquire
Try to spend n units at monotonic instant now (nanoseconds,
caller’s clock).
Acquire::Granted: the units were spent.Acquire::RetryAt: nothing was spent; retrying with the returned instant (and an otherwise untouched bucket) is guaranteed to be granted.Acquire::Never:nexceeds the burst capacity and can never be granted as a single acquisition.
n == 0 is always granted. A now earlier than a previously
provided instant is treated as no time having passed.