syntree/pointer.rs
1//! Pointer-related types and traits.
2
3use core::fmt;
4use core::hash;
5
6mod sealed {
7 pub trait Sealed {}
8}
9
10/// A pointer type that is derived from the pointer [Width].
11pub trait Pointer: Sized + Copy + hash::Hash + Eq + fmt::Debug + self::sealed::Sealed {
12 /// The largest pointer value. It is reserved to mark gap entries in the
13 /// token array, so no node is ever given it.
14 #[doc(hidden)]
15 const GAP: Self;
16
17 /// Test if the pointer can be the id of an interior node.
18 ///
19 /// Interior node ids leave the top bit clear, since a token stores its
20 /// trivia flag there next to its parent pointer, and the largest flagged
21 /// value is [`Pointer::GAP`].
22 #[doc(hidden)]
23 fn is_node_id(self) -> bool;
24
25 /// Set the flag bit on an optional node id, `None` included.
26 #[doc(hidden)]
27 fn flagged(this: Option<Self>) -> Option<Self>;
28
29 /// Test if the flag bit is set on an optional node id.
30 #[doc(hidden)]
31 fn is_flagged(this: Option<Self>) -> bool;
32
33 /// Clear the flag bit on an optional node id.
34 #[doc(hidden)]
35 fn unflagged(this: Option<Self>) -> Option<Self>;
36
37 /// Construct a pointer without checking that `value` is in bounds.
38 ///
39 /// # Safety
40 ///
41 /// The `value` must be in bounds for the pointer type, that is
42 /// [`Pointer::new(value)`][Pointer::new] must return `Some`.
43 #[doc(hidden)]
44 unsafe fn new_unchecked(value: usize) -> Self;
45
46 /// Safe constructor for the pointer.
47 ///
48 /// Returns [`None`] if the value provided is out of bounds for the pointer type.
49 ///
50 /// # Examples
51 ///
52 /// ```
53 /// use syntree::pointer::{Pointer, PointerU32};
54 ///
55 /// let v = PointerU32::new(0).ok_or("out of bounds")?;
56 /// assert_eq!(v.get(), 0);
57 /// let v = PointerU32::new(42).ok_or("out of bounds")?;
58 /// assert_eq!(v.get(), 42);
59 /// # Ok::<_, Box<dyn core::error::Error>>(())
60 /// ```
61 fn new(value: usize) -> Option<Self>;
62
63 /// Get the index of a pointer.
64 ///
65 /// # Examples
66 ///
67 /// ```
68 /// use syntree::pointer::{Pointer, PointerU32};
69 ///
70 /// let v = PointerU32::new(0).ok_or("out of bounds")?;
71 /// assert_eq!(v.get(), 0);
72 /// let v = PointerU32::new(42).ok_or("out of bounds")?;
73 /// assert_eq!(v.get(), 42);
74 /// # Ok::<_, Box<dyn core::error::Error>>(())
75 /// ```
76 fn get(self) -> usize;
77}
78
79/// A pointer width that can be used to reference other nodes.
80///
81/// This is determined by a primitive unsigned types such as `u32` or `usize`.
82pub trait Width: self::sealed::Sealed {
83 /// The pointer type associated with a specific width.
84 ///
85 /// # Examples
86 ///
87 /// ```
88 /// use syntree::pointer::Width;
89 ///
90 /// let tree = syntree::tree! {
91 /// "root1" => {},
92 /// "root2" => {},
93 /// };
94 ///
95 /// let root1 = tree.first().and_then(|n| n.into_node()).ok_or("missing root")?;
96 /// let root2 = tree.last().and_then(|n| n.into_node()).ok_or("missing root")?;
97 ///
98 /// let root1: <u32 as Width>::Pointer = root1.id();
99 /// let root2: <u32 as Width>::Pointer = root2.id();
100 ///
101 /// assert_ne!(root1, root2);
102 ///
103 /// # Ok::<_, Box<dyn core::error::Error>>(())
104 /// ```
105 type Pointer: Pointer;
106}
107
108macro_rules! implement {
109 ($ty:ident, $non_zero:ident, $e:ident) => {
110 impl Width for $ty {
111 type Pointer = $e;
112 }
113
114 use core::num::$non_zero;
115
116 impl self::sealed::Sealed for $ty {}
117 impl self::sealed::Sealed for $e {}
118
119 #[doc = concat!(" [`Pointer`] implementation for `", stringify!($ty), "`.")]
120 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
121 #[repr(transparent)]
122 pub struct $e($non_zero);
123
124 impl $e {
125 #[doc = concat!(" Safe constructor for the pointer.")]
126 ///
127 #[doc = concat!(" Returns [`None`] if the value provided is out of bounds for the pointer type.")]
128 ///
129 /// # Examples
130 ///
131 /// ```
132 /// use syntree::pointer::Pointer;
133 #[doc = concat!("use syntree::pointer::", stringify!($e), ";")]
134 ///
135 #[doc = concat!(" let v = ", stringify!($e), "::new(0).ok_or(\"out of bounds\")?;")]
136 /// assert_eq!(v.get(), 0);
137 #[doc = concat!(" let v = ", stringify!($e), "::new(42).ok_or(\"out of bounds\")?;")]
138 /// assert_eq!(v.get(), 42);
139 /// # Ok::<_, Box<dyn core::error::Error>>(())
140 /// ```
141 #[inline]
142 pub fn new(value: usize) -> Option<Self> {
143 let value = <$ty>::try_from(value).ok()?;
144 $non_zero::new(value.wrapping_add(1)).map(Self)
145 }
146
147 #[doc = concat!(" Get the index of a pointer.")]
148 ///
149 /// # Examples
150 ///
151 /// ```
152 /// use syntree::pointer::Pointer;
153 #[doc = concat!("use syntree::pointer::", stringify!($e), ";")]
154 ///
155 #[doc = concat!(" let v = ", stringify!($e), "::new(0).ok_or(\"out of bounds\")?;")]
156 /// assert_eq!(v.get(), 0);
157 #[doc = concat!(" let v = ", stringify!($e), "::new(42).ok_or(\"out of bounds\")?;")]
158 /// assert_eq!(v.get(), 42);
159 /// # Ok::<_, Box<dyn core::error::Error>>(())
160 /// ```
161 #[inline]
162 pub fn get(self) -> usize {
163 self.0.get().wrapping_sub(1) as usize
164 }
165 }
166
167 #[doc = concat!(" Pointer used for `", stringify!($ty), "` type.")]
168 ///
169 /// ```
170 /// use syntree::pointer::Pointer;
171 #[doc = concat!("use syntree::pointer::", stringify!($e), ";")]
172 ///
173 #[doc = concat!(" let v = ", stringify!($e), "::new(0).ok_or(\"out of bounds\")?;")]
174 /// assert_eq!(v.get(), 0);
175 #[doc = concat!(" let v = ", stringify!($e), "::new(42).ok_or(\"out of bounds\")?;")]
176 /// assert_eq!(v.get(), 42);
177 /// # Ok::<_, Box<dyn core::error::Error>>(())
178 /// ```
179 impl crate::pointer::Pointer for $e {
180 const GAP: Self = Self($non_zero::MAX);
181
182 #[inline]
183 fn is_node_id(self) -> bool {
184 // Flagging the id must neither wrap into the flag bit nor
185 // produce `GAP`.
186 self.0.get() < (<$ty>::MAX >> 1)
187 }
188
189 #[inline]
190 fn flagged(this: Option<Self>) -> Option<Self> {
191 let raw = this.map_or(0, |p| p.0.get());
192 $non_zero::new(raw | !(<$ty>::MAX >> 1)).map(Self)
193 }
194
195 #[inline]
196 fn is_flagged(this: Option<Self>) -> bool {
197 this.is_some_and(|p| p.0.get() & !(<$ty>::MAX >> 1) != 0)
198 }
199
200 #[inline]
201 fn unflagged(this: Option<Self>) -> Option<Self> {
202 let raw = this.map_or(0, |p| p.0.get());
203 $non_zero::new(raw & (<$ty>::MAX >> 1)).map(Self)
204 }
205
206 #[inline]
207 unsafe fn new_unchecked(value: usize) -> Self {
208 let value = value as $ty;
209 Self($non_zero::new_unchecked(value.wrapping_add(1)))
210 }
211
212 #[inline]
213 fn new(value: usize) -> Option<Self> {
214 $e::new(value)
215 }
216
217 #[inline]
218 fn get(self) -> usize {
219 $e::get(self)
220 }
221 }
222
223 /// Construct a default value.
224 ///
225 /// ```
226 /// use syntree::pointer::Pointer;
227 #[doc = concat!("use syntree::pointer::", stringify!($e), ";")]
228 ///
229 #[doc = concat!(" let v = ", stringify!($e), "::default();")]
230 /// assert_eq!(v.get(), 0);
231 /// ```
232 impl Default for $e {
233 #[inline]
234 fn default() -> Self {
235 Self($non_zero::MIN)
236 }
237 }
238
239 impl fmt::Debug for $e {
240 #[inline]
241 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
242 self.get().fmt(f)
243 }
244 }
245 };
246}
247
248implement!(usize, NonZeroUsize, PointerUsize);
249implement!(u8, NonZeroU8, PointerU8);
250implement!(u16, NonZeroU16, PointerU16);
251implement!(u32, NonZeroU32, PointerU32);
252implement!(u64, NonZeroU64, PointerU64);
253implement!(u128, NonZeroU128, PointerU128);