Skip to main content

b_tree/
node.rs

1use std::borrow::Borrow;
2use std::cmp::Ordering;
3use std::fmt;
4
5use collate::{Collate, Overlap, OverlapsValue};
6#[cfg(feature = "stream")]
7use destream::{de, en};
8use get_size::GetSize;
9use uuid::Uuid;
10
11use super::Collator;
12use super::range::Range;
13
14const UUID_SIZE: usize = 16;
15
16/// An ordered set of keys in a [`Node`].
17pub trait Block<V> {
18    type Key;
19
20    fn bisect<C, BV>(&self, range: &Range<BV>, collator: &Collator<C>) -> (usize, usize)
21    where
22        C: Collate<Value = V>,
23        BV: Borrow<V>;
24
25    fn bisect_left<C, BV>(&self, key: &[BV], collator: &Collator<C>) -> usize
26    where
27        C: Collate<Value = V>,
28        BV: Borrow<V>;
29
30    fn bisect_right<C, BV>(&self, key: &[BV], collator: &Collator<C>) -> usize
31    where
32        C: Collate<Value = V>,
33        BV: Borrow<V>;
34}
35
36impl<V: fmt::Debug> Block<V> for Vec<Vec<V>> {
37    type Key = Vec<V>;
38
39    fn bisect<C, BV>(&self, range: &Range<BV>, collator: &Collator<C>) -> (usize, usize)
40    where
41        C: Collate<Value = V>,
42        BV: Borrow<V>,
43    {
44        // handle common edge cases
45
46        if range.is_empty() {
47            return (0, self.len());
48        }
49
50        if let Some(first) = self.first()
51            && range.overlaps_value(first, collator) == Overlap::Less
52        {
53            return (0, 0);
54        }
55
56        if let Some(last) = self.last()
57            && range.overlaps_value(last, collator) == Overlap::Greater
58        {
59            return (self.len(), self.len());
60        }
61
62        // bisect range left
63        let mut lo = 0;
64        let mut hi = self.len();
65
66        while lo < hi {
67            let mid = (lo + hi) >> 1;
68            match range.overlaps_value(&self[mid], collator) {
69                Overlap::Greater => lo = mid + 1,
70                _ => hi = mid,
71            }
72        }
73
74        let left = lo;
75
76        // bisect range right
77        let mut lo = 0;
78        let mut hi = self.len();
79
80        while lo < hi {
81            let mid = (lo + hi) >> 1;
82            match range.overlaps_value(&self[mid], collator) {
83                Overlap::Less => hi = mid,
84                _ => lo = mid + 1,
85            }
86        }
87
88        let right = hi;
89
90        // return
91        (left, right)
92    }
93
94    fn bisect_left<C, BV>(&self, key: &[BV], collator: &Collator<C>) -> usize
95    where
96        C: Collate<Value = V>,
97        BV: Borrow<V>,
98    {
99        let mut lo = 0;
100        let mut hi = self.len();
101
102        while lo < hi {
103            let mid = (lo + hi) >> 1;
104            match collator.cmp_slices(&self[mid], key) {
105                Ordering::Less => lo = mid + 1,
106                _ => hi = mid,
107            }
108        }
109
110        lo
111    }
112
113    fn bisect_right<C, BV>(&self, key: &[BV], collator: &Collator<C>) -> usize
114    where
115        C: Collate<Value = V>,
116        BV: Borrow<V>,
117    {
118        let mut lo = 0;
119        let mut hi = self.len();
120
121        while lo < hi {
122            let mid = (lo + hi) >> 1;
123            match collator.cmp_slices(&self[mid], key) {
124                Ordering::Greater => hi = mid,
125                _ => lo = mid + 1,
126            }
127        }
128
129        hi
130    }
131}
132
133/// A node in a B+Tree
134#[derive(Clone)]
135pub enum Node<N> {
136    Index(N, Vec<Uuid>),
137    Leaf(N),
138}
139
140impl<N> Node<N> {
141    /// Return `true` if this is a leaf node.
142    pub fn is_leaf(&self) -> bool {
143        matches!(self, Self::Leaf(_))
144    }
145}
146
147impl<N: GetSize> GetSize for Node<N> {
148    fn get_size(&self) -> usize {
149        match self {
150            Self::Index(keys, children) => keys.get_size() + (children.len() * UUID_SIZE),
151            Self::Leaf(leaf) => leaf.get_size(),
152        }
153    }
154}
155
156#[cfg(feature = "stream")]
157struct NodeVisitor<C, N> {
158    context: C,
159    phantom: std::marker::PhantomData<N>,
160}
161
162#[cfg(feature = "stream")]
163impl<C, N> NodeVisitor<C, N> {
164    fn new(context: C) -> Self {
165        Self {
166            context,
167            phantom: std::marker::PhantomData,
168        }
169    }
170}
171
172#[cfg(feature = "stream")]
173impl<N> de::Visitor for NodeVisitor<N::Context, N>
174where
175    N: de::FromStream,
176{
177    type Value = Node<N>;
178
179    fn expecting() -> &'static str {
180        "a B+Tree node"
181    }
182
183    async fn visit_seq<A: de::SeqAccess>(self, mut seq: A) -> Result<Self::Value, A::Error> {
184        let leaf = seq.expect_next::<bool>(()).await?;
185
186        if leaf {
187            match seq.expect_next(self.context).await {
188                Ok(leaf) => Ok(Node::Leaf(leaf)),
189                Err(cause) => Err(cause),
190            }
191        } else {
192            let bounds = seq.expect_next(self.context).await?;
193            let children = seq.expect_next(()).await?;
194            Ok(Node::Index(bounds, children))
195        }
196    }
197}
198
199#[cfg(feature = "stream")]
200impl<N> de::FromStream for Node<N>
201where
202    N: de::FromStream,
203{
204    type Context = N::Context;
205
206    async fn from_stream<D: de::Decoder>(
207        cxt: Self::Context,
208        decoder: &mut D,
209    ) -> Result<Self, D::Error> {
210        decoder.decode_seq(NodeVisitor::new(cxt)).await
211    }
212}
213
214#[cfg(feature = "stream")]
215impl<'en, N: 'en> en::IntoStream<'en> for Node<N>
216where
217    N: en::IntoStream<'en>,
218{
219    fn into_stream<E: en::Encoder<'en>>(self, encoder: E) -> Result<E::Ok, E::Error> {
220        match self {
221            Node::Leaf(keys) => (true, keys).into_stream(encoder),
222            Node::Index(bounds, children) => (false, bounds, children).into_stream(encoder),
223        }
224    }
225}
226
227#[cfg(feature = "stream")]
228impl<'en, N: 'en> en::ToStream<'en> for Node<N>
229where
230    N: en::ToStream<'en>,
231{
232    fn to_stream<E: en::Encoder<'en>>(&'en self, encoder: E) -> Result<E::Ok, E::Error> {
233        use en::IntoStream;
234
235        match self {
236            Node::Leaf(keys) => (true, keys).into_stream(encoder),
237            Node::Index(bounds, children) => (false, bounds, children).into_stream(encoder),
238        }
239    }
240}
241
242#[cfg(debug_assertions)]
243impl<N: fmt::Debug> fmt::Debug for Node<N> {
244    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
245        match self {
246            Self::Leaf(keys) => write!(f, "leaf node with keys {:?}", keys),
247            Self::Index(bounds, children) => write!(
248                f,
249                "index node with bounds {:?} and children {:?}",
250                bounds, children
251            ),
252        }
253    }
254}
255
256#[cfg(not(debug_assertions))]
257impl<V: fmt::Debug> fmt::Debug for Node<V> {
258    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
259        match self {
260            Self::Leaf(_keys) => write!(f, "a leaf node"),
261            Self::Index(_bounds, children) => {
262                write!(f, "an index node with {} children", children.len())
263            }
264        }
265    }
266}