rtactor 0.6.0

An Actor framework specially designed for Real-Time constrained use cases.
Documentation
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
//! Type of actors where messages handled by a dispatcher and that call the actor to process them.

// TODO use lock-free mpsc
// see https://docs.rs/crossbeam/0.3.2/crossbeam/index.html

// TODO use lock-free pool:
// https://docs.rs/heapless/0.5.5/heapless/pool/index.html

use crate::Notification;

use crate::actor;
use crate::actor::AddrKind;
use crate::actor::{ActorId, Message, RequestId};
use crate::mpsc_dispatcher::MpscDispatcher;

use std::boxed::Box;

use std::cmp::Ordering;
use std::collections::BTreeMap;
use std::ops::Add;
use std::ops::ControlFlow;
use std::sync::mpsc;

use std::time;
use std::time::Duration;

////////////////////////////// public types /////////////////////////////////////

/// The custom implementation of message handling for a given reactive actor.
///
/// There are two ways to write mocks of reactive actors. There is the very simple
/// `MockBehavior` that mocks directly this trait. Or a more complex and powerful
/// `simulation::ReactiveMocker` that allows to change the mock during the tests, user
/// data, etc.
#[cfg_attr(feature = "mockall", mockall::automock)]
pub trait Behavior {
    #[allow(clippy::needless_lifetimes)] // false positive (tested with 1.64.0 and 1.86.0)
    fn process_message<'a>(&mut self, context: &mut ProcessContext<'a>, msg: &Message);
}

/// An way to interact with the dispatcher that is only valid during `Behavior::process_message()`.
pub struct ProcessContext<'a> {
    tx: mpsc::SyncSender<MessageAndDstId>,
    pub(crate) own_actor_id: actor::ActorId,
    request_id_counter: RequestId,
    instant_source: &'a dyn InstantSource,
    timeout_scheduler: &'a mut TimeoutScheduler,
}

/// Point in time similar to `std::time::Instant` but that allows simulation for reactive.
#[derive(Debug, Clone, Copy)]
pub struct Instant(InternalInstant);

/// Data send in Notification when a timer mature.
///
/// Use `timer.is_scheduling(notif)` to check if a timer is ready.
#[derive(Debug)]
pub struct Timeout(TimeoutId);

/// An handle to a timer that can send a message to a Behavior at a given time.
///
/// Timers can be freely created and destroyed. It is best to call `context.unschedule(timer)`
/// on them before destruction to avoid to retain an entry in the timer scheduling mechanism.
/// If not the timer will be dispatched but never trigger any is_scheduling() == true code.
#[derive(Clone, Copy)]
pub struct Timer {
    id: TimeoutId,
    deadline: Instant,
}

/// An implementation of behavior that do nothing in process_message().
///
/// This can be useful to create circular address dependencies at build time:
/// ```
/// # use rtactor as rt;
/// # struct Sink();
/// # impl Sink {pub fn new(_: &rt::Addr) -> Self {Self()}}
/// # impl rt::Behavior for Sink {fn process_message<'a, 'b>(&mut self, _context: &'a mut rt::ProcessContext<'b>, _msg: &rt::Message) {}}
/// # struct Source();
/// # impl Source {pub fn new(_: &rt::Addr) -> Self {Self()}}
/// # impl rt::Behavior for Source {fn process_message<'a, 'b>(&mut self, _context: &'a mut rt::ProcessContext<'b>, _msg: &rt::Message) {}}
/// #
/// # let builder = rt::mpsc_dispatcher::Builder::new(1);
/// # let mut disp_accessor = builder.to_accessor();
/// # std::thread::spawn(move || builder.build().process());
///
/// let sink_addr = disp_accessor.register_reactive_unwrap(rt::DummyBehavior::default());
/// let source_addr = disp_accessor.register_reactive_unwrap(Source::new(&sink_addr));
/// disp_accessor.replace_reactive_unwrap(&sink_addr, Sink::new(&source_addr));
/// ```

#[derive(Default)]
pub struct DummyBehavior();

impl Behavior for DummyBehavior {
    fn process_message(&mut self, _context: &mut ProcessContext, _msg: &Message) {}
}

////////////////////////////// internal types /////////////////////////////////////

/// An address pointing to an actor that "reacts" (is called) when a message is received.
#[derive(Debug, Clone)]
pub(crate) struct ReactiveAddr {
    tx: mpsc::SyncSender<MessageAndDstId>,
    pub dst_id: actor::ActorId,
}

/// What is stored in the queue.
pub(crate) struct MessageAndDstId {
    pub message: Message,
    pub dst_id: actor::ActorId,
}

/// Private implementation of a `reactive::Instant`.
#[derive(Debug, Clone, Copy)]
pub(crate) enum InternalInstant {
    Finite(time::Instant),
    Infinity,
}

/// Source of `reactive::Instant`, for example real or simulated.
pub(crate) trait InstantSource {
    fn now(&self) -> Instant;
}

/// Identify a timeout to avoid flying notification of unscheduled timer to trigger code.
type TimeoutId = u32;

/// Entity responsible to manage timer registrations and timeouts.
pub(crate) struct TimeoutScheduler {
    next_timeout_id: TimeoutId,
    timeout_list: BTreeMap<Timer, ActorId>,
}

////////////////////////////// public impl's /////////////////////////////////////

impl<'a> ProcessContext<'a> {
    pub(crate) fn new(
        disp: &MpscDispatcher,
        request_id_counter: RequestId,
        instant_source: &'a dyn InstantSource,
        timeout_scheduler: &'a mut TimeoutScheduler,
    ) -> ProcessContext<'a> {
        ProcessContext {
            tx: disp.tx.clone(),
            own_actor_id: actor::INVALID_ACTOR_ID,
            request_id_counter,
            instant_source,
            timeout_scheduler,
        }
    }

    /// Return the actor address of the reactive being processed.
    pub fn own_addr(&self) -> actor::Addr {
        ReactiveAddr::new(self.tx.clone(), self.own_actor_id).into_addr()
    }

    #[deprecated = "use own_addr()"]
    pub fn get_own_addr(&self) -> actor::Addr {
        self.own_addr()
    }

    /// Send a request to an other actor.
    ///
    /// Return an identifier of the transaction.
    pub fn send_request<T>(&mut self, dst: &actor::Addr, data: T) -> RequestId
    where
        T: 'static + Send,
    {
        self.request_id_counter = self.request_id_counter.wrapping_add(1);
        dst.receive_request(&self.own_addr(), self.request_id_counter, data);
        self.request_id_counter
    }

    /// Send the response to a request.
    pub fn send_response<T>(&mut self, request: &actor::Request, data: T)
    where
        T: 'static + Send,
    {
        self.send_addr_id_response(&request.src, request.id, data);
    }

    /// Send the response to a request using destination and request id.
    pub fn send_addr_id_response<T>(&mut self, dst: &actor::Addr, request_id: RequestId, data: T)
    where
        T: 'static + Send,
    {
        // TODO should we retry ? wait ? block ?
        let _result = dst.receive_ok_response(request_id, data);
    }

    pub fn send_self_notification<T>(&mut self, data: T) -> Result<(), crate::Error>
    where
        T: 'static + Send,
    {
        // There is room here for optimization.
        self.own_addr().receive_notification(data)
    }

    /// Send notification.
    ///
    /// This method is equivalent to the function rtactor::send_notification()
    /// but is preferred because it allows possible future thread local memory allocation.
    pub fn send_notification<T>(&mut self, dst: &actor::Addr, data: T) -> Result<(), crate::Error>
    where
        T: 'static + Send,
    {
        dst.receive_notification(data)
    }

    pub fn schedule_until(&mut self, timer: &mut Timer, instant: Instant) {
        self.timeout_scheduler
            .schedule_until(timer, instant, self.own_actor_id);
    }

    /// Schedule a timer for a given duration.
    pub fn schedule_for(&mut self, timer: &mut Timer, duration: Duration) {
        // insert timer
        self.schedule_until(timer, self.instant_source.now() + duration);
    }

    /// Unschedule a timer.
    pub fn unschedule(&mut self, timer: &mut Timer) {
        self.timeout_scheduler.unschedule(timer, self.own_actor_id);
        // find in the list from the most recent and remove
    }

    /// Return the current time.
    pub fn now(&self) -> Instant {
        self.instant_source.now()
    }

    pub(crate) fn request_id_counter(&self) -> RequestId {
        self.request_id_counter
    }

    /// If one timer is mature send a notification for it.
    ///
    /// Return ControlFlow::Continue(()) if a timeout was sent. If not,
    /// return ControlFlow::Break(duration) with the waiting time to the next
    /// timeout or Duration::MAX if there is no timeout.
    pub(crate) fn try_send_next_pending_timeout(&mut self) -> ControlFlow<Duration, ()> {
        match self.timeout_scheduler.timeout_list.iter().next() {
            Some((key, reactive_id)) => {
                let duration_to_next = key.deadline.saturating_sub(&self.now());
                // if timeout is ready
                if duration_to_next == Duration::ZERO {
                    {
                        let key_copy = *key;
                        let reactive_id_copy = *reactive_id;
                        self.timeout_scheduler
                            .timeout_list
                            .remove(&key_copy)
                            .unwrap();

                        // try to send the notification
                        match self.tx.try_send(MessageAndDstId {
                            message: Message::Notification(Notification {
                                data: Box::new(Timeout(key_copy.id)),
                            }),
                            dst_id: reactive_id_copy,
                        }) {
                            // if send ok, continue to process messages
                            Ok(_) => ControlFlow::Continue(()),
                            // if send failed, store back the timeout and let the processing
                            // of message solve the problem (detect queue disconnect or make space if full)
                            Err(_) => {
                                self.timeout_scheduler
                                    .timeout_list
                                    .insert(key_copy, reactive_id_copy);
                                ControlFlow::Continue(())
                            }
                        }
                    }
                } else {
                    // If timeout not ready, break to block on the queue for the needed duration.
                    ControlFlow::Break(duration_to_next)
                }
            }
            // If no timeout, break to wait indefinitely new messages on the queue
            None => ControlFlow::Break(Duration::MAX),
        }
    }
}

impl Instant {
    pub const INFINITY: Instant = Instant(InternalInstant::Infinity);

    /// Return true if the instant represent infinity.
    ///
    /// This is the case for `Instant::INFINITY` or `now() + Duration::MAX`.
    pub fn at_inf(&self) -> bool {
        match self.0 {
            InternalInstant::Finite(_) => false,
            InternalInstant::Infinity => true,
        }
    }

    /// Set the instant to Instant::INFINITY.
    pub fn set_inf(&mut self) {
        self.0 = InternalInstant::Infinity;
    }

    pub fn new(instant: time::Instant) -> Instant {
        Instant(InternalInstant::Finite(instant))
    }

    pub(crate) fn internal(&self) -> &InternalInstant {
        &self.0
    }

    /// Subtract two instants and saturate to Duration::ZERO.
    pub fn saturating_sub(&self, rhs: &Instant) -> Duration {
        match self.internal() {
            InternalInstant::Finite(self_internal) => match rhs.internal() {
                InternalInstant::Finite(rhs_internal) => {
                    if self_internal < rhs_internal {
                        Duration::ZERO
                    } else {
                        self_internal.duration_since(*rhs_internal)
                    }
                }
                InternalInstant::Infinity => Duration::ZERO,
            },
            InternalInstant::Infinity => match rhs.internal() {
                InternalInstant::Finite(_) => Duration::MAX,
                InternalInstant::Infinity => panic!(),
            },
        }
    }
}

#[cfg(test)]
mod instant_tests {
    use super::*;

    #[test]
    fn test_instant_is_inf() {
        let begin = Instant::new(std::time::Instant::now());

        assert!(!begin.at_inf());
        assert!((begin + Duration::MAX).at_inf());
        assert!(Instant::INFINITY.at_inf());
    }

    #[test]
    fn test_instant_sub() {
        let begin = std::time::Instant::now();

        let a = Instant::new(begin);
        let b = a + Duration::from_secs(13);

        assert!(b.saturating_sub(&a) == Duration::from_secs(13));
        assert!(a.saturating_sub(&b) == Duration::ZERO);

        assert!(Instant::INFINITY.saturating_sub(&a) == Duration::MAX);
        assert!(b.saturating_sub(&Instant::INFINITY) == Duration::ZERO);
    }

    #[cfg(test)]
    #[test]
    #[should_panic]
    fn test_instant_inf_sub_inf() {
        Instant::INFINITY.saturating_sub(&Instant::INFINITY);
    }
}

impl Add<Duration> for Instant {
    type Output = Instant;
    fn add(self, other: Duration) -> Instant {
        if other == Duration::MAX {
            Instant(InternalInstant::Infinity)
        } else {
            match self.0 {
                InternalInstant::Finite(internal) => {
                    Instant(InternalInstant::Finite(internal + other))
                }
                InternalInstant::Infinity => Instant(InternalInstant::Infinity),
            }
        }
    }
}

impl PartialEq<Instant> for Instant {
    fn eq(&self, other: &Instant) -> bool {
        match self.0 {
            InternalInstant::Finite(internal) => match other.0 {
                InternalInstant::Finite(other_internal) => internal == other_internal,
                InternalInstant::Infinity => false,
            },
            InternalInstant::Infinity => match other.0 {
                InternalInstant::Finite(_) => false,
                InternalInstant::Infinity => true,
            },
        }
    }
}

impl PartialOrd<Instant> for Instant {
    fn partial_cmp(&self, other: &Instant) -> Option<Ordering> {
        match self.0 {
            InternalInstant::Finite(internal) => match other.0 {
                InternalInstant::Finite(other_internal) => internal.partial_cmp(&other_internal),
                InternalInstant::Infinity => Some(Ordering::Less),
            },
            InternalInstant::Infinity => match other.0 {
                InternalInstant::Finite(_) => Some(Ordering::Greater),
                InternalInstant::Infinity => Some(Ordering::Equal),
            },
        }
    }
}

////////////////////////////// internal impl's /////////////////////////////////////

impl InternalInstant {
    pub(crate) fn into_instant(self) -> crate::Instant {
        Instant(self)
    }
}

impl ReactiveAddr {
    pub(crate) fn new(tx: mpsc::SyncSender<MessageAndDstId>, dst_id: actor::ActorId) -> Self {
        Self { tx, dst_id }
    }

    pub(crate) fn into_addr(self) -> actor::Addr {
        actor::Addr::from_kind(AddrKind::Reactive(self))
    }
    pub(crate) fn actor_id(&self) -> actor::ActorId {
        self.dst_id
    }
    pub(crate) fn receive_notification<T>(&self, data: T) -> Result<(), actor::Error>
    where
        T: 'static + Send + Sized,
    {
        let message = MessageAndDstId {
            dst_id: self.dst_id,
            message: Message::Notification(actor::Notification {
                data: Box::new(data),
            }),
        };

        match self.tx.try_send(message) {
            Ok(_) => Result::Ok(()),
            Err(err) => Result::Err(match err {
                mpsc::TrySendError::Full(_) => actor::Error::QueueFull,
                mpsc::TrySendError::Disconnected(..) => actor::Error::AddrUnreachable,
            }),
        }
    }

    pub fn receive_request<T>(&self, src: &actor::Addr, id: actor::RequestId, data: T)
    where
        T: 'static + Send + Sized,
    {
        let message = MessageAndDstId {
            dst_id: self.dst_id,
            message: Message::Request(actor::Request {
                src: src.clone(),
                id,
                data: Box::new(data),
            }),
        };

        if let Err(err) = self.tx.try_send(message) {
            let (actor_err, returned_data) = match err {
                mpsc::TrySendError::Full(a_data) => (actor::Error::QueueFull, a_data),
                mpsc::TrySendError::Disconnected(a_data) => (actor::Error::AddrUnreachable, a_data),
            };
            // try to send an error response to himself
            let _ = src.receive_err_response(
                id,
                actor::NonBoxedErrorStatus {
                    error: actor_err,
                    request_data: returned_data.message,
                },
            );
        }
    }

    pub(super) fn receive_ok_response<T>(
        &self,
        request_id: RequestId,
        result: T,
    ) -> Result<(), actor::Error>
    where
        T: 'static + Send + Sized,
    {
        let response = actor::Response {
            request_id,
            result: Result::Ok(Box::new(result)),
        };

        let message_and_dst_id = MessageAndDstId {
            dst_id: self.dst_id,
            message: actor::Message::Response(response),
        };

        match self.tx.try_send(message_and_dst_id) {
            Ok(_) => Result::Ok(()),
            Err(err) => Result::Err(match err {
                mpsc::TrySendError::Full(_) => actor::Error::QueueFull,
                mpsc::TrySendError::Disconnected(..) => actor::Error::AddrUnreachable,
            }),
        }
    }

    pub(super) fn receive_err_response<T>(
        &self,
        request_id: RequestId,
        result: actor::NonBoxedErrorStatus<T>,
    ) -> Result<(), actor::Error>
    where
        T: 'static + Send + Sized,
    {
        let boxed_result = actor::ErrorStatus {
            error: result.error,
            request_data: Box::new(result.request_data),
        };

        let response = actor::Response {
            request_id,
            result: Result::Err(boxed_result),
        };

        let message_and_dst_id = MessageAndDstId {
            dst_id: self.dst_id,
            message: actor::Message::Response(response),
        };

        match self.tx.try_send(message_and_dst_id) {
            Ok(_) => Result::Ok(()),
            Err(err) => Result::Err(match err {
                mpsc::TrySendError::Full(_) => actor::Error::QueueFull,
                mpsc::TrySendError::Disconnected(..) => actor::Error::AddrUnreachable,
            }),
        }
    }
}

impl TimeoutScheduler {
    pub(crate) fn new() -> TimeoutScheduler {
        TimeoutScheduler {
            next_timeout_id: 0,
            timeout_list: BTreeMap::new(),
        }
    }

    fn generate_timeout_id(&mut self) -> TimeoutId {
        let out = self.next_timeout_id;
        self.next_timeout_id = self.next_timeout_id.wrapping_add(1);
        out
    }

    /// Schedule a timer at a point in the future.
    pub(crate) fn schedule_until(
        &mut self,
        timer: &mut Timer,
        instant: Instant,
        dst: actor::ActorId,
    ) {
        self.unschedule(timer, dst);

        timer.id = self.generate_timeout_id();
        timer.deadline = instant;
        self.timeout_list.insert(*timer, dst);
        assert!(!self.timeout_list.is_empty());
    }

    /// Remove the timer to the scheduled list if present.
    pub(crate) fn unschedule(&mut self, timer: &mut Timer, dst: actor::ActorId) {
        if !timer.deadline.at_inf() {
            match self.timeout_list.entry(*timer) {
                std::collections::btree_map::Entry::Vacant(_) => (),
                std::collections::btree_map::Entry::Occupied(occupied_entry) => {
                    if *occupied_entry.get() == dst {
                        occupied_entry.remove();
                    }
                }
            }
            timer.deadline.set_inf();
        }
    }
}

impl Timer {
    /// Create an unscheduled timer.
    pub fn new() -> Timer {
        Timer {
            id: 0,
            deadline: Instant::INFINITY,
        }
    }

    /// Check that a notification was created to schedule this timer timeout event.
    ///
    /// The method must always be used to check if the code that the timer should trigger
    /// needs to be executed. It takes care of race conditions like timer unscheduled after
    /// the timeout notification was send to the queue.
    pub fn is_scheduling(&mut self, notif: &Notification) -> bool {
        match notif.data.downcast_ref::<Timeout>() {
            Some(timeout) => {
                if timeout.0 == self.id {
                    self.deadline.set_inf();
                    true
                } else {
                    false
                }
            }
            None => false,
        }
    }
}

impl Default for Timer {
    fn default() -> Self {
        Timer::new()
    }
}

impl std::cmp::Ord for Timer {
    fn cmp(&self, other: &Self) -> Ordering {
        match self.deadline.partial_cmp(&other.deadline) {
            Some(Ordering::Greater) => Ordering::Greater,
            Some(Ordering::Less) => Ordering::Less,
            _ => self.id.cmp(&other.id),
        }
    }
}

impl std::cmp::PartialOrd for Timer {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl std::cmp::Eq for Timer {}

impl std::cmp::PartialEq for Timer {
    fn eq(&self, other: &Self) -> bool {
        self.id == other.id && self.deadline == other.deadline
    }
}

////////////////////////////// tests /////////////////////////////////////

#[cfg(test)]
mod tests {

    use std::mem;

    use super::*;

    #[test]
    fn size_of_objects() {
        assert!(mem::size_of::<mpsc::SyncSender<Message>>() <= 16);
        assert!(mem::size_of::<Message>() <= 56);
        assert!(mem::size_of::<actor::Request>() <= 56);
        assert!(mem::size_of::<actor::Response>() <= 40);
        assert!(mem::size_of::<actor::Notification>() <= 16);
        assert!(mem::size_of::<actor::Addr>() <= 32);
        assert!(mem::size_of::<ReactiveAddr>() <= 24);
    }

    #[test]
    fn test_timer_compare() {
        let begin = Instant::new(time::Instant::now());
        let mut end;
        loop {
            end = Instant::new(time::Instant::now());
            if end.saturating_sub(&begin) > Duration::ZERO {
                break;
            }
        }

        assert!(
            Timer {
                id: 345,
                deadline: begin
            } == Timer {
                id: 345,
                deadline: begin
            }
        );
        assert!(
            Timer {
                id: 1,
                deadline: begin
            } > Timer {
                id: 0,
                deadline: begin
            }
        );

        assert!(
            Timer {
                id: 13,
                deadline: begin
            } < Timer {
                id: 45,
                deadline: end
            }
        );
        assert!(
            Timer {
                id: 13,
                deadline: end
            } > Timer {
                id: 45,
                deadline: begin
            }
        );

        assert!(
            Timer {
                id: 0,
                deadline: InternalInstant::Infinity.into_instant()
            } > Timer {
                id: u32::MAX,
                deadline: begin
            }
        );

        assert!(
            Timer {
                id: 1234567,
                deadline: InternalInstant::Infinity.into_instant()
            } < Timer {
                id: 1234568,
                deadline: InternalInstant::Infinity.into_instant()
            }
        );
        assert!(
            Timer {
                id: 55555,
                deadline: InternalInstant::Infinity.into_instant()
            } == Timer {
                id: 55555,
                deadline: InternalInstant::Infinity.into_instant()
            }
        );
    }
}