Skip to main content

pushrod/
timer.rs

1// Timers
2// Pushrod
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! # Timers
17//!
18//! The schedule behind `Engine::on_timer`.  It only decides *when* timers are due, from
19//! [`Instant`]s the caller passes in; the callbacks live in the `Engine`.  Keeping the clock out of
20//! the schedule makes it testable without waiting.
21
22use std::time::{Duration, Instant};
23
24/// A handle identifying one timer, returned by `Engine::on_timer`.
25///
26/// IDs are unique within an `Engine` and are never reused.  Pass one to `Ui::cancel_timer` or
27/// `Engine::cancel_timer` to stop the timer.
28#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
29pub struct TimerId(pub u64);
30
31/// One scheduled timer.
32struct Entry {
33    id: TimerId,
34    interval: Duration,
35    repeat: bool,
36    due: Instant,
37}
38
39/// The timers that are waiting to fire.
40#[derive(Default)]
41pub(crate) struct TimerSchedule {
42    next_id: u64,
43    entries: Vec<Entry>,
44}
45
46impl TimerSchedule {
47    /// Schedules a timer to first fire one `interval` after `now`.
48    ///
49    /// # Arguments
50    ///
51    /// * `now` - The current time.
52    /// * `interval` - The time until the timer fires, and between firings if it repeats.
53    /// * `repeat` - `true` to fire every `interval`; `false` to fire once.
54    ///
55    /// # Returns
56    ///
57    /// The new timer's ID.
58    pub(crate) fn add(&mut self, now: Instant, interval: Duration, repeat: bool) -> TimerId {
59        let id = TimerId(self.next_id);
60
61        self.next_id += 1;
62        self.entries.push(Entry {
63            id,
64            interval,
65            repeat,
66            due: now + interval,
67        });
68
69        id
70    }
71
72    /// Stops a timer.
73    ///
74    /// # Arguments
75    ///
76    /// * `id` - The timer to stop.
77    ///
78    /// # Returns
79    ///
80    /// `true` if the timer was waiting; `false` if it had already fired (one-shot) or been
81    /// cancelled.
82    pub(crate) fn cancel(&mut self, id: TimerId) -> bool {
83        let before = self.entries.len();
84
85        self.entries.retain(|entry| entry.id != id);
86
87        self.entries.len() != before
88    }
89
90    /// Returns whether a timer is still waiting.
91    ///
92    /// # Arguments
93    ///
94    /// * `id` - The timer to look for.
95    ///
96    /// # Returns
97    ///
98    /// `true` if the timer is scheduled.
99    pub(crate) fn contains(&self, id: TimerId) -> bool {
100        self.entries.iter().any(|entry| entry.id == id)
101    }
102
103    /// Returns the timers due at `now`, earliest first, without changing the schedule.
104    ///
105    /// # Arguments
106    ///
107    /// * `now` - The current time.
108    ///
109    /// # Returns
110    ///
111    /// The IDs of the timers whose time has come; call [`TimerSchedule::complete`] for each.
112    pub(crate) fn due(&self, now: Instant) -> Vec<TimerId> {
113        let mut due: Vec<&Entry> = self.entries.iter().filter(|e| e.due <= now).collect();
114
115        due.sort_by_key(|entry| (entry.due, entry.id));
116        due.into_iter().map(|entry| entry.id).collect()
117    }
118
119    /// Marks a due timer as fired: a one-shot is removed, and a repeating timer moves to its next
120    /// time.  A repeating timer that fell several intervals behind fires once, then keeps its
121    /// rhythm, instead of firing in a burst.
122    ///
123    /// # Arguments
124    ///
125    /// * `id` - The timer that is about to fire.
126    /// * `now` - The current time.
127    ///
128    /// # Returns
129    ///
130    /// `Some(repeat)` if the timer fires (`repeat` is whether it stays scheduled), or `None` if it
131    /// was cancelled since [`TimerSchedule::due`] was called.
132    pub(crate) fn complete(&mut self, id: TimerId, now: Instant) -> Option<bool> {
133        let index = self.entries.iter().position(|entry| entry.id == id)?;
134        let entry = &mut self.entries[index];
135
136        if !entry.repeat {
137            self.entries.remove(index);
138
139            return Some(false);
140        }
141
142        // A zero interval would never get ahead of `now`; fire it once per call.
143        if entry.interval.is_zero() {
144            entry.due = now;
145        } else {
146            while entry.due <= now {
147                entry.due += entry.interval;
148            }
149        }
150
151        Some(true)
152    }
153
154    /// Returns the time until the next timer is due.
155    ///
156    /// # Arguments
157    ///
158    /// * `now` - The current time.
159    ///
160    /// # Returns
161    ///
162    /// The wait (zero if one is already due), or `None` if no timers are scheduled.
163    pub(crate) fn next_wait(&self, now: Instant) -> Option<Duration> {
164        self.entries
165            .iter()
166            .map(|entry| entry.due.saturating_duration_since(now))
167            .min()
168    }
169}
170
171#[cfg(test)]
172mod tests {
173    use super::*;
174
175    fn ms(n: u64) -> Duration {
176        Duration::from_millis(n)
177    }
178
179    #[test]
180    fn a_timer_is_due_only_after_its_interval() {
181        let t0 = Instant::now();
182        let mut s = TimerSchedule::default();
183        let id = s.add(t0, ms(100), false);
184
185        assert!(s.due(t0 + ms(99)).is_empty());
186        assert_eq!(s.due(t0 + ms(100)), vec![id]);
187    }
188
189    #[test]
190    fn a_one_shot_fires_once() {
191        let t0 = Instant::now();
192        let mut s = TimerSchedule::default();
193        let id = s.add(t0, ms(10), false);
194
195        assert_eq!(s.complete(id, t0 + ms(10)), Some(false));
196        assert!(!s.contains(id));
197        assert!(s.due(t0 + ms(500)).is_empty());
198    }
199
200    #[test]
201    fn a_repeating_timer_keeps_its_rhythm_and_skips_missed_intervals() {
202        let t0 = Instant::now();
203        let mut s = TimerSchedule::default();
204        let id = s.add(t0, ms(100), true);
205
206        // Seen late, at 350 ms: one firing, next due at 400 ms.
207        assert_eq!(s.complete(id, t0 + ms(350)), Some(true));
208        assert!(s.due(t0 + ms(399)).is_empty());
209        assert_eq!(s.due(t0 + ms(400)), vec![id]);
210    }
211
212    #[test]
213    fn cancelling_removes_the_timer_once() {
214        let t0 = Instant::now();
215        let mut s = TimerSchedule::default();
216        let id = s.add(t0, ms(10), true);
217
218        assert!(s.cancel(id));
219        assert!(!s.cancel(id));
220        assert_eq!(s.complete(id, t0 + ms(10)), None);
221        assert!(!s.contains(id));
222    }
223
224    #[test]
225    fn due_timers_are_ordered_and_ids_are_not_reused() {
226        let t0 = Instant::now();
227        let mut s = TimerSchedule::default();
228        let late = s.add(t0, ms(50), false);
229        let early = s.add(t0, ms(10), false);
230
231        assert_ne!(late, early);
232        assert_eq!(s.due(t0 + ms(60)), vec![early, late]);
233
234        s.cancel(late);
235
236        assert_ne!(s.add(t0, ms(1), false), late);
237    }
238
239    #[test]
240    fn next_wait_reports_the_nearest_timer() {
241        let t0 = Instant::now();
242        let mut s = TimerSchedule::default();
243
244        assert_eq!(s.next_wait(t0), None);
245
246        s.add(t0, ms(300), false);
247        s.add(t0, ms(120), false);
248
249        assert_eq!(s.next_wait(t0 + ms(20)), Some(ms(100)));
250        assert_eq!(s.next_wait(t0 + ms(400)), Some(Duration::ZERO));
251    }
252}