Skip to main content

b_tree/
range.rs

1use std::borrow::Borrow;
2use std::cmp::Ordering;
3use std::fmt;
4use std::ops::{Bound, Range as Bounds};
5
6use collate::{Collate, Overlap, OverlapsRange, OverlapsValue};
7use smallvec::smallvec;
8
9use super::{Collator, Key};
10
11/// A range used to select a slice of a `BTree`
12#[derive(Clone, Eq, PartialEq)]
13pub struct Range<V> {
14    prefix: Key<V>,
15    start: Bound<V>,
16    end: Bound<V>,
17}
18
19impl<V> Default for Range<V> {
20    fn default() -> Self {
21        Self {
22            prefix: smallvec![],
23            start: Bound::Unbounded,
24            end: Bound::Unbounded,
25        }
26    }
27}
28
29impl<V> Range<V> {
30    /// Construct a new [`Range`] with the given `prefix`.
31    pub fn with_bounds<K: Into<Key<V>>>(prefix: K, bounds: (Bound<V>, Bound<V>)) -> Self {
32        let prefix = prefix.into();
33        let (start, end) = bounds;
34        Self { prefix, start, end }
35    }
36
37    /// Construct a new [`Range`] with the given `prefix`.
38    pub fn with_range<K: Into<Key<V>>>(prefix: K, range: Bounds<V>) -> Self {
39        let Bounds { start, end } = range;
40        Self::with_bounds(prefix, (Bound::Included(start), Bound::Excluded(end)))
41    }
42
43    /// Construct a new [`Range`] with only the given `prefix`.
44    pub fn from_prefix<K: Into<Key<V>>>(prefix: K) -> Self {
45        Self {
46            prefix: prefix.into(),
47            start: Bound::Unbounded,
48            end: Bound::Unbounded,
49        }
50    }
51
52    /// Construct an owned [`Range`] by borrowing this [`Range`].
53    pub fn as_ref(&self) -> Range<&V> {
54        Range {
55            prefix: self.prefix.iter().collect(),
56            start: self.start.as_ref(),
57            end: self.end.as_ref(),
58        }
59    }
60
61    /// Destructure this [`Range`] into a prefix and [`Bound`]s.
62    pub fn into_inner(self) -> (Key<V>, (Bound<V>, Bound<V>)) {
63        (self.prefix, (self.start, self.end))
64    }
65
66    /// Return `false` if this [`Range`] has only a prefix.
67    pub fn has_bounds(&self) -> bool {
68        !matches!(
69            (&self.start, &self.end),
70            (Bound::Unbounded, Bound::Unbounded)
71        )
72    }
73
74    /// Return `true` if this [`Range`] is empty.
75    pub fn is_empty(&self) -> bool {
76        self.prefix.is_empty()
77            && matches!(
78                (&self.start, &self.end),
79                (Bound::Unbounded, Bound::Unbounded)
80            )
81    }
82
83    /// Return the number of columns specified by this [`Range`].
84    pub fn len(&self) -> usize {
85        if self.has_bounds() {
86            self.prefix.len() + 1
87        } else {
88            self.prefix.len()
89        }
90    }
91
92    /// Construct a new [`Range`] by prepending the given `prefix` to this one.
93    pub fn prepend<I: IntoIterator<Item = V>>(self, prefix: I) -> Self {
94        Self {
95            prefix: prefix.into_iter().chain(self.prefix).collect(),
96            start: self.start,
97            end: self.end,
98        }
99    }
100}
101
102impl<BV, C> OverlapsValue<Vec<C::Value>, Collator<C>> for Range<BV>
103where
104    BV: Borrow<C::Value>,
105    C: Collate,
106    C::Value: fmt::Debug,
107{
108    fn overlaps_value(&self, key: &Vec<C::Value>, collator: &Collator<C>) -> Overlap {
109        match collator.cmp_slices(&self.prefix, key) {
110            Ordering::Less => Overlap::Less,
111            Ordering::Greater => Overlap::Greater,
112            Ordering::Equal if self.prefix.len() >= key.len() => Overlap::Narrow,
113            Ordering::Equal => {
114                let value = &key[self.prefix.len()];
115
116                let start = match &self.start {
117                    Bound::Unbounded => Ordering::Less,
118                    Bound::Included(start) => collator.value.cmp(start.borrow(), value),
119                    Bound::Excluded(start) => match collator.value.cmp(start.borrow(), value) {
120                        Ordering::Less => Ordering::Less,
121                        Ordering::Greater | Ordering::Equal => Ordering::Greater,
122                    },
123                };
124
125                let end = match &self.end {
126                    Bound::Unbounded => Ordering::Greater,
127                    Bound::Included(end) => collator.value.cmp(end.borrow(), value),
128                    Bound::Excluded(end) => match collator.value.cmp(end.borrow(), value) {
129                        Ordering::Greater => Ordering::Greater,
130                        Ordering::Less | Ordering::Equal => Ordering::Less,
131                    },
132                };
133
134                match (start, end) {
135                    (start, Ordering::Less) => {
136                        debug_assert!(start != Ordering::Greater);
137                        Overlap::Less
138                    }
139                    (Ordering::Greater, end) => {
140                        debug_assert_eq!(end, Ordering::Greater);
141                        Overlap::Greater
142                    }
143                    (Ordering::Equal, Ordering::Equal) if key.len() == self.prefix.len() + 1 => {
144                        // in this case, the range prefix of length n is exactly equal to key[0..n]
145                        // and the trailing range is exactly equal to key[n]
146                        Overlap::Equal
147                    }
148                    _ => Overlap::Wide,
149                }
150            }
151        }
152    }
153}
154
155impl<C: Collate> OverlapsRange<Range<C::Value>, Collator<C>> for Range<C::Value> {
156    fn overlaps(&self, other: &Range<C::Value>, collator: &Collator<C>) -> Overlap {
157        #[inline]
158        fn cmp_start<C>(collator: &C, bound: &Bound<C::Value>, value: &C::Value) -> Ordering
159        where
160            C: Collate,
161        {
162            match bound {
163                Bound::Unbounded => Ordering::Less,
164                Bound::Included(start) => collator.cmp(start, value),
165                Bound::Excluded(start) => match collator.cmp(start, value) {
166                    Ordering::Less | Ordering::Equal => Ordering::Less,
167                    Ordering::Greater => Ordering::Greater,
168                },
169            }
170        }
171
172        #[inline]
173        fn cmp_end<C>(collator: &C, bound: &Bound<C::Value>, value: &C::Value) -> Ordering
174        where
175            C: Collate,
176        {
177            match bound {
178                Bound::Unbounded => Ordering::Less,
179                Bound::Included(end) => collator.cmp(end, value),
180                Bound::Excluded(end) => match collator.cmp(end, value) {
181                    Ordering::Less => Ordering::Less,
182                    Ordering::Greater | Ordering::Equal => Ordering::Greater,
183                },
184            }
185        }
186
187        match collator.cmp_slices(&self.prefix, &other.prefix) {
188            Ordering::Less => Overlap::Less,
189            Ordering::Greater => Overlap::Greater,
190            Ordering::Equal => match self.prefix.len().cmp(&other.prefix.len()) {
191                Ordering::Less => {
192                    let value = &other.prefix[self.prefix.len()];
193
194                    match (
195                        cmp_start(&collator.value, &self.start, value),
196                        cmp_end(&collator.value, &self.end, value),
197                    ) {
198                        (Ordering::Greater, _) => Overlap::Greater,
199                        (_, Ordering::Less) => Overlap::Less,
200
201                        (Ordering::Equal, Ordering::Greater) => Overlap::WideGreater,
202                        (Ordering::Less, Ordering::Equal) => Overlap::WideLess,
203
204                        (Ordering::Less, Ordering::Greater) => Overlap::Wide,
205                        (Ordering::Equal, Ordering::Equal) => Overlap::Wide,
206                    }
207                }
208                Ordering::Equal => {
209                    (&self.start, &self.end).overlaps(&(&other.start, &other.end), &collator.value)
210                }
211                Ordering::Greater => {
212                    let value = &self.prefix[other.prefix.len()];
213
214                    match (
215                        cmp_start(&collator.value, &other.start, value),
216                        cmp_end(&collator.value, &other.end, value),
217                    ) {
218                        (Ordering::Greater, _) => Overlap::Less,
219                        (_, Ordering::Less) => Overlap::Greater,
220                        _ => Overlap::Narrow,
221                    }
222                }
223            },
224        }
225    }
226}
227
228impl<V> From<Key<V>> for Range<V> {
229    fn from(prefix: Key<V>) -> Self {
230        Self {
231            prefix,
232            start: Bound::Unbounded,
233            end: Bound::Unbounded,
234        }
235    }
236}
237
238impl<V, K: Into<Key<V>>> From<(K, Bounds<V>)> for Range<V> {
239    fn from(tuple: (K, Bounds<V>)) -> Self {
240        let (prefix, suffix) = tuple;
241        let Bounds { start, end } = suffix;
242
243        Self {
244            prefix: prefix.into(),
245            start: Bound::Included(start),
246            end: Bound::Excluded(end),
247        }
248    }
249}
250
251impl<K: fmt::Debug> fmt::Debug for Range<K> {
252    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
253        write!(f, "range ")?;
254
255        match (&self.start, &self.end) {
256            (Bound::Excluded(l), Bound::Unbounded) => write!(f, "[{:?},)", l),
257            (Bound::Excluded(l), Bound::Excluded(r)) => write!(f, "[{:?}, {:?}]", l, r),
258            (Bound::Excluded(l), Bound::Included(r)) => write!(f, "[{:?}, {:?})", l, r),
259            (Bound::Included(l), Bound::Unbounded) => write!(f, "({:?},)", l),
260            (Bound::Included(l), Bound::Excluded(r)) => write!(f, "({:?}, {:?}]", l, r),
261            (Bound::Included(l), Bound::Included(r)) => write!(f, "({:?}, {:?})", l, r),
262            (Bound::Unbounded, Bound::Unbounded) => write!(f, "()"),
263            (Bound::Unbounded, Bound::Excluded(r)) => write!(f, "(,{:?}]", r),
264            (Bound::Unbounded, Bound::Included(r)) => write!(f, "(,{:?})", r),
265        }?;
266
267        write!(f, " with prefix {:?}", self.prefix)
268    }
269}