1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
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
}
}