Rust token bucket rate limiter with burst capacity
Rust
use std::time::Instant;
struct TokenBucket { capacity: f64, tokens: f64, rate: f64, last: Instant }
impl TokenBucket {
fn new(capacity: f64, rate: f64) -> Self {
Self { capacity, tokens: capacity, rate, last: Instant::now() }
}
fn try_acquire(&mut self, cost: f64) -> bool {
let now = Instant::now();
let gained = now.duration_since(self.last).as_secs_f64() * self.rate;
self.tokens = (self.tokens + gained).min(self.capacity);
self.last = now;
if self.tokens >= cost {
self.tokens -= cost;
true
} else {
false
}
}
}