pub struct RateLimiter { /* private fields */ }Expand description
Token-bucket rate limiter.
Refills at rate_pps tokens per second. Each consume() call
blocks until a token is available, providing smooth rate control.
Internal scaling: we represent both the bucket and the refill in
units of 1 token = SCALE. Since refill comes in tokens-per-μs
(= rate_pps / 1_000_000), we pick SCALE = 1_000_000 so the
per-μs refill in scaled units equals rate_pps exactly — no
truncation for rates below 1000 pps, no 1000× overshoot for
rates at or above 1000 pps. Earlier scaling used SCALE = 1000
and stored rate_pps in refill_per_us_x1000 directly, which
was 1000× too fast at every rate ≥ 1000 pps.
Implementations§
Source§impl RateLimiter
impl RateLimiter
Sourcepub fn new(rate_pps: u64, burst: u64) -> Self
pub fn new(rate_pps: u64, burst: u64) -> Self
Create a new rate limiter.
rate_pps: target packets per second (0 = unlimited)burst: maximum burst size in packets
Sourcepub fn try_consume(&mut self) -> bool
pub fn try_consume(&mut self) -> bool
Try to consume one token. Returns true if the token was available.
Does NOT block.
Sourcepub fn try_consume_batch(&mut self, n: u64) -> u64
pub fn try_consume_batch(&mut self, n: u64) -> u64
Try to consume n tokens. Returns the number actually consumed.
Sourcepub fn consume_blocking(&mut self)
pub fn consume_blocking(&mut self)
Block until a token is available, then consume it.
Uses spin-wait for sub-microsecond precision when the wait is short,
and thread::yield_now for longer waits.
Sourcepub fn is_unlimited(&self) -> bool
pub fn is_unlimited(&self) -> bool
Whether this limiter is unlimited.
Sourcepub fn set_rate_pps(&mut self, rate_pps: u64)
pub fn set_rate_pps(&mut self, rate_pps: u64)
Re-target the rate at runtime. Used by AdaptiveLoop to react
to TX drops / ICMP-unreachable bursts without rebuilding the
limiter (which would lose the bucket fill state and stutter).