Skip to main content

naia_shared/backends/native/
timer.rs

1use std::time::Duration;
2
3use naia_socket_shared::Instant;
4
5/// A Timer with a given duration after which it will enter into a "Ringing"
6/// state. The Timer can be reset at an given time, or manually set to start
7/// "Ringing" again.
8pub struct Timer {
9    duration: Duration,
10    last: Instant,
11}
12
13impl Timer {
14    /// Creates a new Timer with a given Duration
15    pub fn new(duration: Duration) -> Self {
16        Self {
17            last: Instant::now(),
18            duration,
19        }
20    }
21
22    /// Reset the Timer to stop ringing and wait till 'Duration' has elapsed
23    /// again
24    pub fn reset(&mut self) {
25        self.last = Instant::now();
26    }
27
28    /// Gets whether or not the Timer is "Ringing" (i.e. the given Duration has
29    /// elapsed since the last "reset")
30    pub fn ringing(&self) -> bool {
31        let now = Instant::now();
32        // Handle case where time might go backwards (shouldn't happen, but be safe)
33        if now.is_after(&self.last) {
34            self.last.elapsed(&now) > self.duration
35        } else {
36            false
37        }
38    }
39
40    /// Manually causes the Timer to enter into a "Ringing" state
41    pub fn ring_manual(&mut self) {
42        let mut last = self.last.clone();
43        last.subtract_millis(self.duration.as_millis() as u32);
44        self.last = last;
45    }
46}