Skip to main content

icedwright_protocol/
ids.rs

1//! Newtypes so a generation, a frame count, a window ordinal and a task id cannot be swapped.
2
3use core::time::Duration;
4
5use serde::{Deserialize, Serialize};
6
7macro_rules! id_newtype {
8    ($($(#[doc = $doc:literal])+ $name:ident($inner:ty);)+) => {
9        $(
10            $(#[doc = $doc])+
11            #[derive(
12                Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Serialize,
13                Deserialize,
14            )]
15            #[serde(transparent)]
16            pub struct $name(pub $inner);
17        )+
18    };
19}
20
21id_newtype! {
22    /// Rises whenever the app handles a message or the probe delivers an event.
23    Generation(u64);
24    /// Rises on every redraw.
25    FrameCount(u64);
26    /// A window on the wire, numbered in order of first appearance.
27    WindowOrdinal(u32);
28    /// A named task the probe is tracking.
29    WireTaskId(u64);
30    /// A task rule the client installed.
31    WireRuleId(u64);
32    /// Chosen by the client; a reply carries its request's id.
33    RequestId(u64);
34}
35
36/// A real-time duration on the wire, in whole milliseconds.
37#[derive(
38    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Serialize, Deserialize,
39)]
40#[serde(transparent)]
41pub struct WireDuration(pub u64);
42
43impl From<Duration> for WireDuration {
44    fn from(duration: Duration) -> Self {
45        WireDuration(u64::try_from(duration.as_millis()).unwrap_or(u64::MAX))
46    }
47}
48
49impl From<WireDuration> for Duration {
50    fn from(duration: WireDuration) -> Self {
51        Duration::from_millis(duration.0)
52    }
53}
54
55#[cfg(test)]
56mod tests {
57    use super::*;
58
59    #[test]
60    fn durations_convert_in_milliseconds() {
61        assert_eq!(
62            WireDuration::from(Duration::from_millis(1500)),
63            WireDuration(1500)
64        );
65        assert_eq!(Duration::from(WireDuration(20)), Duration::from_millis(20));
66        assert_eq!(WireDuration::from(Duration::MAX), WireDuration(u64::MAX));
67    }
68}