use ring_vec::RingVec;
use std::time::{Duration, Instant};
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct RateLimit {
pub count: usize,
pub period: Duration,
}
impl RateLimit {
pub fn new(count: usize, period: Duration) -> Option<RateLimit> {
if count > 0 {
Some(RateLimit { count, period })
} else {
None
}
}
}
pub struct RateLimiter {
pub limit: RateLimit,
readings: RingVec<Instant>,
}
impl RateLimiter {
pub fn new(limit: RateLimit) -> RateLimiter {
RateLimiter { limit, readings: RingVec::new(limit.count) }
}
pub fn new_preallocated(limit: RateLimit) -> RateLimiter {
RateLimiter { limit, readings: RingVec::new_preallocated(limit.count) }
}
pub fn check(&mut self) -> bool { self.check_at(Instant::now()) }
pub fn check_at(&mut self, instant: Instant) -> bool {
if self.readings.push(instant).is_ok() { return true; }
let reclaimed = self.sweep(instant);
if reclaimed {
self.readings.push(instant).unwrap();
}
reclaimed
}
pub fn sweep(&mut self, instant: Instant) -> bool {
let bench = instant - self.limit.period;
let mut reclaimed = false;
while let Some(x) = self.readings.peek() {
if *x < bench {
reclaimed = true;
self.readings.pop();
} else { break; }
}
reclaimed
}
}