1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 // This is an attempt at an implementation following the ideal
14 // struct BTreeMap<K, V> {
16 // root: Option<Box<Node<K, V, height>>>
19 // struct Node<K, V, height: usize> {
20 // keys: [K; 2 * B - 1],
21 // vals: [V; 2 * B - 1],
22 // edges: if height > 0 {
23 // [Box<Node<K, V, height - 1>>; 2 * B]
25 // parent: *const Node<K, V, height + 1>,
31 // Since Rust doesn't acutally have dependent types and polymorphic recursion,
32 // we make do with lots of unsafety.
35 use core::marker::PhantomData;
37 use core::nonzero::NonZero;
38 use core::ptr::{self, Unique};
44 pub const CAPACITY: usize = 2 * B - 1;
46 struct LeafNode<K, V> {
49 parent: *const InternalNode<K, V>,
54 impl<K, V> LeafNode<K, V> {
55 unsafe fn new() -> Self {
57 keys: mem::uninitialized(),
58 vals: mem::uninitialized(),
60 parent_idx: mem::uninitialized(),
66 // We use repr(C) so that a pointer to an internal node can be
67 // directly used as a pointer to a leaf node
69 struct InternalNode<K, V> {
71 edges: [BoxedNode<K, V>; 2 * B],
74 impl<K, V> InternalNode<K, V> {
75 unsafe fn new() -> Self {
77 data: LeafNode::new(),
78 edges: mem::uninitialized()
83 struct BoxedNode<K, V> {
84 ptr: Unique<LeafNode<K, V>> // we don't know if this points to a leaf node or an internal node
87 impl<K, V> BoxedNode<K, V> {
88 fn from_leaf(node: Box<LeafNode<K, V>>) -> Self {
90 BoxedNode { ptr: Unique::new(Box::into_raw(node)) }
94 fn from_internal(node: Box<InternalNode<K, V>>) -> Self {
96 BoxedNode { ptr: Unique::new(Box::into_raw(node) as *mut LeafNode<K, V>) }
100 unsafe fn from_ptr(ptr: NonZero<*const LeafNode<K, V>>) -> Self {
101 BoxedNode { ptr: Unique::new(*ptr as *mut LeafNode<K, V>) }
104 fn as_ptr(&self) -> NonZero<*const LeafNode<K, V>> {
106 NonZero::new(*self.ptr as *const LeafNode<K, V>)
111 /// An owned tree. Note that despite being owned, this does not have a destructor,
112 /// and must be cleaned up manually.
113 pub struct Root<K, V> {
114 node: BoxedNode<K, V>,
118 unsafe impl<K: Sync, V: Sync> Sync for Root<K, V> { }
119 unsafe impl<K: Send, V: Send> Send for Root<K, V> { }
121 impl<K, V> Root<K, V> {
122 pub fn new_leaf() -> Self {
124 node: BoxedNode::from_leaf(Box::new(unsafe { LeafNode::new() })),
130 -> NodeRef<marker::Immut, K, V, marker::LeafOrInternal> {
133 node: self.node.as_ptr(),
134 root: self as *const _ as *mut _,
135 _marker: PhantomData,
139 pub fn as_mut(&mut self)
140 -> NodeRef<marker::Mut, K, V, marker::LeafOrInternal> {
143 node: self.node.as_ptr(),
144 root: self as *mut _,
145 _marker: PhantomData,
149 pub fn into_ref(self)
150 -> NodeRef<marker::Owned, K, V, marker::LeafOrInternal> {
153 node: self.node.as_ptr(),
154 root: ptr::null_mut(), // FIXME: Is there anything better to do here?
155 _marker: PhantomData,
159 /// Add a new internal node with a single edge, pointing to the previous root, and make that
160 /// new node the root. This increases the height by 1 and is the opposite of `pop_level`.
161 pub fn push_level(&mut self)
162 -> NodeRef<marker::Mut, K, V, marker::Internal> {
163 let mut new_node = Box::new(unsafe { InternalNode::new() });
164 new_node.edges[0] = unsafe { BoxedNode::from_ptr(self.node.as_ptr()) };
166 self.node = BoxedNode::from_internal(new_node);
169 let mut ret = NodeRef {
171 node: self.node.as_ptr(),
172 root: self as *mut _,
177 ret.reborrow_mut().first_edge().correct_parent_link();
183 /// Remove the root node, using its first child as the new root. This cannot be called when
184 /// the tree consists only of a leaf node. As it is intended only to be called when the root
185 /// has only one edge, no cleanup is done on any of the other children are elements of the root.
186 /// This decreases the height by 1 and is the opposite of `push_level`.
187 pub fn pop_level(&mut self) {
188 debug_assert!(self.height > 0);
190 let top = *self.node.ptr as *mut u8;
193 BoxedNode::from_ptr(self.as_mut()
194 .cast_unchecked::<marker::Internal>()
200 self.as_mut().as_leaf_mut().parent = ptr::null();
205 mem::size_of::<InternalNode<K, V>>(),
206 mem::align_of::<InternalNode<K, V>>()
212 // N.B. `NodeRef` is always covariant in `K` and `V`, even when the `BorrowType`
213 // is `Mut`. This is technically wrong, but cannot result in any unsafety due to
214 // internal use of `NodeRef` because we stay completely generic over `K` and `V`.
215 // However, whenever a public type wraps `NodeRef`, make sure that it has the
217 /// A reference to a node.
219 /// This type has a number of paramaters that controls how it acts:
220 /// - `BorrowType`: This can be `Immut<'a>` or `Mut<'a>` for some `'a` or `Owned`.
221 /// When this is `Immut<'a>`, the `NodeRef` acts roughly like `&'a Node`,
222 /// when this is `Mut<'a>`, the `NodeRef` acts roughly like `&'a mut Node`,
223 /// and when this is `Owned`, the `NodeRef` acts roughly like `Box<Node>`.
224 /// - `K` and `V`: These control what types of things are stored in the nodes.
225 /// - `Type`: This can be `Leaf`, `Internal`, or `LeafOrInternal`. When this is
226 /// `Leaf`, the `NodeRef` points to a leaf node, when this is `Internal` the
227 /// `NodeRef` points to an internal node, and when this is `LeafOrInternal` the
228 /// `NodeRef` could be pointing to either type of node.
229 pub struct NodeRef<BorrowType, K, V, Type> {
231 node: NonZero<*const LeafNode<K, V>>,
232 root: *const Root<K, V>,
233 _marker: PhantomData<(BorrowType, Type)>
236 impl<'a, K: 'a, V: 'a, Type> Copy for NodeRef<marker::Immut<'a>, K, V, Type> { }
237 impl<'a, K: 'a, V: 'a, Type> Clone for NodeRef<marker::Immut<'a>, K, V, Type> {
238 fn clone(&self) -> Self {
243 unsafe impl<BorrowType, K: Sync, V: Sync, Type> Sync
244 for NodeRef<BorrowType, K, V, Type> { }
246 unsafe impl<'a, K: Sync + 'a, V: Sync + 'a, Type> Send
247 for NodeRef<marker::Immut<'a>, K, V, Type> { }
248 unsafe impl<'a, K: Send + 'a, V: Send + 'a, Type> Send
249 for NodeRef<marker::Mut<'a>, K, V, Type> { }
250 unsafe impl<K: Send, V: Send, Type> Send
251 for NodeRef<marker::Owned, K, V, Type> { }
253 impl<BorrowType, K, V> NodeRef<BorrowType, K, V, marker::Internal> {
254 fn as_internal(&self) -> &InternalNode<K, V> {
256 &*(*self.node as *const InternalNode<K, V>)
261 impl<'a, K, V> NodeRef<marker::Mut<'a>, K, V, marker::Internal> {
262 fn as_internal_mut(&mut self) -> &mut InternalNode<K, V> {
264 &mut *(*self.node as *mut InternalNode<K, V>)
270 impl<BorrowType, K, V, Type> NodeRef<BorrowType, K, V, Type> {
271 pub fn len(&self) -> usize {
272 self.as_leaf().len as usize
275 pub fn forget_type(self) -> NodeRef<BorrowType, K, V, marker::LeafOrInternal> {
284 fn reborrow<'a>(&'a self) -> NodeRef<marker::Immut<'a>, K, V, Type> {
293 fn as_leaf(&self) -> &LeafNode<K, V> {
299 pub fn keys(&self) -> &[K] {
300 self.reborrow().into_slices().0
303 pub fn vals(&self) -> &[V] {
304 self.reborrow().into_slices().1
307 pub fn ascend(self) -> Result<
318 if self.as_leaf().parent.is_null() {
323 height: self.height + 1,
325 NonZero::new(self.as_leaf().parent as *mut LeafNode<K, V>)
330 idx: self.as_leaf().parent_idx as usize,
336 pub fn first_edge(self) -> Handle<Self, marker::Edge> {
337 Handle::new_edge(self, 0)
340 pub fn last_edge(self) -> Handle<Self, marker::Edge> {
341 let len = self.len();
342 Handle::new_edge(self, len)
346 impl<K, V> NodeRef<marker::Owned, K, V, marker::Leaf> {
347 pub unsafe fn deallocate_and_ascend(self) -> Option<
357 let ptr = self.as_leaf() as *const LeafNode<K, V> as *const u8 as *mut u8;
358 let ret = self.ascend().ok();
359 heap::deallocate(ptr, mem::size_of::<LeafNode<K, V>>(), mem::align_of::<LeafNode<K, V>>());
364 impl<K, V> NodeRef<marker::Owned, K, V, marker::Internal> {
365 pub unsafe fn deallocate_and_ascend(self) -> Option<
375 let ptr = self.as_internal() as *const InternalNode<K, V> as *const u8 as *mut u8;
376 let ret = self.ascend().ok();
379 mem::size_of::<InternalNode<K, V>>(),
380 mem::align_of::<InternalNode<K, V>>()
386 impl<'a, K, V, Type> NodeRef<marker::Mut<'a>, K, V, Type> {
387 unsafe fn cast_unchecked<NewType>(&mut self)
388 -> NodeRef<marker::Mut, K, V, NewType> {
398 unsafe fn reborrow_mut(&mut self) -> NodeRef<marker::Mut, K, V, Type> {
407 fn as_leaf_mut(&mut self) -> &mut LeafNode<K, V> {
409 &mut *(*self.node as *mut LeafNode<K, V>)
413 pub fn keys_mut(&mut self) -> &mut [K] {
414 unsafe { self.reborrow_mut().into_slices_mut().0 }
417 pub fn vals_mut(&mut self) -> &mut [V] {
418 unsafe { self.reborrow_mut().into_slices_mut().1 }
422 impl<'a, K: 'a, V: 'a, Type> NodeRef<marker::Immut<'a>, K, V, Type> {
423 pub fn into_slices(self) -> (&'a [K], &'a [V]) {
426 slice::from_raw_parts(
427 self.as_leaf().keys.as_ptr(),
430 slice::from_raw_parts(
431 self.as_leaf().vals.as_ptr(),
439 impl<'a, K: 'a, V: 'a, Type> NodeRef<marker::Mut<'a>, K, V, Type> {
440 pub fn into_root_mut(self) -> &'a mut Root<K, V> {
442 &mut *(self.root as *mut Root<K, V>)
446 pub fn into_slices_mut(mut self) -> (&'a mut [K], &'a mut [V]) {
449 slice::from_raw_parts_mut(
450 &mut self.as_leaf_mut().keys as *mut [K] as *mut K,
453 slice::from_raw_parts_mut(
454 &mut self.as_leaf_mut().vals as *mut [V] as *mut V,
462 impl<'a, K, V> NodeRef<marker::Mut<'a>, K, V, marker::Leaf> {
463 pub fn push(&mut self, key: K, val: V) {
464 // Necessary for correctness, but this is an internal module
465 debug_assert!(self.len() < CAPACITY);
467 let idx = self.len();
470 ptr::write(self.keys_mut().get_unchecked_mut(idx), key);
471 ptr::write(self.vals_mut().get_unchecked_mut(idx), val);
474 self.as_leaf_mut().len += 1;
477 pub fn push_front(&mut self, key: K, val: V) {
478 // Necessary for correctness, but this is an internal module
479 debug_assert!(self.len() < CAPACITY);
482 slice_insert(self.keys_mut(), 0, key);
483 slice_insert(self.vals_mut(), 0, val);
486 self.as_leaf_mut().len += 1;
490 impl<'a, K, V> NodeRef<marker::Mut<'a>, K, V, marker::Internal> {
491 pub fn push(&mut self, key: K, val: V, edge: Root<K, V>) {
492 // Necessary for correctness, but this is an internal module
493 debug_assert!(edge.height == self.height - 1);
494 debug_assert!(self.len() < CAPACITY);
496 let idx = self.len();
499 ptr::write(self.keys_mut().get_unchecked_mut(idx), key);
500 ptr::write(self.vals_mut().get_unchecked_mut(idx), val);
501 ptr::write(self.as_internal_mut().edges.get_unchecked_mut(idx + 1), edge.node);
503 self.as_leaf_mut().len += 1;
505 Handle::new_edge(self.reborrow_mut(), idx + 1).correct_parent_link();
509 pub fn push_front(&mut self, key: K, val: V, edge: Root<K, V>) {
510 // Necessary for correctness, but this is an internal module
511 debug_assert!(edge.height == self.height - 1);
512 debug_assert!(self.len() < CAPACITY);
515 slice_insert(self.keys_mut(), 0, key);
516 slice_insert(self.vals_mut(), 0, val);
518 slice::from_raw_parts_mut(
519 self.as_internal_mut().edges.as_mut_ptr(),
526 self.as_leaf_mut().len += 1;
528 for i in 0..self.len()+1 {
529 Handle::new_edge(self.reborrow_mut(), i).correct_parent_link();
536 impl<'a, K, V> NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal> {
537 pub fn pop(&mut self) -> (K, V, Option<Root<K, V>>) {
538 // Necessary for correctness, but this is an internal module
539 debug_assert!(self.len() > 0);
541 let idx = self.len() - 1;
544 let key = ptr::read(self.keys().get_unchecked(idx));
545 let val = ptr::read(self.vals().get_unchecked(idx));
546 let edge = match self.reborrow_mut().force() {
547 ForceResult::Leaf(_) => None,
548 ForceResult::Internal(internal) => {
549 let edge = ptr::read(internal.as_internal().edges.get_unchecked(idx + 1));
550 let mut new_root = Root { node: edge, height: internal.height - 1 };
551 new_root.as_mut().as_leaf_mut().parent = ptr::null();
556 self.as_leaf_mut().len -= 1;
561 pub fn pop_front(&mut self) -> (K, V, Option<Root<K, V>>) {
562 // Necessary for correctness, but this is an internal module
563 debug_assert!(self.len() > 0);
565 let old_len = self.len();
568 let key = slice_remove(self.keys_mut(), 0);
569 let val = slice_remove(self.vals_mut(), 0);
570 let edge = match self.reborrow_mut().force() {
571 ForceResult::Leaf(_) => None,
572 ForceResult::Internal(mut internal) => {
573 let edge = slice_remove(
574 slice::from_raw_parts_mut(
575 internal.as_internal_mut().edges.as_mut_ptr(),
581 let mut new_root = Root { node: edge, height: internal.height - 1 };
582 new_root.as_mut().as_leaf_mut().parent = ptr::null();
584 for i in 0..old_len {
585 Handle::new_edge(internal.reborrow_mut(), i).correct_parent_link();
592 self.as_leaf_mut().len -= 1;
599 impl<BorrowType, K, V> NodeRef<BorrowType, K, V, marker::LeafOrInternal> {
600 pub fn force(self) -> ForceResult<
601 NodeRef<BorrowType, K, V, marker::Leaf>,
602 NodeRef<BorrowType, K, V, marker::Internal>
604 if self.height == 0 {
605 ForceResult::Leaf(NodeRef {
612 ForceResult::Internal(NodeRef {
622 pub struct Handle<Node, Type> {
625 _marker: PhantomData<Type>
628 impl<Node: Copy, Type> Copy for Handle<Node, Type> { }
629 impl<Node: Copy, Type> Clone for Handle<Node, Type> {
630 fn clone(&self) -> Self {
635 impl<Node, Type> Handle<Node, Type> {
636 pub fn into_node(self) -> Node {
641 impl<BorrowType, K, V, NodeType> Handle<NodeRef<BorrowType, K, V, NodeType>, marker::KV> {
642 pub fn new_kv(node: NodeRef<BorrowType, K, V, NodeType>, idx: usize) -> Self {
643 // Necessary for correctness, but in a private module
644 debug_assert!(idx < node.len());
653 pub fn left_edge(self) -> Handle<NodeRef<BorrowType, K, V, NodeType>, marker::Edge> {
654 Handle::new_edge(self.node, self.idx)
657 pub fn right_edge(self) -> Handle<NodeRef<BorrowType, K, V, NodeType>, marker::Edge> {
658 Handle::new_edge(self.node, self.idx + 1)
662 impl<BorrowType, K, V, NodeType, HandleType> PartialEq
663 for Handle<NodeRef<BorrowType, K, V, NodeType>, HandleType> {
665 fn eq(&self, other: &Self) -> bool {
666 self.node.node == other.node.node && self.idx == other.idx
670 impl<BorrowType, K, V, NodeType, HandleType>
671 Handle<NodeRef<BorrowType, K, V, NodeType>, HandleType> {
673 pub fn reborrow(&self)
674 -> Handle<NodeRef<marker::Immut, K, V, NodeType>, HandleType> {
676 // We can't use Handle::new_kv or Handle::new_edge because we don't know our type
678 node: self.node.reborrow(),
685 impl<'a, K, V, NodeType, HandleType>
686 Handle<NodeRef<marker::Mut<'a>, K, V, NodeType>, HandleType> {
688 pub unsafe fn reborrow_mut(&mut self)
689 -> Handle<NodeRef<marker::Mut, K, V, NodeType>, HandleType> {
691 // We can't use Handle::new_kv or Handle::new_edge because we don't know our type
693 node: self.node.reborrow_mut(),
700 impl<BorrowType, K, V, NodeType>
701 Handle<NodeRef<BorrowType, K, V, NodeType>, marker::Edge> {
703 pub fn new_edge(node: NodeRef<BorrowType, K, V, NodeType>, idx: usize) -> Self {
704 // Necessary for correctness, but in a private module
705 debug_assert!(idx <= node.len());
715 -> Result<Handle<NodeRef<BorrowType, K, V, NodeType>, marker::KV>, Self> {
718 Ok(Handle::new_kv(self.node, self.idx - 1))
724 pub fn right_kv(self)
725 -> Result<Handle<NodeRef<BorrowType, K, V, NodeType>, marker::KV>, Self> {
727 if self.idx < self.node.len() {
728 Ok(Handle::new_kv(self.node, self.idx))
735 impl<'a, K, V> Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge> {
736 fn insert_fit(&mut self, key: K, val: V) -> *mut V {
737 // Necessary for correctness, but in a private module
738 debug_assert!(self.node.len() < CAPACITY);
741 slice_insert(self.node.keys_mut(), self.idx, key);
742 slice_insert(self.node.vals_mut(), self.idx, val);
744 self.node.as_leaf_mut().len += 1;
746 self.node.vals_mut().get_unchecked_mut(self.idx)
750 pub fn insert(mut self, key: K, val: V)
751 -> (InsertResult<'a, K, V, marker::Leaf>, *mut V) {
753 if self.node.len() < CAPACITY {
754 let ptr = self.insert_fit(key, val);
755 (InsertResult::Fit(Handle::new_kv(self.node, self.idx)), ptr)
757 let middle = Handle::new_kv(self.node, B);
758 let (mut left, k, v, mut right) = middle.split();
759 let ptr = if self.idx <= B {
761 Handle::new_edge(left.reborrow_mut(), self.idx).insert_fit(key, val)
766 right.as_mut().cast_unchecked::<marker::Leaf>(),
768 ).insert_fit(key, val)
771 (InsertResult::Split(left, k, v, right), ptr)
776 impl<'a, K, V> Handle<NodeRef<marker::Mut<'a>, K, V, marker::Internal>, marker::Edge> {
777 fn correct_parent_link(mut self) {
778 let idx = self.idx as u16;
779 let ptr = self.node.as_internal_mut() as *mut _;
780 let mut child = self.descend();
781 child.as_leaf_mut().parent = ptr;
782 child.as_leaf_mut().parent_idx = idx;
785 unsafe fn cast_unchecked<NewType>(&mut self)
786 -> Handle<NodeRef<marker::Mut, K, V, NewType>, marker::Edge> {
788 Handle::new_edge(self.node.cast_unchecked(), self.idx)
791 fn insert_fit(&mut self, key: K, val: V, edge: Root<K, V>) {
792 // Necessary for correctness, but in an internal module
793 debug_assert!(self.node.len() < CAPACITY);
794 debug_assert!(edge.height == self.node.height - 1);
797 self.cast_unchecked::<marker::Leaf>().insert_fit(key, val);
800 slice::from_raw_parts_mut(
801 self.node.as_internal_mut().edges.as_mut_ptr(),
808 for i in (self.idx+1)..(self.node.len()+1) {
809 Handle::new_edge(self.node.reborrow_mut(), i).correct_parent_link();
814 pub fn insert(mut self, key: K, val: V, edge: Root<K, V>)
815 -> InsertResult<'a, K, V, marker::Internal> {
817 // Necessary for correctness, but this is an internal module
818 debug_assert!(edge.height == self.node.height - 1);
820 if self.node.len() < CAPACITY {
821 self.insert_fit(key, val, edge);
822 InsertResult::Fit(Handle::new_kv(self.node, self.idx))
824 let middle = Handle::new_kv(self.node, B);
825 let (mut left, k, v, mut right) = middle.split();
828 Handle::new_edge(left.reborrow_mut(), self.idx).insert_fit(key, val, edge);
833 right.as_mut().cast_unchecked::<marker::Internal>(),
835 ).insert_fit(key, val, edge);
838 InsertResult::Split(left, k, v, right)
843 impl<BorrowType, K, V>
844 Handle<NodeRef<BorrowType, K, V, marker::Internal>, marker::Edge> {
846 pub fn descend(self) -> NodeRef<BorrowType, K, V, marker::LeafOrInternal> {
848 height: self.node.height - 1,
849 node: unsafe { self.node.as_internal().edges.get_unchecked(self.idx).as_ptr() },
850 root: self.node.root,
856 impl<'a, K: 'a, V: 'a, NodeType>
857 Handle<NodeRef<marker::Immut<'a>, K, V, NodeType>, marker::KV> {
859 pub fn into_kv(self) -> (&'a K, &'a V) {
860 let (keys, vals) = self.node.into_slices();
862 (keys.get_unchecked(self.idx), vals.get_unchecked(self.idx))
867 impl<'a, K: 'a, V: 'a, NodeType>
868 Handle<NodeRef<marker::Mut<'a>, K, V, NodeType>, marker::KV> {
870 pub fn into_kv_mut(self) -> (&'a mut K, &'a mut V) {
871 let (mut keys, mut vals) = self.node.into_slices_mut();
873 (keys.get_unchecked_mut(self.idx), vals.get_unchecked_mut(self.idx))
878 impl<'a, K, V, NodeType> Handle<NodeRef<marker::Mut<'a>, K, V, NodeType>, marker::KV> {
879 pub fn kv_mut(&mut self) -> (&mut K, &mut V) {
881 let (mut keys, mut vals) = self.node.reborrow_mut().into_slices_mut();
882 (keys.get_unchecked_mut(self.idx), vals.get_unchecked_mut(self.idx))
887 impl<'a, K, V> Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::KV> {
888 pub fn split(mut self)
889 -> (NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, K, V, Root<K, V>) {
891 let mut new_node = Box::new(LeafNode::new());
893 let k = ptr::read(self.node.keys().get_unchecked(self.idx));
894 let v = ptr::read(self.node.vals().get_unchecked(self.idx));
896 let new_len = self.node.len() - self.idx - 1;
898 ptr::copy_nonoverlapping(
899 self.node.keys().as_ptr().offset(self.idx as isize + 1),
900 new_node.keys.as_mut_ptr(),
903 ptr::copy_nonoverlapping(
904 self.node.vals().as_ptr().offset(self.idx as isize + 1),
905 new_node.vals.as_mut_ptr(),
909 self.node.as_leaf_mut().len = self.idx as u16;
910 new_node.len = new_len as u16;
916 node: BoxedNode::from_leaf(new_node),
923 pub fn remove(mut self)
924 -> (Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge>, K, V) {
926 let k = slice_remove(self.node.keys_mut(), self.idx);
927 let v = slice_remove(self.node.vals_mut(), self.idx);
928 self.node.as_leaf_mut().len -= 1;
929 (self.left_edge(), k, v)
934 impl<'a, K, V> Handle<NodeRef<marker::Mut<'a>, K, V, marker::Internal>, marker::KV> {
935 pub fn split(mut self)
936 -> (NodeRef<marker::Mut<'a>, K, V, marker::Internal>, K, V, Root<K, V>) {
938 let mut new_node = Box::new(InternalNode::new());
940 let k = ptr::read(self.node.keys().get_unchecked(self.idx));
941 let v = ptr::read(self.node.vals().get_unchecked(self.idx));
943 let height = self.node.height;
944 let new_len = self.node.len() - self.idx - 1;
946 ptr::copy_nonoverlapping(
947 self.node.keys().as_ptr().offset(self.idx as isize + 1),
948 new_node.data.keys.as_mut_ptr(),
951 ptr::copy_nonoverlapping(
952 self.node.vals().as_ptr().offset(self.idx as isize + 1),
953 new_node.data.vals.as_mut_ptr(),
956 ptr::copy_nonoverlapping(
957 self.node.as_internal().edges.as_ptr().offset(self.idx as isize + 1),
958 new_node.edges.as_mut_ptr(),
962 self.node.as_leaf_mut().len = self.idx as u16;
963 new_node.data.len = new_len as u16;
965 let mut new_root = Root {
966 node: BoxedNode::from_internal(new_node),
970 for i in 0..(new_len+1) {
971 Handle::new_edge(new_root.as_mut().cast_unchecked(), i).correct_parent_link();
982 pub fn can_merge(&self) -> bool {
996 pub fn merge(mut self)
997 -> Handle<NodeRef<marker::Mut<'a>, K, V, marker::Internal>, marker::Edge> {
998 let self1 = unsafe { ptr::read(&self) };
999 let self2 = unsafe { ptr::read(&self) };
1000 let mut left_node = self1.left_edge().descend();
1001 let left_len = left_node.len();
1002 let mut right_node = self2.right_edge().descend();
1003 let right_len = right_node.len();
1005 // necessary for correctness, but in a private module
1006 debug_assert!(left_len + right_len + 1 <= CAPACITY);
1009 ptr::write(left_node.keys_mut().get_unchecked_mut(left_len),
1010 slice_remove(self.node.keys_mut(), self.idx));
1011 ptr::copy_nonoverlapping(
1012 right_node.keys().as_ptr(),
1013 left_node.keys_mut().as_mut_ptr().offset(left_len as isize + 1),
1016 ptr::write(left_node.vals_mut().get_unchecked_mut(left_len),
1017 slice_remove(self.node.vals_mut(), self.idx));
1018 ptr::copy_nonoverlapping(
1019 right_node.vals().as_ptr(),
1020 left_node.vals_mut().as_mut_ptr().offset(left_len as isize + 1),
1024 slice_remove(&mut self.node.as_internal_mut().edges, self.idx + 1);
1025 for i in self.idx+1..self.node.len() {
1026 Handle::new_edge(self.node.reborrow_mut(), i).correct_parent_link();
1028 self.node.as_leaf_mut().len -= 1;
1030 if self.node.height > 1 {
1031 ptr::copy_nonoverlapping(
1032 right_node.cast_unchecked().as_internal().edges.as_ptr(),
1033 left_node.cast_unchecked()
1037 .offset(left_len as isize + 1),
1041 for i in left_len+1..left_len+right_len+2 {
1043 left_node.cast_unchecked().reborrow_mut(),
1045 ).correct_parent_link();
1049 *right_node.node as *mut u8,
1050 mem::size_of::<InternalNode<K, V>>(),
1051 mem::align_of::<InternalNode<K, V>>()
1055 *right_node.node as *mut u8,
1056 mem::size_of::<LeafNode<K, V>>(),
1057 mem::align_of::<LeafNode<K, V>>()
1061 left_node.as_leaf_mut().len += right_len as u16 + 1;
1063 Handle::new_edge(self.node, self.idx)
1068 impl<BorrowType, K, V, HandleType>
1069 Handle<NodeRef<BorrowType, K, V, marker::LeafOrInternal>, HandleType> {
1071 pub fn force(self) -> ForceResult<
1072 Handle<NodeRef<BorrowType, K, V, marker::Leaf>, HandleType>,
1073 Handle<NodeRef<BorrowType, K, V, marker::Internal>, HandleType>
1075 match self.node.force() {
1076 ForceResult::Leaf(node) => ForceResult::Leaf(Handle {
1079 _marker: PhantomData
1081 ForceResult::Internal(node) => ForceResult::Internal(Handle {
1084 _marker: PhantomData
1090 pub enum ForceResult<Leaf, Internal> {
1095 pub enum InsertResult<'a, K, V, Type> {
1096 Fit(Handle<NodeRef<marker::Mut<'a>, K, V, Type>, marker::KV>),
1097 Split(NodeRef<marker::Mut<'a>, K, V, Type>, K, V, Root<K, V>)
1101 use core::marker::PhantomData;
1104 pub enum Internal { }
1105 pub enum LeafOrInternal { }
1108 pub struct Immut<'a>(PhantomData<&'a ()>);
1109 pub struct Mut<'a>(PhantomData<&'a mut ()>);
1115 unsafe fn slice_insert<T>(slice: &mut [T], idx: usize, val: T) {
1117 slice.as_ptr().offset(idx as isize),
1118 slice.as_mut_ptr().offset(idx as isize + 1),
1121 ptr::write(slice.get_unchecked_mut(idx), val);
1124 unsafe fn slice_remove<T>(slice: &mut [T], idx: usize) -> T {
1125 let ret = ptr::read(slice.get_unchecked(idx));
1127 slice.as_ptr().offset(idx as isize + 1),
1128 slice.as_mut_ptr().offset(idx as isize),
1129 slice.len() - idx - 1