crossterm/event/
timeout.rs

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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
use std::time::{Duration, Instant};

/// Keeps track of the elapsed time since the moment the polling started.
#[derive(Debug, Clone)]
pub struct PollTimeout {
    timeout: Option<Duration>,
    start: Instant,
}

impl PollTimeout {
    /// Constructs a new `PollTimeout` with the given optional `Duration`.
    pub fn new(timeout: Option<Duration>) -> PollTimeout {
        PollTimeout {
            timeout,
            start: Instant::now(),
        }
    }

    /// Returns whether the timeout has elapsed.
    ///
    /// It always returns `false` if the initial timeout was set to `None`.
    pub fn elapsed(&self) -> bool {
        self.timeout
            .map(|timeout| self.start.elapsed() >= timeout)
            .unwrap_or(false)
    }

    /// Returns the timeout leftover (initial timeout duration - elapsed duration).
    pub fn leftover(&self) -> Option<Duration> {
        self.timeout.map(|timeout| {
            let elapsed = self.start.elapsed();

            if elapsed >= timeout {
                Duration::from_secs(0)
            } else {
                timeout - elapsed
            }
        })
    }
}

#[cfg(test)]
mod tests {
    use std::time::{Duration, Instant};

    use super::PollTimeout;

    #[test]
    pub fn test_timeout_without_duration_does_not_have_leftover() {
        let timeout = PollTimeout::new(None);
        assert_eq!(timeout.leftover(), None)
    }

    #[test]
    pub fn test_timeout_without_duration_never_elapses() {
        let timeout = PollTimeout::new(None);
        assert!(!timeout.elapsed());
    }

    #[test]
    pub fn test_timeout_elapses() {
        const TIMEOUT_MILLIS: u64 = 100;

        let timeout = PollTimeout {
            timeout: Some(Duration::from_millis(TIMEOUT_MILLIS)),
            start: Instant::now() - Duration::from_millis(2 * TIMEOUT_MILLIS),
        };

        assert!(timeout.elapsed());
    }

    #[test]
    pub fn test_elapsed_timeout_has_zero_leftover() {
        const TIMEOUT_MILLIS: u64 = 100;

        let timeout = PollTimeout {
            timeout: Some(Duration::from_millis(TIMEOUT_MILLIS)),
            start: Instant::now() - Duration::from_millis(2 * TIMEOUT_MILLIS),
        };

        assert!(timeout.elapsed());
        assert_eq!(timeout.leftover(), Some(Duration::from_millis(0)));
    }

    #[test]
    pub fn test_not_elapsed_timeout_has_positive_leftover() {
        let timeout = PollTimeout::new(Some(Duration::from_secs(60)));

        assert!(!timeout.elapsed());
        assert!(timeout.leftover().unwrap() > Duration::from_secs(0));
    }
}