syntree/
empty.rs

1use core::convert::Infallible;
2use core::marker::PhantomData;
3use core::ops::{Deref, DerefMut};
4
5use crate::flavor::Storage;
6use crate::index::{Index, Length};
7
8/// The empty [Index] implementation.
9///
10/// This can be used in combination with [`Builder::new_with`] to ensure that
11/// that tree does not store any information on spans, reducing overhead if this
12/// is not necessary.
13///
14/// [`Builder::new_with`]: crate::Builder::new_with
15#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
16#[repr(transparent)]
17pub struct Empty;
18
19impl From<u32> for Empty {
20    fn from(_: u32) -> Self {
21        Empty
22    }
23}
24
25impl From<usize> for Empty {
26    fn from(_: usize) -> Self {
27        Empty
28    }
29}
30
31impl Index for Empty {
32    const EMPTY: Self = Empty;
33
34    type Length = Empty;
35
36    #[inline]
37    fn is_empty(&self) -> bool {
38        true
39    }
40
41    #[inline]
42    fn as_usize(self) -> usize {
43        0
44    }
45
46    #[inline]
47    fn checked_add_len(self, _: Self::Length) -> Option<Self> {
48        Some(Empty)
49    }
50
51    #[inline]
52    fn len_to(self, _: Self) -> Self {
53        Empty
54    }
55
56    #[inline]
57    fn from_usize(_: usize) -> Option<Self> {
58        Some(Empty)
59    }
60}
61
62impl From<Empty> for usize {
63    #[inline]
64    fn from(Empty: Empty) -> Self {
65        0
66    }
67}
68
69impl Length for Empty {
70    const EMPTY: Self = Empty;
71
72    #[inline]
73    fn is_empty(&self) -> bool {
74        true
75    }
76}
77
78/// An empty vector.
79pub struct EmptyVec<T>(PhantomData<T>);
80
81impl<T> Default for EmptyVec<T> {
82    fn default() -> Self {
83        EmptyVec(PhantomData)
84    }
85}
86
87impl<T> Storage<T> for EmptyVec<T> {
88    const EMPTY: Self = EmptyVec(PhantomData);
89
90    type Error = Infallible;
91
92    #[inline]
93    fn push(&mut self, _: T) -> Result<(), Self::Error> {
94        Ok(())
95    }
96
97    #[inline]
98    fn with_capacity(_: usize) -> Result<Self, Self::Error> {
99        Ok(Self::EMPTY)
100    }
101
102    #[inline]
103    fn capacity(&self) -> usize {
104        0
105    }
106}
107
108impl<T> Deref for EmptyVec<T> {
109    type Target = [T];
110
111    #[inline]
112    fn deref(&self) -> &Self::Target {
113        &[]
114    }
115}
116
117impl<T> DerefMut for EmptyVec<T> {
118    #[inline]
119    fn deref_mut(&mut self) -> &mut Self::Target {
120        &mut []
121    }
122}