beetree 0.0.1

A simple, generic, and serializable B+ Tree
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
use std::{
    cmp::{Ord, Ordering},
    default::Default,
    fmt,
    fmt::{Debug, Formatter},
    ptr::NonNull,
};

#[derive(Clone, PartialEq)]
pub enum BTree<K: Ord + Clone, V, const Q: usize> {
    // INVARIANT: NonNull always valid
    Internal(NonNull<InternalNode<K, V, Q>>),
    // INVARIANT: NonNull always valid
    Leaf(NonNull<LeafNode<K, V, Q>>),
}

#[derive(Clone, PartialEq)]
pub struct InternalNode<K: Ord + Clone, V, const Q: usize> {
    keys: Vec<K>,
    // INVARIANT: children.len() == keys.len() + 1
    children: Vec<BTree<K, V, Q>>,
}

#[derive(Clone, PartialEq)]
pub struct LeafNode<K: Ord + Clone, V, const Q: usize> {
    keys: Vec<K>,
    values: Vec<V>,
    // INVARIANS: is Some => NonNull points to valid leaf node
    next: Option<NonNull<LeafNode<K, V, Q>>>,
    // INVARIANT: is Some => NonNull points to valid leaf node
    prev: Option<NonNull<LeafNode<K, V, Q>>>,
}

impl<K, V, const Q: usize> Debug for BTree<K, V, Q>
where
    K: Debug + Ord + Clone,
    V: Debug,
{
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            BTree::Internal(ptr) => {
                let node = unsafe { ptr.as_ref() };
                f.debug_struct("InternalNode")
                    .field("entries", node)
                    .finish()
            }
            BTree::Leaf(ptr) => {
                let node = unsafe { ptr.as_ref() };
				let prev_key = unsafe { node.prev.map(|ptr| &ptr.as_ref().keys[0]) };
				let next_key= unsafe { node.next.map(|ptr| &ptr.as_ref().keys[0]) };
                f.debug_struct("LeafNode")
					.field("entries", node)
					.field("next_0th_key", &next_key)
					.field("prev_0th_key", &prev_key)
					.finish()
            }
        }
    }
}

impl<K, V, const Q: usize> Debug for InternalNode<K, V, Q>
where
    K: Debug + Ord + Clone,
    V: Debug,
{
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
		let mut m = &mut f.debug_map();
		for i in 0..self.children.len() {
			if i == 0 {
				m = m.entry(&"null", &self.children[i]);
			} else {
				m = m.entry(&self.keys[i - 1], &self.children[i])
			}
		}
		m.finish()
    }
}

impl<K, V, const Q: usize> Debug for LeafNode<K, V, Q>
where
    K: Debug + Ord + Clone,
    V: Debug,
{
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
		let mut m = &mut f.debug_map();
		for i in 0..self.keys.len() {
			m = m.entry(&self.keys[i], &self.values[i]);
		}
		m.finish()
    }
}

impl<K, V, const Q: usize> Default for BTree<K, V, Q>
where
    K: Ord + Clone,
{
    fn default() -> Self {
        assert!(Q > 2, "branching factor Q must be greater than 2");
        let node = unsafe { NonNull::new_unchecked(Box::into_raw(Box::new(LeafNode::default()))) };
        BTree::Leaf(node)
    }
}

impl<K, V, const Q: usize> Default for LeafNode<K, V, Q>
where
    K: Ord + Clone,
{
    fn default() -> Self {
        assert!(Q > 2, "branching factor Q must be greater than 2");
        LeafNode {
            keys: Vec::with_capacity(Q),
            values: Vec::with_capacity(Q),
            next: None,
            prev: None,
        }
    }
}

impl<K, V, const Q: usize> InternalNode<K, V, Q>
where
    K: Ord + Clone + Debug,
{
    fn new(child: BTree<K, V, Q>) -> Self {
        assert!(Q > 2, "branching factor Q must be greater than 2");

        let mut children = Vec::with_capacity(Q);
        children.push(child);

        InternalNode {
            keys: Vec::with_capacity(Q),
            children,
        }
    }

    fn insert(&mut self, key: K, child: BTree<K, V, Q>) {
        let idx = self.keys.binary_search(&key).unwrap_or_else(|idx| idx);
        self.keys.insert(idx, key);
        self.children.insert(idx + 1, child);
    }
}

impl<K, V, const Q: usize> LeafNode<K, V, Q>
where
    K: Ord + Clone,
{
    fn insert(&mut self, key: K, value: V) {
        let idx = self.keys.binary_search(&key).unwrap_or_else(|idx| idx);
        self.keys.insert(idx, key);
        self.values.insert(idx, value);
    }
}

impl<K, V, const Q: usize> BTree<K, V, Q>
where
    K: Ord + Clone + Debug,
	V: Debug
{
    fn insert_inner(&mut self, key: K, value: V) -> Option<(K, BTree<K, V, Q>)> {
        match self {
            BTree::Leaf(ref mut _leaf) => {
                // SAFETY: OK due to invariant
                let leaf = unsafe { _leaf.as_mut() };
                leaf.insert(key, value);
                if leaf.keys.len() == Q {
                    let mid = leaf.keys.len() / 2;

                    let mut right: LeafNode<K, V, Q> = Default::default();
                    right.keys = leaf.keys.split_off(mid);
                    right.values = leaf.values.split_off(mid);

                    let right = Box::new(right);
                    let split_key = right.keys[0].clone();

                    // SAFETY: right is valid pointer
                    let mut right = unsafe { NonNull::new_unchecked(Box::into_raw(right)) };
                    // SAFETY: _leaf is valid pointer due to invariant
                    unsafe { right.as_mut().prev = Some(*_leaf) };
                    leaf.next = Some(right);

                    Some((split_key, BTree::Leaf(right)))
                } else {
                    None
                }
            }
            BTree::Internal(ref mut node) => {
                // SAFETY: OK due to invariant
                let node = unsafe { node.as_mut() };

                let idx = node.keys.binary_search(&key).unwrap_or_else(|idx| idx);
                if let Some((split_key, child)) = node.children[idx].insert_inner(key, value) {
                    node.insert(split_key, child);

                    if node.keys.len() == Q {
                        let mid = node.keys.len() / 2;

                        let right_keys = node.keys.split_off(mid + 1);
                        let right_children = node.children.split_off(mid + 1);

                        // unwrap() OK here because Q >= 3 => node.keys.len() >= 3
                        // => after split, node.keys.len() > 1
                        // => after split, node.children.len() > 1 due to invariant (children.len() == keys.len() + 1)
                        let split_key = node.keys.pop().unwrap();
                        let split_child = node.children.pop().unwrap();

                        let mut right = InternalNode::new(split_child);
                        right.keys.extend(right_keys);
                        right.children.extend(right_children);

                        let right = Box::new(right);

                        // SAFETY: right is valid pointer
                        let right = unsafe { NonNull::new_unchecked(Box::into_raw(right)) };
                        Some((split_key, BTree::Internal(right)))
                    } else {
                        None
                    }
                } else {
                    None
                }
            }
        }
    }

    pub fn insert(&mut self, key: K, value: V) {
        // if insert_inner returns Some, need to make a new root
        // otherwise, we're done
        if let Some((right_key, right)) = self.insert_inner(key, value) {
            let new_root = InternalNode::new(right);
            let new_root = Box::new(new_root);
            // SAFETY: new_root is valid pointer due to box
            let new_root = unsafe { NonNull::new_unchecked(Box::into_raw(new_root)) };

            let left = std::mem::replace(self, BTree::Internal(new_root));
            match self {
                BTree::Internal(ref mut node) => {
                    // SAFETY: node is valid pointer because self is new root, which is valid pointer
                    let node = unsafe { node.as_mut() };

                    node.keys.push(right_key);
                    node.children.insert(0, left);
                }
                BTree::Leaf(_) => panic!("expected root to be Internal node!"),
            }
        }
    }

    pub fn get(&self, key: &K) -> Option<&V> {
        match self {
            BTree::Internal(ref node) => {
                // SAFETY: Ok due to invariant
                let idx = unsafe { node.as_ref() }
                    .keys
                    .binary_search(key)
                    .unwrap_or_else(|idx| idx);
                unsafe { node.as_ref() }.children[idx].get(key)
            }
            BTree::Leaf(ref node) => {
                // SAFETY: Ok due to invariant
                let idx = unsafe { node.as_ref() }.keys.binary_search(key).ok();
                match idx {
                    // SAFETY: Ok due to invariant
                    Some(idx) => Some(&(unsafe { node.as_ref() }.values[idx])),
                    None => None,
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fmt::Debug;

    fn is_sorted<T: Ord>(items: &Vec<T>) -> bool {
        let (is_sorted, _) = items.iter().fold((true, None), |(is_sorted, prev), curr| {
            if let Some(prev) = prev {
                (is_sorted && prev <= curr, Some(curr))
            } else {
                (is_sorted, Some(curr))
            }
        });

        is_sorted
    }

    fn assert_at_node<K: Debug>(
        cond: bool,
        left_parent_key: Option<&K>,
        level: usize,
        msg: String,
    ) {
        assert!(
            cond,
            "In node with parent key {:#?} at level {}: {}",
            left_parent_key, level, msg
        );
    }

    fn assert_is_b_tree_inner<K: Ord + Clone + Debug, V, const Q: usize>(
        node: &BTree<K, V, Q>,
        parent_keys: (Option<&K>, Option<&K>),
        level: usize,
    ) {
        let (left_parent_key, right_parent_key) = parent_keys;

        match node {
            BTree::Internal(ptr) => {
                // SAFETY: ptr validity guaratnteed by invariant
                let node = unsafe { ptr.as_ref() };

                assert_at_node(
                    is_sorted(&node.keys),
                    left_parent_key,
                    level,
                    "keys are not sorted".to_string(),
                );

                // ensure every key in node is >= left parent key but < right parent key
                // ignore the corresponding check of each parent key that is None
                node.keys
                    .iter()
                    .for_each(|key| match (left_parent_key, right_parent_key) {
                        (Some(left), Some(right)) => assert_at_node(
                            key >= left && key < right,
                            left_parent_key,
                            level,
                            format!(
                                "key {:#?} < left parent key {:?} or >= right parent key {:?}",
                                key, left, right
                            ),
                        ),
                        (Some(left), None) => assert_at_node(
                            key >= left,
                            left_parent_key,
                            level,
                            format!("key {:?} < left parent key {:?}", key, left),
                        ),
                        (None, Some(right)) => assert_at_node(
                            key < right,
                            left_parent_key,
                            level,
                            format!("key {:?} >= right parent key {:?}", key, right),
                        ),
                        (None, None) => assert_at_node(
                            level == 0,
                            left_parent_key,
                            level,
                            "(None, None) case of parent keys for non-root node encountered!"
                                .to_string(),
                        ),
                    });

				assert!(node.children.len() > 1);

                node.children.iter().enumerate().for_each(|(i, child)| {
                    // recurse - parent keys have 4 possible cases
					// (None, None) is covered by assert statement above and should never happen
                    if i == 0 {
                        // case where it's the 0th child child
                        let right = &node.keys[i];
                        assert_is_b_tree_inner(child, (None, Some(right)), level + 1);
                    } else if i == node.keys.len() {
                        // case where it's the last child
                        let left = &node.keys[i - 1];
                        assert_is_b_tree_inner(child, (Some(left), None), level + 1);
                    } else {
                        // case where it's neither the first nor the last child
                        let left = &node.keys[i - 1];
                        let right = &node.keys[i];
                        assert_is_b_tree_inner(child, (Some(left), Some(right)), level + 1);
                    }
                });
            }
            BTree::Leaf(ptr) => {
                // SAFETY: ptr validity guaranteed by invariant
                let node = unsafe { ptr.as_ref() };

                assert_at_node(
                    is_sorted(&node.keys),
                    left_parent_key,
                    level,
                    "keys are not sorted".to_string(),
                );

                // if it's the root, there are different requirements
                if left_parent_key.is_none() && right_parent_key.is_none() {
                    assert_at_node(
                        node.keys.len() < Q,
                        left_parent_key,
                        level,
                        format!("root node that's leaf has {} > Q keys", node.keys.len()),
                    );
                    return;
                }

                assert_at_node(
                    node.keys.len() >= Q / 2,
                    left_parent_key,
                    level,
                    format!("leaf node has {} < Q / 2 keys", node.keys.len()),
                );

                // check key of leaf node to the left, if it exists
                let (left_leaf_last_key, is_lte) = node.prev.map_or((None, true), |ptr| {
                    // SAFETY: guaranteed by invariant that Some => ptr is valid
                    let left_leaf = unsafe { ptr.as_ref() };

                    // if left_leaf.keys.last() is None the keys.len() assertion will catch this bug
                    // ignore that case
                    if let Some(left_leaf_last_key) = left_leaf.keys.last() {
                        (
                            Some(left_leaf_last_key),
                            left_leaf_last_key <= node.keys.first().unwrap(),
                        )
                    } else {
                        (None, true)
                    }
                });

                assert_at_node(
                    is_lte,
                    left_parent_key,
                    level,
                    format!(
                        "last key {:?} of left leaf node > {:?}, the first key of current leaf node",
                        node.keys.first().unwrap(),
                        left_leaf_last_key
                    ),
                );

                // check key of node to the right, if it exists
                let (right_leaf_first_key, is_gte) = node.next.map_or((None, true), |ptr| {
                    // SAFETY: guaranteed by invariant that Some => ptr is valid
                    let right_leaf = unsafe { ptr.as_ref() };

                    // if left_leaf.keys.last() is None the keys.len() assertion will catch this bug
                    // ignore that case
                    if let Some(right_leaf_first_key) = right_leaf.keys.first() {
                        (
                            Some(right_leaf_first_key),
                            right_leaf_first_key >= node.keys.last().unwrap(),
                        )
                    } else {
                        (None, true)
                    }
                });

                assert_at_node(
                    is_gte,
                    left_parent_key,
                    level,
                    format!(
                        "first key {:?} of right leaf node < {:?}, the last key of current leaf node",
                        node.keys.last().unwrap(),
                        right_leaf_first_key
                    ),
                )
            }
        }
    }

    fn assert_is_b_tree<K: Ord + Clone + Debug, V: Debug, const Q: usize>(root: &BTree<K, V, Q>) {
        println!("{:#?}", root);
        assert_is_b_tree_inner(root, (None, None), 0)
    }

    #[test]
    fn test_get_insert_basic() {
        let mut tree: BTree<i32, String, 4> = Default::default();

        let vals = vec![
            (-5, "hi"),
            (2, "howdy"),
            (-1, "yo"),
            (6, "salutations"),
            (-99, "greetings"),
            (30, "wilkommen"),
            (99, "ohayou"),
            (-400, "nihao"),
        ];

        for &(k, v) in vals.iter() {
            tree.insert(k, v.to_string());
            assert_is_b_tree(&tree);
        }

        assert_eq!(tree.get(&-99), Some(&"greetings".to_string()));
        assert_eq!(tree.get(&99), Some(&"ohayou".to_string()));
        assert!(tree.get(&0).is_none());
        assert!(tree.get(&7).is_none());
    }
}