icedwright-trace 0.0.1

The icedwright trace format: a deterministic .iwtrace archive of every step a test took, with its writer, reader and comparison
Documentation
//! Trace-only index and ordinal newtypes, and the raw ids the writer renumbers into them.
//!
//! iced's window and widget ids and the harness's task and subscription ids come from
//! process-wide counters, so their values depend on what else ran first. The writer maps each
//! raw id to an ordinal in order of first appearance, which is the same on every run.

use core::fmt;
use std::collections::BTreeMap;

use serde::{Deserialize, Serialize};

macro_rules! ordinal {
    ($(#[$doc:meta])* $name:ident, $prefix:literal) => {
        $(#[$doc])*
        #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
        #[serde(transparent)]
        pub struct $name(u32);

        impl $name {
            /// The position, counting from zero.
            #[must_use]
            pub const fn get(self) -> u32 {
                self.0
            }

            pub(crate) const fn from_index(index: u32) -> Self {
                Self(index)
            }
        }

        impl fmt::Display for $name {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                write!(f, concat!($prefix, "{}"), self.0)
            }
        }
    };
}

ordinal!(
    /// The position of a step in its trace.
    StepIndex,
    "step "
);
ordinal!(
    /// A window, numbered in the order the trace first saw it.
    WindowOrdinal,
    "window "
);
ordinal!(
    /// A widget with a generated id, numbered in the order the trace first saw it.
    WidgetOrdinal,
    "widget "
);
ordinal!(
    /// A task, numbered in the order the trace first saw it.
    TaskOrdinal,
    "task "
);
ordinal!(
    /// A subscription, numbered in the order the trace first saw it.
    SubscriptionOrdinal,
    "subscription "
);

mod sealed {
    pub trait Sealed {}
}

/// A raw id from a process-wide counter. The ordinal it renumbers to follows from its type.
pub trait RawId: Copy + sealed::Sealed {
    /// The per-trace ordinal this kind of id becomes.
    type Ordinal: Copy;

    #[doc(hidden)]
    fn __slot(self) -> (usize, u64);

    #[doc(hidden)]
    fn __ordinal(index: u32) -> Self::Ordinal;
}

macro_rules! raw_id {
    ($(#[$doc:meta])* $name:ident => $ordinal:ident, $slot:literal) => {
        $(#[$doc])*
        #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
        pub struct $name(pub u64);

        impl sealed::Sealed for $name {}

        impl RawId for $name {
            type Ordinal = $ordinal;

            fn __slot(self) -> (usize, u64) {
                ($slot, self.0)
            }

            fn __ordinal(index: u32) -> $ordinal {
                $ordinal::from_index(index)
            }
        }
    };
}

raw_id!(
    /// The counter value inside an iced `window::Id`.
    RawWindowId => WindowOrdinal, 0
);
raw_id!(
    /// The counter value inside an iced `widget::Id::unique()`.
    RawWidgetId => WidgetOrdinal, 1
);
raw_id!(
    /// The harness executor's id for a task.
    RawTaskId => TaskOrdinal, 2
);
raw_id!(
    /// The harness's id for a subscription.
    RawSubscriptionId => SubscriptionOrdinal, 3
);

/// First-appearance numbering, one sequence per kind of id.
#[derive(Debug, Default, Clone)]
pub(crate) struct Renumbering {
    seen: [BTreeMap<u64, u32>; 4],
}

impl Renumbering {
    pub(crate) fn ordinal<I: RawId>(&mut self, raw: I) -> I::Ordinal {
        let (slot, value) = raw.__slot();
        let Some(map) = self.seen.get_mut(slot) else {
            return I::__ordinal(u32::MAX);
        };
        let next = u32::try_from(map.len()).unwrap_or(u32::MAX);
        I::__ordinal(*map.entry(value).or_insert(next))
    }
}

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

    #[test]
    fn ordinals_follow_first_appearance_per_kind() {
        let mut ids = Renumbering::default();
        assert_eq!(ids.ordinal(RawWindowId(77)), WindowOrdinal(0));
        assert_eq!(ids.ordinal(RawWindowId(12)), WindowOrdinal(1));
        assert_eq!(ids.ordinal(RawWindowId(77)), WindowOrdinal(0));
        assert_eq!(ids.ordinal(RawTaskId(77)), TaskOrdinal(0));
        assert_eq!(ids.ordinal(RawWidgetId(5)), WidgetOrdinal(0));
        assert_eq!(ids.ordinal(RawSubscriptionId(5)), SubscriptionOrdinal(0));
        assert_eq!(ids.ordinal(RawTaskId(3)), TaskOrdinal(1));
    }

    #[test]
    fn different_raw_values_give_the_same_ordinals() {
        let mut first = Renumbering::default();
        let mut second = Renumbering::default();
        let a: Vec<_> = [9, 4, 9].map(|raw| first.ordinal(RawWindowId(raw))).into();
        let b: Vec<_> = [130, 131, 130]
            .map(|raw| second.ordinal(RawWindowId(raw)))
            .into();
        assert_eq!(a, b);
    }

    #[test]
    fn display_and_serde() -> Result<(), serde_json::Error> {
        assert_eq!(StepIndex(3).to_string(), "step 3");
        assert_eq!(TaskOrdinal(1).to_string(), "task 1");
        assert_eq!(serde_json::to_string(&WindowOrdinal(2))?, "2");
        assert_eq!(serde_json::from_str::<StepIndex>("4")?.get(), 4);
        Ok(())
    }
}