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
use std::mem;
use std::ptr;

const MAX_VALUES_PER_LEAF: usize = 4;

/* A pivot is a key and a node of the subtree of values >= that key. */
struct Pivot<K, V> {
    min_key: K,
    child: Box<Node<K, V>>,
}

struct LeafNode<K, V> {
    elements: [(K, V); MAX_VALUES_PER_LEAF],
    // must be <= MAX_VALUES_PER_LEAF
    len: usize,
}

impl<K, V> LeafNode<K, V>
where
    K: Copy,
    V: Clone,
{
    fn empty() -> Self {
        unsafe { Self { elements: mem::MaybeUninit::uninit().assume_init(), len: 0 } }
    }

    fn from(items: &[(K, V)]) -> Self {
        debug_assert!(items.len() <= MAX_VALUES_PER_LEAF);
        let mut result = Self::empty();
        result.elements.clone_from_slice(items);
        result
    }

    fn valid_elements_mut(&mut self) -> &mut [(K, V)] {
        &mut self.elements[0..self.len]
    }

    fn valid_elements(&self) -> &[(K, V)] {
        &self.elements[0..self.len]
    }
}

struct BranchNode<K, V> {
    pivots: [Pivot<K, V>; MAX_VALUES_PER_LEAF],
    // must be <= MAX_VALUES_PER_LEAF and > 1
    len: usize,
}

impl<K, V> BranchNode<K, V>
where
    K: Copy,
{
    fn from(left: Pivot<K, V>, right: Pivot<K, V>) -> Self {
        unsafe {
            let mut result = Self { pivots: mem::MaybeUninit::uninit().assume_init(), len: 2 };
            result.pivots[0] = left;
            result.pivots[1] = right;
            result
        }
    }
    fn valid_pivots_mut(&mut self) -> &mut [Pivot<K, V>] {
        &mut self.pivots[0..self.len]
    }

    fn valid_pivots(&self) -> &[Pivot<K, V>] {
        &self.pivots[0..self.len]
    }
}

enum Node<K, V> {
    Branch(BranchNode<K, V>),
    Leaf(LeafNode<K, V>),
}

impl<K, V> Node<K, V>
where
    K: Copy + Ord,
    V: Clone,
{
    fn min_key(&self) -> K {
        match *self {
            Node::Branch(ref branch) => {
                debug_assert!(branch.len > 1);
                branch.pivots[0].min_key
            }
            Node::Leaf(ref leaf) => {
                debug_assert_ne!(leaf.len, 0);
                leaf.elements[0].0
            }
        }
    }

    fn insert(&mut self, key: K, value: V) {
        let replace_node: Option<Self> = match *self {
            Node::Branch(ref mut branch) => {
                // Find a child node whose keys are not before the target key
                match branch.valid_pivots().iter().position(|ref p| key <= p.min_key) {
                    Some(i) => {
                        // If there is one, insert into it and update the pivot key
                        let pivot = &mut branch.pivots[i];
                        pivot.min_key = key;
                        pivot.child.insert(key, value)
                    }
                    // o/w, insert a new leaf at the end
                    None => {
                        branch.pivots[branch.len] =
                            Pivot { min_key: key, child: Box::new(Node::Leaf(LeafNode::empty())) };
                        branch.len += 1
                        // XXX consider splitting branch
                    }
                };
                None
            }
            Node::Leaf(ref mut leaf) => {
                let index = leaf.valid_elements_mut().binary_search_by_key(&key, |&(k, _)| k);
                match index {
                    Err(i) => {
                        // key is absent, true insert
                        if leaf.len < MAX_VALUES_PER_LEAF {
                            // there's space left, just insert
                            unsafe { slice_insert(leaf.valid_elements_mut(), i, (key, value)) }
                            leaf.len += 1;
                            None
                        } else {
                            // must split the node: create the new node here
                            let new_branch = {
                                let (left, right) =
                                    leaf.valid_elements_mut().split_at(MAX_VALUES_PER_LEAF / 2);
                                let left_leaf = Box::new(Node::Leaf(LeafNode::from(left)));
                                let right_leaf = Box::new(Node::Leaf(LeafNode::from(right)));
                                Node::Branch(BranchNode::from(
                                    Pivot { min_key: left_leaf.min_key(), child: left_leaf },
                                    Pivot { min_key: right_leaf.min_key(), child: right_leaf },
                                ))
                            };
                            Some(new_branch)
                        }
                    }
                    // key is present, replace
                    Ok(i) => {
                        leaf.elements[i] = (key, value);
                        None
                    }
                }
            }
        };
        if let Some(new_branch) = replace_node {
            *self = new_branch
        }
    }

    fn delete(&mut self, key: K) {
        match *self {
            Node::Branch(ref mut branch) => {
                // Find a child node whose keys are not before the target key
                if let Some(ref mut pivot) =
                    branch.valid_pivots_mut().iter_mut().find(|ref p| key <= p.min_key)
                {
                    // If there is one, delete from it and update the pivot key
                    pivot.child.delete(key);
                    pivot.min_key = pivot.child.min_key()
                }
            }
            Node::Leaf(ref mut leaf) if leaf.len > 0 => {
                let index = leaf.valid_elements_mut().binary_search_by_key(&key, |&(k, _)| k);
                match index {
                    Err(_) => (),
                    Ok(i) => unsafe {
                        slice_remove(leaf.valid_elements_mut(), i);
                        leaf.len -= 1;
                    },
                }
            }
            _ => (),
        }
    }

    fn get(&self, key: K) -> Option<&V> {
        match *self {
            Node::Branch(ref branch) => {
                // Find a child node whose keys are not before the target key
                match branch.valid_pivots().iter().find(|ref p| key <= p.min_key) {
                    Some(ref pivot) => {
                        // If there is one, query it
                        pivot.child.get(key)
                    }
                    // o/w, the key doesn't exist
                    None => None,
                }
            }
            Node::Leaf(ref leaf) if leaf.len > 0 => {
                let index = leaf.valid_elements().binary_search_by_key(&key, |&(k, _)| k);
                match index {
                    Err(_) => None,
                    Ok(i) => Some(&leaf.elements[i].1),
                }
            }
            _ => None,
        }
    }
}

unsafe fn slice_insert<T>(slice: &mut [T], idx: usize, val: T) {
    ptr::copy(
        slice.as_mut_ptr().add(idx),
        slice.as_mut_ptr().offset(idx as isize + 1),
        slice.len() - idx,
    );
    ptr::write(slice.get_unchecked_mut(idx), val);
}

unsafe fn slice_remove<T>(slice: &mut [T], idx: usize) -> T {
    let ret = ptr::read(slice.get_unchecked(idx));
    ptr::copy(
        slice.as_ptr().offset(idx as isize + 1),
        slice.as_mut_ptr().add(idx),
        slice.len() - idx - 1,
    );
    ret
}

/// A map based on a B๐›†-tree
pub struct BeTree<K, V> {
    root: Node<K, V>,
}

impl<K, V> BeTree<K, V>
where
    K: Copy + Ord,
    V: Clone,
{
    /// Create an empty B๐›†-tree.
    pub fn new() -> Self {
        BeTree { root: Node::Leaf(LeafNode::empty()) }
    }

    /// Clear the tree, removing all entries.
    pub fn clear(&mut self) {
        match self.root {
            Node::Leaf(ref mut leaf) => leaf.len = 0,
            _ => self.root = Node::Leaf(LeafNode::empty()),
        }
    }

    /// Insert a key-value pair into the tree.
    ///
    /// If the key is already present in the tree, the value is replaced. The key is not updated, though; this matters for
    /// types that can be `==` without being identical.
    pub fn insert(&mut self, key: K, value: V) {
        self.root.insert(key, value)
    }

    /// Remove a key (and its value) from the tree.
    ///
    /// If the key is not present, silently does nothing.
    pub fn delete(&mut self, key: K) {
        self.root.delete(key)
    }

    /// Retrieve a reference to the value corresponding to the key.
    pub fn get(&self, key: K) -> Option<&V> {
        self.root.get(key)
    }
}

impl<K, V> Default for BeTree<K, V>
where
    K: Copy + Ord,
    V: Clone,
{
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::{BeTree, MAX_VALUES_PER_LEAF};

    #[test]
    fn can_construct() {
        BeTree::<i32, char>::new();
    }

    #[test]
    fn can_insert_single() {
        let mut b = BeTree::new();
        b.insert(0, 'x');
        let result = b.get(0);
        assert_eq!(Some(&'x'), result);
    }

    #[test]
    fn can_insert_two() {
        let mut b = BeTree::new();
        b.insert(0, 'x');
        b.insert(-1, 'y');
        assert_eq!(Some(&'x'), b.get(0));
        assert_eq!(Some(&'y'), b.get(-1));
    }

    #[test]
    fn can_split() {
        let mut b = BeTree::new();
        // insert MAX_VALUES_PER_LEAF + 1 items
        for i in 0..MAX_VALUES_PER_LEAF {
            b.insert(i, i);
        }
        // are they all there?
        for i in 0..MAX_VALUES_PER_LEAF {
            assert_eq!(Some(&i), b.get(i));
        }
    }

    #[test]
    fn can_clear() {
        let mut b = BeTree::new();
        b.insert(0, 'x');
        b.insert(-1, 'y');
        b.clear();
        assert_eq!(None, b.get(0));
    }

    #[test]
    fn insert_replaces_existing() {
        let mut b = BeTree::new();
        b.insert(0, 'x');
        b.insert(0, 'y');
        assert_eq!(Some(&'y'), b.get(0));
    }

    #[test]
    fn can_delete_existing() {
        let mut b = BeTree::new();
        b.insert(0, 'x');
        b.delete(0);
        assert_eq!(b.get(0), None)
    }

    #[test]
    fn can_delete_only_existing() {
        let mut b = BeTree::new();
        b.insert(0, 'x');
        b.insert(2, 'y');
        b.delete(0);
        assert_eq!(b.get(0), None);
        assert_eq!(Some(&'y'), b.get(2));
    }

    #[test]
    fn can_delete_nothing() {
        let mut b = BeTree::<i32, char>::new();
        b.delete(0);
    }
}