syntree/flavor.rs
1//! Trait for defining the flavor of a syntree.
2
3use core::ops::DerefMut;
4
5use crate::index::{Index, Length};
6use crate::pointer::{Pointer, Width};
7
8/// Storage being used in a tree.
9pub trait Storage<T>
10where
11 Self: Sized + DerefMut<Target = [T]>,
12{
13 /// A storage error.
14 type Error: 'static;
15
16 /// Empty storage.
17 const EMPTY: Self;
18
19 /// Construct storage with the given capacity.
20 ///
21 /// Fixed-capacity storage should error if `capacity` doesn't fit.
22 fn with_capacity(capacity: usize) -> Result<Self, Self::Error>;
23
24 /// Get the capacity of the underlying storage.
25 fn capacity(&self) -> usize;
26
27 /// Reserve capacity for at least `additional` more items.
28 ///
29 /// This is a hint. The default does nothing, fixed-capacity storage may
30 /// error if `additional` more items don't fit.
31 #[inline]
32 fn reserve(&mut self, additional: usize) -> Result<(), Self::Error> {
33 _ = additional;
34 Ok(())
35 }
36
37 /// Push an item into storage.
38 fn push(&mut self, item: T) -> Result<(), Self::Error>;
39}
40
41#[cfg(feature = "alloc")]
42impl<T> Storage<T> for alloc::vec::Vec<T> {
43 type Error = core::convert::Infallible;
44
45 const EMPTY: Self = alloc::vec::Vec::new();
46
47 /// Capacity is a hint, and is ignored if it can't be allocated.
48 #[inline]
49 fn with_capacity(capacity: usize) -> Result<Self, Self::Error> {
50 let mut vec = alloc::vec::Vec::new();
51 _ = vec.try_reserve_exact(capacity);
52 Ok(vec)
53 }
54
55 #[inline]
56 fn capacity(&self) -> usize {
57 alloc::vec::Vec::capacity(self)
58 }
59
60 /// Capacity is a hint, and is ignored if it can't be allocated.
61 #[inline]
62 fn reserve(&mut self, additional: usize) -> Result<(), Self::Error> {
63 _ = self.try_reserve(additional);
64 Ok(())
65 }
66
67 #[inline]
68 fn push(&mut self, item: T) -> Result<(), Self::Error> {
69 alloc::vec::Vec::push(self, item);
70 Ok(())
71 }
72}
73
74/// Declare a new flavor.
75///
76/// The associated types are declared in this order, and all but `Index` are
77/// optional:
78/// * `type Index = ..;` the [Index] used for spans.
79/// * `type Width = ..;` the [Width] which bounds pointers, defaults to `u32`
80/// like [`FlavorDefault`]. Declare `type Width = usize;` for trees that need
81/// more nodes than a `u32` width can address.
82/// * `type Error = ..;` the error raised by storage, defaults to
83/// [`Infallible`].
84/// * `type Storage<T> = ..;` the [Storage] used for tree data, defaults to
85/// `Vec<T>` (or [`EmptyVec<T>`] without the `alloc` feature).
86///
87/// The `Error` of `Storage` must be the flavor's `Error`, so a flavor with a
88/// custom `Error` needs to declare `Storage` too. Errors raised by storage are
89/// reported as [`Error::Flavor`].
90///
91/// [`Infallible`]: core::convert::Infallible
92/// [`EmptyVec<T>`]: crate::EmptyVec
93/// [`Error::Flavor`]: crate::Error::Flavor
94/// [`FlavorDefault`]: crate::FlavorDefault
95///
96/// # Examples
97///
98/// ```
99/// use syntree::Empty;
100///
101/// syntree::flavor! {
102/// struct FlavorEmpty {
103/// type Index = Empty;
104/// }
105/// }
106///
107/// syntree::flavor! {
108/// struct FlavorU32 {
109/// type Index = u32;
110/// type Width = u32;
111/// }
112/// }
113/// ```
114///
115/// A flavor with custom fallible storage:
116///
117/// ```
118/// use core::ops::{Deref, DerefMut};
119/// use syntree::{Builder, Error, Storage};
120///
121/// #[derive(Debug, PartialEq)]
122/// struct Full;
123///
124/// /// Storage which holds at most one item.
125/// struct One<T>(Option<T>);
126///
127/// impl<T> Deref for One<T> {
128/// type Target = [T];
129///
130/// fn deref(&self) -> &[T] {
131/// self.0.as_slice()
132/// }
133/// }
134///
135/// impl<T> DerefMut for One<T> {
136/// fn deref_mut(&mut self) -> &mut [T] {
137/// self.0.as_mut_slice()
138/// }
139/// }
140///
141/// impl<T> Storage<T> for One<T> {
142/// type Error = Full;
143///
144/// const EMPTY: Self = One(None);
145///
146/// fn with_capacity(capacity: usize) -> Result<Self, Full> {
147/// if capacity > 1 {
148/// return Err(Full);
149/// }
150///
151/// Ok(One(None))
152/// }
153///
154/// fn capacity(&self) -> usize {
155/// 1
156/// }
157///
158/// fn push(&mut self, item: T) -> Result<(), Full> {
159/// if self.0.is_some() {
160/// return Err(Full);
161/// }
162///
163/// self.0 = Some(item);
164/// Ok(())
165/// }
166/// }
167///
168/// syntree::flavor! {
169/// struct FlavorOne {
170/// type Index = u32;
171/// type Error = Full;
172/// type Storage<T> = One<T>;
173/// }
174/// }
175///
176/// let mut tree: Builder<_, FlavorOne> = Builder::new_with();
177/// tree.token("a", 1)?;
178/// assert_eq!(tree.token("b", 1), Err(Error::Flavor(Full)));
179/// # Ok::<_, Error<Full>>(())
180/// ```
181#[macro_export]
182macro_rules! flavor {
183 (
184 $(#[doc = $doc:literal])*
185 $vis:vis struct $ty:ident {
186 type Index = $index:ty;
187 $(type Width = $width:ty;)?
188 $(type Error = $error:ty;)?
189 $(type Storage<$t:ident> = $storage:ty;)?
190 }
191 ) => {
192 $(#[doc = $doc])*
193 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
194 #[non_exhaustive]
195 $vis struct $ty;
196
197 impl $crate::Flavor for $ty {
198 type Error = $crate::flavor!(@error $($error)*);
199 type Index = $index;
200 type Length = <$index as $crate::Index>::Length;
201 type Width = $crate::flavor!(@width $($width)*);
202 type Pointer = $crate::flavor!(@pointer $($width)*);
203 $crate::flavor!(@storage $($t $storage)*);
204 }
205 };
206
207 (@error $ty:ty) => { $ty };
208 (@error) => { ::core::convert::Infallible };
209 (@width $ty:ty) => { $ty };
210 (@width) => { u32 };
211 (@pointer $ty:ty) => { <$ty as $crate::pointer::Width>::Pointer };
212 (@pointer) => { <u32 as $crate::pointer::Width>::Pointer };
213 (@storage $t:ident $ty:ty) => { type Storage<$t> = $ty; };
214 (@storage) => { type Storage<T> = $crate::macro_support::Vec<T>; };
215}
216
217flavor! {
218 /// The default flavor of a tree.
219 ///
220 /// This corresponds to a `u32` index with a `u32` width.
221 ///
222 /// A `u32` width keeps entries small, on 64-bit targets with a 2-byte `T`
223 /// a token takes 12 rather than 16 bytes and a node 40 rather than 72, but
224 /// bounds a tree to about 4 billion tokens and as many nodes. Adding more
225 /// fails with [`Error::Overflow`]. A tree which needs more can declare a
226 /// flavor with `type Width = usize;` through [`flavor!`].
227 ///
228 /// [`Error::Overflow`]: crate::Error::Overflow
229 pub struct FlavorDefault {
230 type Index = u32;
231 type Width = u32;
232 }
233}
234
235/// The flavor of a tree.
236///
237/// This should not be implemented directly, instead see the [flavor!] macro.
238///
239/// The Index associated type is constrained by the [Index] trait, and
240/// determines the numerical bounds of [spans] the tree.
241///
242/// The `Width` associated type determines the bounds of pointers in the tree
243/// through the [Width] trait, this decides how many elements that can be stored
244/// in the tree.
245///
246/// [spans]: crate::Span
247pub trait Flavor {
248 /// The error raised by the type of the tree.
249 type Error;
250 /// The type of an index used by a tree.
251 type Index: Index<Length = Self::Length>;
252 /// The length used in the flavor.
253 type Length: Length;
254 /// The width used in the flavor.
255 type Width: Width<Pointer = Self::Pointer>;
256 /// The pointer in use.
257 type Pointer: Pointer;
258 /// The storage type used in the tree.
259 type Storage<T>: Storage<T, Error = Self::Error>;
260}