Skip to main content

wa_wire_contract/
path.rs

1//! Addressing a node inside a frame.
2//!
3//! A path is the list of child indices from the root node. Correlating a
4//! plaintext to its `<enc>` by path rather than by ordinal survives an engine
5//! reordering or filtering children, and rather than by buffer offset because
6//! the Go and TypeScript decoders do not expose offsets — and adapters are
7//! meant to stay dumb.
8
9use core::fmt;
10
11/// A borrowed node path: little-endian `u16` components over the envelope's
12/// own buffer.
13///
14/// Holding the raw bytes rather than a `&[u16]` avoids both an alignment
15/// requirement the envelope cannot guarantee and a copy the boundary does not
16/// need.
17#[derive(Clone, Copy, PartialEq, Eq, Hash)]
18pub struct NodePath<'a> {
19    bytes: &'a [u8],
20}
21
22impl<'a> NodePath<'a> {
23    /// Wrap the little-endian component bytes of a path.
24    ///
25    /// `bytes.len()` must be even; the decoder only ever produces such slices.
26    /// An odd length drops the trailing half-component here, at construction,
27    /// rather than at each read: a path whose byte count disagreed with its
28    /// component count would encode a length prefix the decoder then uses to
29    /// take fewer bytes than were written, shifting every field after it.
30    #[must_use]
31    pub const fn from_le_bytes(bytes: &'a [u8]) -> Self {
32        // `& !1` rounds down to the nearest even length without arithmetic
33        // that could underflow on an empty slice.
34        let (whole, _odd_tail) = bytes.split_at(bytes.len() & !1);
35        Self { bytes: whole }
36    }
37
38    /// The root node itself.
39    #[must_use]
40    pub const fn root() -> Self {
41        Self { bytes: &[] }
42    }
43
44    /// Number of components.
45    #[must_use]
46    pub const fn len(self) -> usize {
47        self.bytes.len() / 2
48    }
49
50    /// Whether this path addresses the root node.
51    #[must_use]
52    pub const fn is_empty(self) -> bool {
53        self.len() == 0
54    }
55
56    /// The component at `index`, if present.
57    #[must_use]
58    pub fn get(self, index: usize) -> Option<u16> {
59        let start = index.checked_mul(2)?;
60        let end = start.checked_add(2)?;
61        let pair = self.bytes.get(start..end)?;
62        // `get` guaranteed exactly two bytes.
63        let (lo, hi) = (*pair.first()?, *pair.get(1)?);
64        Some(u16::from_le_bytes([lo, hi]))
65    }
66
67    /// Iterate the components from the root downwards.
68    ///
69    /// `as_chunks` yields fixed-size pairs, so decoding needs no fallible step
70    /// and a trailing odd byte is simply not a component.
71    pub fn iter(self) -> impl Iterator<Item = u16> + 'a {
72        let (pairs, _odd_tail) = self.bytes.as_chunks::<2>();
73        pairs.iter().copied().map(u16::from_le_bytes)
74    }
75
76    /// The underlying little-endian bytes.
77    #[must_use]
78    pub const fn as_le_bytes(self) -> &'a [u8] {
79        self.bytes
80    }
81
82    /// Whether `self` is `other` or a node beneath it.
83    #[must_use]
84    pub fn starts_with(self, other: NodePath<'_>) -> bool {
85        let prefix = other.len();
86        if prefix > self.len() {
87            return false;
88        }
89        self.iter()
90            .zip(other.iter())
91            .take(prefix)
92            .all(|(a, b)| a == b)
93    }
94}
95
96impl<'a> IntoIterator for NodePath<'a> {
97    type Item = u16;
98    type IntoIter =
99        core::iter::Map<core::iter::Copied<core::slice::Iter<'a, [u8; 2]>>, fn([u8; 2]) -> u16>;
100
101    fn into_iter(self) -> Self::IntoIter {
102        let (pairs, _odd_tail) = self.bytes.as_chunks::<2>();
103        pairs.iter().copied().map(u16::from_le_bytes as _)
104    }
105}
106
107impl fmt::Debug for NodePath<'_> {
108    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
109        f.debug_list().entries(self.iter()).finish()
110    }
111}
112
113impl fmt::Display for NodePath<'_> {
114    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
115        if self.is_empty() {
116            return f.write_str("/");
117        }
118        for component in self.iter() {
119            write!(f, "/{component}")?;
120        }
121        Ok(())
122    }
123}
124
125#[cfg(test)]
126mod tests {
127    use super::*;
128    extern crate alloc;
129    use alloc::string::ToString;
130    use alloc::vec::Vec;
131
132    fn path_bytes(components: &[u16]) -> Vec<u8> {
133        components
134            .iter()
135            .flat_map(|c| c.to_le_bytes())
136            .collect::<Vec<_>>()
137    }
138
139    #[test]
140    fn root_is_empty() {
141        let root = NodePath::root();
142        assert!(root.is_empty());
143        assert_eq!(root.len(), 0);
144        assert_eq!(root.get(0), None);
145        assert_eq!(root.iter().count(), 0);
146        assert_eq!(root.to_string(), "/");
147    }
148
149    #[test]
150    fn components_round_trip_little_endian() {
151        let components = [0u16, 1, 258, 0xFFFF, 7];
152        let bytes = path_bytes(&components);
153        let path = NodePath::from_le_bytes(&bytes);
154
155        assert_eq!(path.len(), components.len());
156        assert!(!path.is_empty());
157        assert_eq!(path.iter().collect::<Vec<_>>(), components);
158        assert_eq!(path.into_iter().collect::<Vec<_>>(), components);
159        for (i, want) in components.iter().enumerate() {
160            assert_eq!(path.get(i), Some(*want));
161        }
162        assert_eq!(path.get(components.len()), None);
163        assert_eq!(path.as_le_bytes(), bytes.as_slice());
164    }
165
166    #[test]
167    fn odd_length_truncates_instead_of_panicking() {
168        // Not produced by the decoder, but the type must stay total.
169        let path = NodePath::from_le_bytes(&[1, 0, 2]);
170        assert_eq!(path.len(), 1);
171        assert_eq!(path.iter().collect::<Vec<_>>(), [1]);
172        assert_eq!(path.get(1), None);
173        // The bytes are truncated too, not just the count. The encoder writes
174        // `len()` as the prefix and `as_le_bytes()` as the body, so the two
175        // disagreeing would shift every field after the path.
176        assert_eq!(path.as_le_bytes(), [1, 0]);
177    }
178
179    #[test]
180    fn get_rejects_indices_that_would_overflow() {
181        let bytes = path_bytes(&[1, 2]);
182        let path = NodePath::from_le_bytes(&bytes);
183        assert_eq!(path.get(usize::MAX), None);
184        assert_eq!(path.get(usize::MAX / 2), None);
185    }
186
187    #[test]
188    fn starts_with_matches_ancestry() {
189        let child = path_bytes(&[1, 2, 3]);
190        let parent = path_bytes(&[1, 2]);
191        let sibling = path_bytes(&[1, 3]);
192        let deeper = path_bytes(&[1, 2, 3, 4]);
193
194        let child = NodePath::from_le_bytes(&child);
195        let parent = NodePath::from_le_bytes(&parent);
196        let sibling = NodePath::from_le_bytes(&sibling);
197        let deeper = NodePath::from_le_bytes(&deeper);
198
199        assert!(child.starts_with(parent));
200        assert!(child.starts_with(child));
201        assert!(child.starts_with(NodePath::root()));
202        assert!(!child.starts_with(sibling));
203        assert!(!parent.starts_with(child));
204        assert!(!child.starts_with(deeper));
205    }
206
207    #[test]
208    fn display_and_debug_are_readable() {
209        let bytes = path_bytes(&[0, 12, 5]);
210        let path = NodePath::from_le_bytes(&bytes);
211        assert_eq!(path.to_string(), "/0/12/5");
212        assert_eq!(alloc::format!("{path:?}"), "[0, 12, 5]");
213    }
214
215    #[test]
216    fn equality_is_by_value() {
217        let a = path_bytes(&[1, 2]);
218        let b = path_bytes(&[1, 2]);
219        let c = path_bytes(&[1, 3]);
220        assert_eq!(NodePath::from_le_bytes(&a), NodePath::from_le_bytes(&b));
221        assert_ne!(NodePath::from_le_bytes(&a), NodePath::from_le_bytes(&c));
222    }
223}