icedwright-protocol 0.1.0

Wire types for icedwright: the raw semantic tree a live app records and the typed remote protocol
Documentation
//! Newtypes so a generation, a frame count, a window ordinal and a task id cannot be swapped.

use core::time::Duration;

use serde::{Deserialize, Serialize};

macro_rules! id_newtype {
    ($($(#[doc = $doc:literal])+ $name:ident($inner:ty);)+) => {
        $(
            $(#[doc = $doc])+
            #[derive(
                Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Serialize,
                Deserialize,
            )]
            #[serde(transparent)]
            pub struct $name(pub $inner);
        )+
    };
}

id_newtype! {
    /// Rises whenever the app handles a message or the probe delivers an event.
    Generation(u64);
    /// Rises on every redraw.
    FrameCount(u64);
    /// A window on the wire, numbered in order of first appearance.
    WindowOrdinal(u32);
    /// A named task the probe is tracking.
    WireTaskId(u64);
    /// A task rule the client installed.
    WireRuleId(u64);
    /// Chosen by the client; a reply carries its request's id.
    RequestId(u64);
}

/// A real-time duration on the wire, in whole milliseconds.
#[derive(
    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Serialize, Deserialize,
)]
#[serde(transparent)]
pub struct WireDuration(pub u64);

impl From<Duration> for WireDuration {
    fn from(duration: Duration) -> Self {
        WireDuration(u64::try_from(duration.as_millis()).unwrap_or(u64::MAX))
    }
}

impl From<WireDuration> for Duration {
    fn from(duration: WireDuration) -> Self {
        Duration::from_millis(duration.0)
    }
}

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

    #[test]
    fn durations_convert_in_milliseconds() {
        assert_eq!(
            WireDuration::from(Duration::from_millis(1500)),
            WireDuration(1500)
        );
        assert_eq!(Duration::from(WireDuration(20)), Duration::from_millis(20));
        assert_eq!(WireDuration::from(Duration::MAX), WireDuration(u64::MAX));
    }
}