waiter_trait/
counter.rs

1use super::*;
2
3/// The timeout condition is independent of time
4/// and is determined solely by the number of times `timeout()` is called.
5pub struct Counter {
6    retry_times: usize,
7}
8
9impl Counter {
10    /// - `retry_times`: The number of calls to `timeout()` before it returns `true`.
11    ///     - If set to `0`, `timeout()` always returns `true`
12    ///     - If set to `usize::MAX`, `timeout()` always returns `false`
13    pub fn new(retry_times: usize) -> Self {
14        Self { retry_times }
15    }
16}
17
18impl Waiter for Counter {
19    #[inline]
20    fn start(&self) -> impl WaiterTime {
21        CounterInstance {
22            count: 0,
23            waiter: self,
24        }
25    }
26}
27
28pub struct CounterInstance<'a> {
29    count: usize,
30    waiter: &'a Counter,
31}
32
33impl<'a> WaiterTime for CounterInstance<'a> {
34    #[inline]
35    fn timeout(&mut self) -> bool {
36        if self.waiter.retry_times == usize::MAX {
37            return false;
38        }
39
40        if self.count < self.waiter.retry_times {
41            self.count = self.count.wrapping_add(1);
42            false
43        } else {
44            true
45        }
46    }
47
48    #[inline(always)]
49    fn restart(&mut self) {
50        self.count = 0;
51    }
52}
53
54#[cfg(test)]
55mod tests {
56    use super::*;
57
58    #[test]
59    fn counter() {
60        let c = Counter::new(0);
61        let mut t = c.start();
62        assert!(t.timeout());
63        assert!(t.timeout());
64
65        let c = Counter::new(usize::MAX);
66        let mut t = c.start();
67        assert!(!t.timeout());
68        assert!(!t.timeout());
69
70        let c = Counter::new(2);
71        let mut t = c.start();
72        assert!(!t.timeout());
73        assert!(!t.timeout());
74        assert!(t.timeout());
75        assert!(t.timeout());
76
77        t.restart();
78        assert!(!t.timeout());
79        assert!(!t.timeout());
80        assert!(t.timeout());
81        assert!(t.timeout());
82    }
83}