aboutsummaryrefslogtreecommitdiff
path: root/src/client/timer.rs
blob: bd5c249a406c81c83ed462418efd6bb35de0d594 (plain)
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
74
75
76
77
78
use std::time::{Duration, Instant};

pub(super) struct ClientLoopTimer {
    deadline: Option<Instant>,
}

impl ClientLoopTimer {
    pub(super) fn new() -> Self {
        Self { deadline: None }
    }

    pub(super) fn deadline(&mut self, now: Instant, delay: Duration) -> Instant {
        let requested = now.checked_add(delay).unwrap_or(now);
        let deadline = self
            .deadline
            .map_or(requested, |current| current.min(requested));
        self.deadline = Some(deadline);
        deadline
    }

    pub(super) fn fired(&mut self) {
        self.deadline = None;
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn incoming_events_do_not_postpone_timer_deadline() {
        let start = Instant::now();
        let delay = Duration::from_millis(100);
        let mut timer = ClientLoopTimer::new();

        let first_deadline = timer.deadline(start, delay);
        assert_eq!(
            timer.deadline(start + Duration::from_millis(25), delay),
            first_deadline
        );
        assert_eq!(
            timer.deadline(start + Duration::from_millis(50), delay),
            first_deadline
        );
        assert_eq!(
            timer.deadline(start + Duration::from_millis(75), delay),
            first_deadline
        );

        timer.fired();
        assert_eq!(
            timer.deadline(first_deadline, delay),
            first_deadline + delay
        );
    }

    #[test]
    fn earlier_client_work_can_pull_the_timer_deadline_forward() {
        let start = Instant::now();
        let mut timer = ClientLoopTimer::new();

        assert_eq!(
            timer.deadline(start, Duration::from_millis(100)),
            start + Duration::from_millis(100)
        );
        assert_eq!(
            timer.deadline(start + Duration::from_millis(20), Duration::from_millis(10)),
            start + Duration::from_millis(30)
        );
        assert_eq!(
            timer.deadline(
                start + Duration::from_millis(25),
                Duration::from_millis(100)
            ),
            start + Duration::from_millis(30)
        );
    }
}