Skip to main content

syntree/
index.rs

1//! Types that can be used to refer to indexes in a [Span][crate::Span].
2
3use core::cmp;
4
5mod sealed {
6    pub trait Sealed {}
7
8    impl Sealed for u32 {}
9    impl Sealed for usize {}
10    impl Sealed for crate::empty::Empty {}
11}
12
13/// A type that can be used when referring to an index in a tree.
14///
15/// An index is a valid single component of a [Span][crate::Span], valid indexes
16/// are types such as `u32` and `usize`, but also [`Empty`][crate::Empty] in
17/// case indexing is not required.
18///
19/// See [Builder::new_with][crate::Builder::new_with].
20pub trait Index: Sized + Copy + cmp::Ord + cmp::Eq + self::sealed::Sealed {
21    #[doc(hidden)]
22    const EMPTY: Self;
23
24    #[doc(hidden)]
25    type Length: Length;
26
27    #[doc(hidden)]
28    fn is_empty(&self) -> bool;
29
30    #[doc(hidden)]
31    fn as_usize(self) -> usize;
32
33    #[doc(hidden)]
34    fn checked_add_len(self, other: Self::Length) -> Option<Self>;
35
36    #[doc(hidden)]
37    fn len_to(self, other: Self) -> Self::Length;
38
39    #[doc(hidden)]
40    fn from_usize(value: usize) -> Option<Self>;
41}
42
43#[doc(hidden)]
44pub trait Length: Copy + self::sealed::Sealed {
45    #[doc(hidden)]
46    const EMPTY: Self;
47
48    #[doc(hidden)]
49    fn is_empty(&self) -> bool;
50}
51
52impl Length for usize {
53    const EMPTY: Self = 0;
54
55    #[inline]
56    fn is_empty(&self) -> bool {
57        *self == 0
58    }
59}
60
61/// Ensure u32 is smaller or equal to usize.
62const _: () = assert!(core::mem::size_of::<u32>() <= core::mem::size_of::<usize>());
63
64impl Index for u32 {
65    const EMPTY: Self = 0;
66
67    type Length = usize;
68
69    #[inline]
70    fn is_empty(&self) -> bool {
71        *self == 0
72    }
73
74    #[inline]
75    fn as_usize(self) -> usize {
76        self as usize
77    }
78
79    #[inline]
80    fn checked_add_len(self, other: Self::Length) -> Option<Self> {
81        u32::checked_add(self, u32::try_from(other).ok()?)
82    }
83
84    #[inline]
85    fn len_to(self, other: Self) -> Self::Length {
86        other.saturating_sub(self) as usize
87    }
88
89    #[inline]
90    fn from_usize(value: usize) -> Option<Self> {
91        u32::try_from(value).ok()
92    }
93}
94
95impl Index for usize {
96    const EMPTY: Self = 0;
97
98    type Length = usize;
99
100    #[inline]
101    fn is_empty(&self) -> bool {
102        *self == 0
103    }
104
105    #[inline]
106    fn as_usize(self) -> usize {
107        self
108    }
109
110    #[inline]
111    fn checked_add_len(self, other: Self::Length) -> Option<Self> {
112        usize::checked_add(self, other)
113    }
114
115    #[inline]
116    fn len_to(self, other: Self) -> Self::Length {
117        other.saturating_sub(self)
118    }
119
120    #[inline]
121    fn from_usize(value: usize) -> Option<Self> {
122        Some(value)
123    }
124}