Skip to main content

icedwright_trace/
ids.rs

1//! Trace-only index and ordinal newtypes, and the raw ids the writer renumbers into them.
2//!
3//! iced's window and widget ids and the harness's task and subscription ids come from
4//! process-wide counters, so their values depend on what else ran first. The writer maps each
5//! raw id to an ordinal in order of first appearance, which is the same on every run.
6
7use core::fmt;
8use std::collections::BTreeMap;
9
10use serde::{Deserialize, Serialize};
11
12macro_rules! ordinal {
13    ($(#[$doc:meta])* $name:ident, $prefix:literal) => {
14        $(#[$doc])*
15        #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
16        #[serde(transparent)]
17        pub struct $name(u32);
18
19        impl $name {
20            /// The position, counting from zero.
21            #[must_use]
22            pub const fn get(self) -> u32 {
23                self.0
24            }
25
26            pub(crate) const fn from_index(index: u32) -> Self {
27                Self(index)
28            }
29        }
30
31        impl fmt::Display for $name {
32            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
33                write!(f, concat!($prefix, "{}"), self.0)
34            }
35        }
36    };
37}
38
39ordinal!(
40    /// The position of a step in its trace.
41    StepIndex,
42    "step "
43);
44ordinal!(
45    /// A window, numbered in the order the trace first saw it.
46    WindowOrdinal,
47    "window "
48);
49ordinal!(
50    /// A widget with a generated id, numbered in the order the trace first saw it.
51    WidgetOrdinal,
52    "widget "
53);
54ordinal!(
55    /// A task, numbered in the order the trace first saw it.
56    TaskOrdinal,
57    "task "
58);
59ordinal!(
60    /// A subscription, numbered in the order the trace first saw it.
61    SubscriptionOrdinal,
62    "subscription "
63);
64
65mod sealed {
66    pub trait Sealed {}
67}
68
69/// A raw id from a process-wide counter. The ordinal it renumbers to follows from its type.
70pub trait RawId: Copy + sealed::Sealed {
71    /// The per-trace ordinal this kind of id becomes.
72    type Ordinal: Copy;
73
74    #[doc(hidden)]
75    fn __slot(self) -> (usize, u64);
76
77    #[doc(hidden)]
78    fn __ordinal(index: u32) -> Self::Ordinal;
79}
80
81macro_rules! raw_id {
82    ($(#[$doc:meta])* $name:ident => $ordinal:ident, $slot:literal) => {
83        $(#[$doc])*
84        #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
85        pub struct $name(pub u64);
86
87        impl sealed::Sealed for $name {}
88
89        impl RawId for $name {
90            type Ordinal = $ordinal;
91
92            fn __slot(self) -> (usize, u64) {
93                ($slot, self.0)
94            }
95
96            fn __ordinal(index: u32) -> $ordinal {
97                $ordinal::from_index(index)
98            }
99        }
100    };
101}
102
103raw_id!(
104    /// The counter value inside an iced `window::Id`.
105    RawWindowId => WindowOrdinal, 0
106);
107raw_id!(
108    /// The counter value inside an iced `widget::Id::unique()`.
109    RawWidgetId => WidgetOrdinal, 1
110);
111raw_id!(
112    /// The harness executor's id for a task.
113    RawTaskId => TaskOrdinal, 2
114);
115raw_id!(
116    /// The harness's id for a subscription.
117    RawSubscriptionId => SubscriptionOrdinal, 3
118);
119
120/// First-appearance numbering, one sequence per kind of id.
121#[derive(Debug, Default, Clone)]
122pub(crate) struct Renumbering {
123    seen: [BTreeMap<u64, u32>; 4],
124}
125
126impl Renumbering {
127    pub(crate) fn ordinal<I: RawId>(&mut self, raw: I) -> I::Ordinal {
128        let (slot, value) = raw.__slot();
129        let Some(map) = self.seen.get_mut(slot) else {
130            return I::__ordinal(u32::MAX);
131        };
132        let next = u32::try_from(map.len()).unwrap_or(u32::MAX);
133        I::__ordinal(*map.entry(value).or_insert(next))
134    }
135}
136
137#[cfg(test)]
138mod tests {
139    use super::*;
140
141    #[test]
142    fn ordinals_follow_first_appearance_per_kind() {
143        let mut ids = Renumbering::default();
144        assert_eq!(ids.ordinal(RawWindowId(77)), WindowOrdinal(0));
145        assert_eq!(ids.ordinal(RawWindowId(12)), WindowOrdinal(1));
146        assert_eq!(ids.ordinal(RawWindowId(77)), WindowOrdinal(0));
147        assert_eq!(ids.ordinal(RawTaskId(77)), TaskOrdinal(0));
148        assert_eq!(ids.ordinal(RawWidgetId(5)), WidgetOrdinal(0));
149        assert_eq!(ids.ordinal(RawSubscriptionId(5)), SubscriptionOrdinal(0));
150        assert_eq!(ids.ordinal(RawTaskId(3)), TaskOrdinal(1));
151    }
152
153    #[test]
154    fn different_raw_values_give_the_same_ordinals() {
155        let mut first = Renumbering::default();
156        let mut second = Renumbering::default();
157        let a: Vec<_> = [9, 4, 9].map(|raw| first.ordinal(RawWindowId(raw))).into();
158        let b: Vec<_> = [130, 131, 130]
159            .map(|raw| second.ordinal(RawWindowId(raw)))
160            .into();
161        assert_eq!(a, b);
162    }
163
164    #[test]
165    fn display_and_serde() -> Result<(), serde_json::Error> {
166        assert_eq!(StepIndex(3).to_string(), "step 3");
167        assert_eq!(TaskOrdinal(1).to_string(), "task 1");
168        assert_eq!(serde_json::to_string(&WindowOrdinal(2))?, "2");
169        assert_eq!(serde_json::from_str::<StepIndex>("4")?.get(), 4);
170        Ok(())
171    }
172}