Skip to main content

wgame_utils/
lib.rs

1//! Utility types and functions for wgame.
2//!
3//! Provides periodic timer for handling regular intervals.
4
5#![forbid(unsafe_code)]
6
7use futures::future::FusedFuture;
8use std::time::Duration;
9use wgame_app::{
10    runtime::sleep_until,
11    sleep,
12    time::{Instant, Timer},
13};
14
15/// A timer that preserves its deadline phase when ticks are missed.
16/// [`Self::elapsed_periods`] and [`Self::wait_next`] return the duration of whole
17/// elapsed periods, not an integer count. Use elapsed time for animation and
18/// periodic timers for scheduled background work.
19pub struct PeriodicTimer {
20    timer: Timer,
21    period: Duration,
22}
23
24impl PeriodicTimer {
25    /// Creates a periodic timer in the current runtime.
26    ///
27    /// # Panics
28    ///
29    /// Panics for a zero period or when no runtime is active.
30    pub fn new(period: Duration) -> Self {
31        assert!(!period.is_zero(), "Timer period must be positive");
32        Self {
33            timer: sleep(period),
34            period,
35        }
36    }
37
38    /// Returns the period of the timer.
39    pub fn period(&self) -> Duration {
40        self.period
41    }
42
43    /// Returns the total duration of whole periods elapsed since the last wait.
44    pub fn elapsed_periods(&mut self) -> Duration {
45        if self.timer.is_terminated() {
46            let now = Instant::now();
47            let (next_timestamp, elapsed) = advance(self.timer.timestamp(), now, self.period);
48            self.timer = sleep_until(next_timestamp);
49            elapsed
50        } else {
51            Duration::ZERO
52        }
53    }
54
55    /// Waits for the next timer fire and returns the elapsed periods.
56    pub async fn wait_next(&mut self) -> Duration {
57        (&mut self.timer).await;
58        self.elapsed_periods()
59    }
60}
61
62fn advance(deadline: Instant, now: Instant, period: Duration) -> (Instant, Duration) {
63    let late = now - deadline;
64    let rem = late.as_nanos() % period.as_nanos();
65    let remainder = Duration::new((rem / 1_000_000_000) as u64, (rem % 1_000_000_000) as u32);
66    let elapsed = late - remainder + period;
67    (deadline + elapsed, elapsed)
68}
69#[cfg(test)]
70mod tests {
71    use super::*;
72    #[test]
73    fn periodic_deadlines_keep_phase_and_count_missed_ticks() {
74        let start = Instant::now();
75        let period = Duration::from_millis(10);
76        assert_eq!(advance(start, start, period), (start + period, period));
77        assert_eq!(
78            advance(start, start + Duration::from_millis(25), period),
79            (start + Duration::from_millis(30), Duration::from_millis(30))
80        );
81    }
82}