steel_core/player/chat/
spam_throttler.rs1#[derive(Debug, Clone, Copy)]
2pub(super) struct TickThrottler {
3 increment_step: i32,
4 threshold: i32,
5 count: i32,
6}
7
8impl TickThrottler {
9 pub(super) const fn new(increment_step: i32, threshold: i32) -> Self {
10 Self {
11 increment_step,
12 threshold,
13 count: 0,
14 }
15 }
16
17 pub(super) const fn increment(&mut self) {
18 self.count = self.count.wrapping_add(self.increment_step);
19 }
20
21 pub(super) const fn tick(&mut self) {
22 if self.count > 0 {
23 self.count -= 1;
24 }
25 }
26
27 pub(super) const fn is_under_threshold(self) -> bool {
28 self.threshold <= 0 || self.count < self.threshold
29 }
30}
31
32#[cfg(test)]
33mod tests {
34 use super::TickThrottler;
35
36 #[test]
37 fn threshold_at_or_below_zero_disables_throttling() {
38 let mut throttler = TickThrottler::new(20, -20);
39
40 throttler.increment();
41 throttler.increment();
42
43 assert!(throttler.is_under_threshold());
44 }
45
46 #[test]
47 fn increment_reaches_threshold_and_tick_decays() {
48 let mut throttler = TickThrottler::new(20, 40);
49
50 throttler.increment();
51 assert!(throttler.is_under_threshold());
52
53 throttler.increment();
54 assert!(!throttler.is_under_threshold());
55
56 throttler.tick();
57 assert!(throttler.is_under_threshold());
58 }
59}