1use core::fmt;
10
11#[derive(Clone, Copy, PartialEq, Eq, Hash)]
18pub struct NodePath<'a> {
19 bytes: &'a [u8],
20}
21
22impl<'a> NodePath<'a> {
23 #[must_use]
31 pub const fn from_le_bytes(bytes: &'a [u8]) -> Self {
32 let (whole, _odd_tail) = bytes.split_at(bytes.len() & !1);
35 Self { bytes: whole }
36 }
37
38 #[must_use]
40 pub const fn root() -> Self {
41 Self { bytes: &[] }
42 }
43
44 #[must_use]
46 pub const fn len(self) -> usize {
47 self.bytes.len() / 2
48 }
49
50 #[must_use]
52 pub const fn is_empty(self) -> bool {
53 self.len() == 0
54 }
55
56 #[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 let (lo, hi) = (*pair.first()?, *pair.get(1)?);
64 Some(u16::from_le_bytes([lo, hi]))
65 }
66
67 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 #[must_use]
78 pub const fn as_le_bytes(self) -> &'a [u8] {
79 self.bytes
80 }
81
82 #[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 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 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}