Skip to main content

tvision_rs/
timer.rs

1//! Injected clock and timer queue.
2//!
3//! A [`TimerQueue`] holds pending one-shot and periodic timers; the event loop
4//! asks it which timers are due and how long until the next one. Time comes
5//! from an injected [`Clock`]: [`SystemClock`] in production, [`ManualClock`]
6//! in tests. **`Instant::now()` is only called inside [`SystemClock`]** — all
7//! timer logic operates on the opaque `u64` millisecond values the clock
8//! yields, so tests can advance time deterministically without sleeps.
9//!
10//! Two structural choices differ from the original:
11//!
12//! 1. **No re-entrancy dance.** [`TimerQueue::collect_expired`] gathers due ids
13//!    into a `Vec` and returns them; the caller dispatches afterwards, so there
14//!    is no re-entrant mutation of the queue to guard against. Two invariants
15//!    are preserved: a single `now_ms` value is used for the whole pass, and a
16//!    periodic timer fires at most once per `collect_expired` call (even if
17//!    overdue by several periods — it reschedules forward past `now_ms` via
18//!    [`calc_next_expires_at`]).
19//!
20//! 2. **The clock lives in the event loop, not the queue.** `now_ms` is passed
21//!    into [`TimerQueue::collect_expired`], [`TimerQueue::time_until_next`], and
22//!    [`TimerQueue::set_timer`] by the caller, which keeps the queue easy to
23//!    test and gives `set_timer` the absolute expiry it needs for the
24//!    reschedule grid arithmetic.
25//!
26//! **Guide:** [The event loop in depth](../../../internals/event-loop.html).
27//!
28//! # Turbo Vision heritage
29//!
30//! Ports `TTimerQueue` (`ttimerqu.cpp`, `system.h`) and its time source
31//! `THardwareInfo::getTickCountMs`. The original marked each timer with a
32//! per-invocation collect-id so a callback could mutate the list mid-iteration,
33//! and stored the clock inside the queue; tvision-rs replaces the callback with a
34//! returned id list and injects the clock from the event loop (deviations D9 and
35//! D11).
36
37use std::cell::Cell;
38use std::collections::HashMap;
39use std::time::{Duration, Instant};
40
41// ---------------------------------------------------------------------------
42// Clock — the injected time source
43// ---------------------------------------------------------------------------
44
45/// Monotonic millisecond clock.
46///
47/// Two implementations are provided: [`SystemClock`] for production and
48/// [`ManualClock`] for deterministic tests.  **Only [`SystemClock`] may call
49/// `Instant::now()`** — all other code receives `u64` ms values from the
50/// injected clock.
51///
52/// # Turbo Vision heritage
53///
54/// Faithful to `TTimePoint` (a `uint64_t` ms tick count) and
55/// `THardwareInfo::getTickCountMs`. The injected clock makes time
56/// deterministic in tests (deviation D11).
57pub trait Clock {
58    /// Monotonic milliseconds since some fixed epoch.
59    fn now_ms(&self) -> u64;
60}
61
62// ---------------------------------------------------------------------------
63// SystemClock — production implementation
64// ---------------------------------------------------------------------------
65
66/// Production clock. Captures an `Instant` at construction and returns elapsed
67/// ms on each call.
68///
69/// `Instant::now()` is allowed **only here** — everything else in the timer
70/// subsystem takes a `u64` from the caller.
71pub struct SystemClock {
72    base: Instant,
73}
74
75impl SystemClock {
76    /// Create a new `SystemClock` whose epoch is now.
77    pub fn new() -> Self {
78        SystemClock {
79            base: Instant::now(), // sole allowed call to Instant::now()
80        }
81    }
82}
83
84impl Default for SystemClock {
85    fn default() -> Self {
86        Self::new()
87    }
88}
89
90impl Clock for SystemClock {
91    fn now_ms(&self) -> u64 {
92        self.base.elapsed().as_millis() as u64
93    }
94}
95
96// ---------------------------------------------------------------------------
97// ManualClock — deterministic test clock
98// ---------------------------------------------------------------------------
99
100/// Test clock. Holds the current time in a [`Cell`] so `&self` can both read
101/// the time (via the [`Clock`] trait) and advance it (via
102/// [`set`](ManualClock::set) / [`advance`](ManualClock::advance)).
103pub struct ManualClock {
104    ms: Cell<u64>,
105}
106
107impl ManualClock {
108    /// Create a manual clock at `start_ms`.
109    pub fn new(start_ms: u64) -> Self {
110        ManualClock {
111            ms: Cell::new(start_ms),
112        }
113    }
114
115    /// Overwrite the current time.
116    pub fn set(&self, ms: u64) {
117        self.ms.set(ms);
118    }
119
120    /// Advance the current time by `delta_ms`.
121    pub fn advance(&self, delta_ms: u64) {
122        self.ms.set(self.ms.get() + delta_ms);
123    }
124}
125
126impl Clock for ManualClock {
127    fn now_ms(&self) -> u64 {
128        self.ms.get()
129    }
130}
131
132/// Lets a shared [`ManualClock`] be injected (as `Box<Rc<ManualClock>>`) while a
133/// test retains a clone to advance time — the boxed `dyn Clock` an event loop
134/// owns is otherwise un-advanceable. `Clock` reads through `&self`, and
135/// `ManualClock`'s interior [`Cell`] makes advancing through a shared `Rc`
136/// sound on the single thread the event loop runs on. **Test-only** to keep the
137/// public clock API minimal.
138#[cfg(test)]
139impl Clock for std::rc::Rc<ManualClock> {
140    fn now_ms(&self) -> u64 {
141        (**self).now_ms()
142    }
143}
144
145// ---------------------------------------------------------------------------
146// TimerId — a cancelable handle
147// ---------------------------------------------------------------------------
148
149/// A handle to a pending timer. Monotonically-increasing id allocated by
150/// [`TimerQueue`]; `Copy + Eq + Hash` so callers can store it and compare it in
151/// event handlers.
152///
153/// # Turbo Vision heritage
154///
155/// Faithful to `TTimerId` (`system.h`), which was a raw `TTimer*`; tvision-rs uses an
156/// opaque integer handle instead (no pointer arithmetic, and `u64` never
157/// realistically exhausts).
158#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
159pub struct TimerId(u64);
160
161// ---------------------------------------------------------------------------
162// Internal timer entry
163// ---------------------------------------------------------------------------
164
165#[derive(Debug)]
166struct TimerEntry {
167    /// Absolute ms when this timer next fires.
168    expires_at: u64,
169    /// `None` = one-shot; `Some(ms)` = periodic with this period. (The original
170    /// used a signed sentinel — negative for one-shot — where tvision-rs uses `Option`.)
171    period_ms: Option<u64>,
172}
173
174// ---------------------------------------------------------------------------
175// calc_next_expires_at
176// ---------------------------------------------------------------------------
177
178/// Catch-up-aware reschedule for periodic timers.
179///
180/// ```text
181/// // Pre: expires_at <= now && period > 0
182/// return (1 + (now - expires_at + period) / period) * period
183///            + expires_at - period;
184/// ```
185///
186/// The arithmetic advances `expires_at` to the next grid point strictly after
187/// `now`, skipping any missed periods.  It is **not** a simple `expires_at +
188/// period` — it aligns to the period grid even when many periods have elapsed.
189///
190/// # Overflow analysis
191/// With u64 ms the product `(1 + …) * period` is at least `2 * period`. The
192/// subsequent `+ expires_at - period` subtracts one period back, so the final
193/// result equals `product + expires_at - period`.  Because `product >= period`,
194/// `product + expires_at - period >= expires_at`, and wrapping cannot occur for
195/// realistic ms timestamps.  **The `- period` must execute last** (not
196/// `expires_at - period + product`) to avoid underflow when
197/// `expires_at < period`.
198///
199/// # Panics
200/// Panics in debug mode (and is undefined in release) if `period == 0`.
201/// Callers must guarantee `period > 0` and `expires_at <= now`.
202pub fn calc_next_expires_at(expires_at: u64, now: u64, period: u64) -> u64 {
203    (1 + (now - expires_at + period) / period) * period + expires_at - period
204}
205
206// ---------------------------------------------------------------------------
207// TimerQueue
208// ---------------------------------------------------------------------------
209
210/// A queue of pending one-shot and periodic timers.
211///
212/// [`collect_expired`](Self::collect_expired) returns the due timers as a
213/// `Vec<TimerId>` for the caller to dispatch, and the current time `now_ms` is
214/// passed in by the caller rather than stored here (see the module docs).
215///
216/// Durations are stored internally as `u64` milliseconds (truncated from
217/// [`Duration`]).  **Sub-millisecond periods truncate to 0 and are rejected.**
218///
219/// # Turbo Vision heritage
220///
221/// Ports `TTimerQueue` (`ttimerqu.cpp`, `system.h`).
222#[derive(Debug, Default)]
223pub struct TimerQueue {
224    timers: HashMap<TimerId, TimerEntry>,
225    next_id: u64,
226}
227
228impl TimerQueue {
229    /// Create an empty timer queue.
230    pub fn new() -> Self {
231        TimerQueue::default()
232    }
233
234    /// Arm a new timer.
235    ///
236    /// - `now_ms` — the current clock value at the moment of arming.  Must be
237    ///   supplied by the caller (the clock lives in the event loop, not here).
238    ///   Call `clock.now_ms()` immediately before `set_timer`.
239    /// - `timeout` — delay until first expiry.
240    /// - `period` — `None` for a one-shot; `Some(d)` for a repeating timer.
241    ///   `d` must convert to at least 1 ms (sub-millisecond periods are
242    ///   rejected with a `debug_assert`; in release they silently become
243    ///   one-shot-like one-ms timers — document this in your integration code).
244    ///
245    /// Returns a [`TimerId`] that can be passed to [`kill_timer`](Self::kill_timer).
246    pub fn set_timer(
247        &mut self,
248        now_ms: u64,
249        timeout: Duration,
250        period: Option<Duration>,
251    ) -> TimerId {
252        let timeout_ms = timeout.as_millis() as u64;
253        let period_ms = period.map(|d| {
254            let ms = d.as_millis() as u64;
255            debug_assert!(
256                ms > 0,
257                "timer period must be at least 1 ms; sub-ms periods are unsupported"
258            );
259            ms
260        });
261
262        let id = TimerId(self.next_id);
263        self.next_id += 1;
264
265        self.timers.insert(
266            id,
267            TimerEntry {
268                expires_at: now_ms + timeout_ms,
269                period_ms,
270            },
271        );
272        id
273    }
274
275    /// Cancel a pending timer.
276    ///
277    /// No-op if `id` is unknown or has already fired (one-shot).
278    pub fn kill_timer(&mut self, id: TimerId) {
279        self.timers.remove(&id);
280    }
281
282    /// Fire all timers due at `now_ms` and return their ids (in unspecified order).
283    ///
284    /// Instead of calling a user-supplied callback mid-iteration, it collects due
285    /// ids into a [`Vec`] and returns them.  The caller then dispatches each id
286    /// (posts a command, calls a callback, etc.).
287    ///
288    /// **Invariants:**
289    /// - A single `now_ms` snapshot is used for the whole pass.
290    /// - A periodic timer fires **at most once** per call, even if overdue by
291    ///   several periods — it is rescheduled forward past `now_ms` via
292    ///   [`calc_next_expires_at`].
293    /// - One-shot timers are removed from the queue upon firing.
294    pub fn collect_expired(&mut self, now_ms: u64) -> Vec<TimerId> {
295        let mut due = Vec::new();
296
297        // Collect due ids with their period first, then mutate — avoids
298        // borrow-checker issues in a single pass.
299        let mut to_reschedule: Vec<(TimerId, u64, u64)> = Vec::new(); // (id, expires_at, period_ms)
300        let mut to_remove: Vec<TimerId> = Vec::new();
301
302        for (&id, entry) in &self.timers {
303            if entry.expires_at <= now_ms {
304                due.push(id);
305                match entry.period_ms {
306                    Some(period_ms) if period_ms > 0 => {
307                        to_reschedule.push((id, entry.expires_at, period_ms));
308                    }
309                    _ => {
310                        to_remove.push(id);
311                    }
312                }
313            }
314        }
315
316        // Reschedule periodic timers.
317        for (id, expires_at, period_ms) in to_reschedule {
318            if let Some(entry) = self.timers.get_mut(&id) {
319                entry.expires_at = calc_next_expires_at(expires_at, now_ms, period_ms);
320            }
321        }
322
323        // Remove one-shot timers.
324        for id in to_remove {
325            self.timers.remove(&id);
326        }
327
328        due
329    }
330
331    /// Milliseconds until the next timer expires.
332    ///
333    /// - `None` if the queue is empty.
334    /// - `Some(Duration::ZERO)` if any timer is already due.
335    /// - `Some(remaining)` otherwise (the minimum over all timers).
336    ///
337    /// Returning `Option<Duration>` avoids any artificial cap on the wait time.
338    pub fn time_until_next(&self, now_ms: u64) -> Option<Duration> {
339        if self.timers.is_empty() {
340            return None;
341        }
342        let mut min_remaining: Option<u64> = None;
343        for entry in self.timers.values() {
344            if entry.expires_at <= now_ms {
345                return Some(Duration::ZERO);
346            }
347            let remaining = entry.expires_at - now_ms;
348            min_remaining = Some(match min_remaining {
349                None => remaining,
350                Some(prev) => prev.min(remaining),
351            });
352        }
353        min_remaining.map(Duration::from_millis)
354    }
355
356    /// Whether the queue has no pending timers.
357    pub fn is_empty(&self) -> bool {
358        self.timers.is_empty()
359    }
360
361    /// Number of pending timers.
362    pub fn len(&self) -> usize {
363        self.timers.len()
364    }
365}
366
367// ---------------------------------------------------------------------------
368// Tests
369// ---------------------------------------------------------------------------
370
371#[cfg(test)]
372mod tests {
373    use super::*;
374
375    // Helper: a ManualClock starting at 0.
376    fn clock0() -> ManualClock {
377        ManualClock::new(0)
378    }
379
380    // -----------------------------------------------------------------------
381    // calc_next_expires_at
382    // -----------------------------------------------------------------------
383
384    #[test]
385    fn calc_next_expires_at_basic() {
386        // expires_at=100, period=30, now=205
387        // (1 + (205-100+30)/30)*30 + 100 - 30
388        // = (1 + 135/30)*30 + 70
389        // = (1 + 4)*30 + 70
390        // = 150 + 70 = 220
391        let next = calc_next_expires_at(100, 205, 30);
392        assert_eq!(next, 220);
393        assert!(next > 205, "rescheduled expiry must be strictly after now");
394    }
395
396    #[test]
397    fn calc_next_expires_at_exactly_on_boundary() {
398        // expires_at=0, period=50, now=100 (exactly 2 periods elapsed)
399        // (1 + (100-0+50)/50)*50 + 0 - 50
400        // = (1 + 3)*50 - 50 = 200 - 50 = 150
401        let next = calc_next_expires_at(0, 100, 50);
402        assert_eq!(next, 150);
403        assert!(next > 100);
404    }
405
406    #[test]
407    fn calc_next_expires_at_one_period_behind() {
408        // expires_at=100, period=50, now=130 (< 1 full period behind)
409        // (1 + (130-100+50)/50)*50 + 100 - 50
410        // = (1 + 1)*50 + 50 = 150
411        let next = calc_next_expires_at(100, 130, 50);
412        assert_eq!(next, 150);
413        assert!(next > 130);
414    }
415
416    #[test]
417    fn calc_next_expires_at_large_expires_at() {
418        // Verify no underflow when expires_at > period.
419        // expires_at=1000, period=30, now=1005
420        // (1 + (1005-1000+30)/30)*30 + 1000 - 30
421        // = (1 + 1)*30 + 970 = 60 + 970 = 1030
422        let next = calc_next_expires_at(1000, 1005, 30);
423        assert_eq!(next, 1030);
424        assert!(next > 1005);
425    }
426
427    // -----------------------------------------------------------------------
428    // ManualClock
429    // -----------------------------------------------------------------------
430
431    #[test]
432    fn manual_clock_new_set_advance() {
433        let c = ManualClock::new(1000);
434        assert_eq!(c.now_ms(), 1000);
435        c.set(5000);
436        assert_eq!(c.now_ms(), 5000);
437        c.advance(100);
438        assert_eq!(c.now_ms(), 5100);
439        c.advance(0);
440        assert_eq!(c.now_ms(), 5100);
441    }
442
443    #[test]
444    fn system_clock_monotonic() {
445        let c = SystemClock::new();
446        let t0 = c.now_ms();
447        let t1 = c.now_ms();
448        assert!(t1 >= t0);
449    }
450
451    // -----------------------------------------------------------------------
452    // TimerQueue — one-shot
453    // -----------------------------------------------------------------------
454
455    #[test]
456    fn one_shot_fires_once_then_gone() {
457        let clock = clock0();
458        let mut q = TimerQueue::new();
459
460        let id = q.set_timer(clock.now_ms(), Duration::from_millis(100), None);
461        assert_eq!(q.len(), 1);
462
463        // Before expiry — nothing fires.
464        clock.advance(50);
465        let fired = q.collect_expired(clock.now_ms());
466        assert!(fired.is_empty());
467        assert_eq!(q.len(), 1);
468
469        // At expiry — fires once.
470        clock.advance(50);
471        let fired = q.collect_expired(clock.now_ms());
472        assert_eq!(fired, vec![id]);
473        assert!(q.is_empty(), "one-shot must be removed after firing");
474
475        // After — nothing more.
476        clock.advance(200);
477        let fired = q.collect_expired(clock.now_ms());
478        assert!(fired.is_empty());
479    }
480
481    #[test]
482    fn one_shot_fires_when_overdue() {
483        let clock = clock0();
484        let mut q = TimerQueue::new();
485
486        let id = q.set_timer(clock.now_ms(), Duration::from_millis(10), None);
487
488        // Well past expiry.
489        clock.advance(999);
490        let fired = q.collect_expired(clock.now_ms());
491        assert_eq!(fired, vec![id]);
492        assert!(q.is_empty());
493    }
494
495    // -----------------------------------------------------------------------
496    // TimerQueue — periodic
497    // -----------------------------------------------------------------------
498
499    #[test]
500    fn periodic_fires_at_most_once_per_collect() {
501        let clock = clock0();
502        let mut q = TimerQueue::new();
503
504        let period = Duration::from_millis(30);
505        let id = q.set_timer(clock.now_ms(), period, Some(period));
506        assert_eq!(q.len(), 1);
507
508        // First period: advance to t=30 (exactly on expiry).
509        clock.advance(30);
510        let fired = q.collect_expired(clock.now_ms());
511        assert_eq!(fired.len(), 1);
512        assert_eq!(fired[0], id);
513        assert_eq!(q.len(), 1, "periodic timer stays in queue");
514
515        // time_until_next should now point to the rescheduled expiry.
516        let until = q.time_until_next(clock.now_ms());
517        assert!(
518            until.is_some() && until.unwrap() > Duration::ZERO,
519            "rescheduled timer must not be immediately due again"
520        );
521
522        // Advance well past several periods in one step — still fires at most once.
523        clock.advance(300); // many periods elapsed
524        let fired = q.collect_expired(clock.now_ms());
525        assert_eq!(
526            fired.len(),
527            1,
528            "periodic fires at most once per collect_expired"
529        );
530        assert_eq!(q.len(), 1);
531    }
532
533    #[test]
534    fn periodic_reschedules_forward() {
535        let clock = clock0();
536        let mut q = TimerQueue::new();
537
538        let period = Duration::from_millis(50);
539        let _id = q.set_timer(clock.now_ms(), period, Some(period));
540
541        // Fire once at t=50.
542        clock.advance(50);
543        q.collect_expired(clock.now_ms());
544
545        // Now the timer should be rescheduled past t=50.
546        let until = q.time_until_next(clock.now_ms()).unwrap();
547        assert!(
548            until > Duration::ZERO,
549            "rescheduled expiry must be in the future"
550        );
551
552        // Fire again at t=100.
553        clock.advance(50);
554        let fired = q.collect_expired(clock.now_ms());
555        assert_eq!(fired.len(), 1);
556        assert_eq!(q.len(), 1);
557    }
558
559    // -----------------------------------------------------------------------
560    // TimerQueue — kill_timer
561    // -----------------------------------------------------------------------
562
563    #[test]
564    fn kill_timer_cancels_pending() {
565        let clock = clock0();
566        let mut q = TimerQueue::new();
567
568        let id = q.set_timer(clock.now_ms(), Duration::from_millis(100), None);
569        assert_eq!(q.len(), 1);
570
571        q.kill_timer(id);
572        assert!(q.is_empty());
573
574        clock.advance(200);
575        let fired = q.collect_expired(clock.now_ms());
576        assert!(fired.is_empty(), "killed timer must not fire");
577    }
578
579    #[test]
580    fn kill_timer_unknown_id_is_noop() {
581        let clock = clock0();
582        let mut q = TimerQueue::new();
583
584        let id = q.set_timer(clock.now_ms(), Duration::from_millis(100), None);
585        let phantom = TimerId(id.0 + 999);
586
587        q.kill_timer(phantom); // must not panic
588        assert_eq!(q.len(), 1, "killing unknown id must not remove real timer");
589
590        q.kill_timer(phantom); // second call also no-op
591        assert_eq!(q.len(), 1);
592    }
593
594    #[test]
595    fn kill_timer_after_oneshot_fires_is_noop() {
596        let clock = clock0();
597        let mut q = TimerQueue::new();
598
599        let id = q.set_timer(clock.now_ms(), Duration::from_millis(10), None);
600        clock.advance(20);
601        q.collect_expired(clock.now_ms()); // fires and removes
602
603        q.kill_timer(id); // must not panic
604        assert!(q.is_empty());
605    }
606
607    #[test]
608    fn kill_timer_updates_time_until_next() {
609        let clock = clock0();
610        let mut q = TimerQueue::new();
611
612        // Two timers: one at t=50, one at t=200.
613        let early = q.set_timer(clock.now_ms(), Duration::from_millis(50), None);
614        let _late = q.set_timer(clock.now_ms(), Duration::from_millis(200), None);
615
616        assert_eq!(
617            q.time_until_next(clock.now_ms()),
618            Some(Duration::from_millis(50))
619        );
620
621        q.kill_timer(early);
622        assert_eq!(
623            q.time_until_next(clock.now_ms()),
624            Some(Duration::from_millis(200)),
625            "after killing the soonest timer, next timeout must reflect the remaining one"
626        );
627    }
628
629    // -----------------------------------------------------------------------
630    // TimerQueue — time_until_next
631    // -----------------------------------------------------------------------
632
633    #[test]
634    fn time_until_next_none_when_empty() {
635        let q = TimerQueue::new();
636        assert_eq!(q.time_until_next(0), None);
637    }
638
639    #[test]
640    fn time_until_next_zero_when_overdue() {
641        let clock = clock0();
642        let mut q = TimerQueue::new();
643
644        q.set_timer(clock.now_ms(), Duration::from_millis(10), None);
645        clock.advance(100);
646
647        assert_eq!(q.time_until_next(clock.now_ms()), Some(Duration::ZERO));
648    }
649
650    #[test]
651    fn time_until_next_remaining_otherwise() {
652        let clock = clock0();
653        let mut q = TimerQueue::new();
654
655        q.set_timer(clock.now_ms(), Duration::from_millis(100), None);
656        clock.advance(40);
657
658        assert_eq!(
659            q.time_until_next(clock.now_ms()),
660            Some(Duration::from_millis(60))
661        );
662    }
663
664    #[test]
665    fn time_until_next_reflects_soonest_of_several() {
666        let clock = clock0();
667        let mut q = TimerQueue::new();
668
669        q.set_timer(clock.now_ms(), Duration::from_millis(200), None);
670        q.set_timer(clock.now_ms(), Duration::from_millis(50), None);
671        q.set_timer(clock.now_ms(), Duration::from_millis(100), None);
672
673        assert_eq!(
674            q.time_until_next(clock.now_ms()),
675            Some(Duration::from_millis(50))
676        );
677    }
678
679    // -----------------------------------------------------------------------
680    // TimerQueue — multiple timers fire together
681    // -----------------------------------------------------------------------
682
683    #[test]
684    fn multiple_timers_fire_in_same_collect() {
685        let clock = clock0();
686        let mut q = TimerQueue::new();
687
688        let id1 = q.set_timer(clock.now_ms(), Duration::from_millis(10), None);
689        let id2 = q.set_timer(clock.now_ms(), Duration::from_millis(20), None);
690        let id3 = q.set_timer(clock.now_ms(), Duration::from_millis(5), None);
691
692        clock.advance(30); // all three are overdue
693        let mut fired = q.collect_expired(clock.now_ms());
694        fired.sort_by_key(|id| id.0); // sort for deterministic assert
695
696        let mut expected = vec![id1, id2, id3];
697        expected.sort_by_key(|id| id.0);
698
699        assert_eq!(fired, expected);
700        assert!(q.is_empty());
701    }
702
703    #[test]
704    fn mix_of_periodic_and_oneshot_in_same_collect() {
705        let clock = clock0();
706        let mut q = TimerQueue::new();
707
708        let one_shot = q.set_timer(clock.now_ms(), Duration::from_millis(10), None);
709        let periodic = q.set_timer(
710            clock.now_ms(),
711            Duration::from_millis(10),
712            Some(Duration::from_millis(50)),
713        );
714
715        clock.advance(10);
716        let fired = q.collect_expired(clock.now_ms());
717        assert_eq!(fired.len(), 2);
718        assert!(fired.contains(&one_shot));
719        assert!(fired.contains(&periodic));
720
721        // One-shot gone; periodic still present.
722        assert_eq!(q.len(), 1);
723        assert!(!q.is_empty());
724    }
725}