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<*mut LeafNode<K, V>>) -> Self {
101 BoxedNode { ptr: Unique::new(*ptr) }
104 fn as_ptr(&self) -> NonZero<*mut LeafNode<K, V>> {
106 NonZero::new(*self.ptr)
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 /// A reference to a node.
214 /// This type has a number of paramaters that controls how it acts:
215 /// - `BorrowType`: This can be `Immut<'a>` or `Mut<'a>` for some `'a` or `Owned`.
216 /// When this is `Immut<'a>`, the `NodeRef` acts roughly like `&'a Node`,
217 /// when this is `Mut<'a>`, the `NodeRef` acts roughly like `&'a mut Node`,
218 /// and when this is `Owned`, the `NodeRef` acts roughly like `Box<Node>`.
219 /// - `K` and `V`: These control what types of things are stored in the nodes.
220 /// - `Type`: This can be `Leaf`, `Internal`, or `LeafOrInternal`. When this is
221 /// `Leaf`, the `NodeRef` points to a leaf node, when this is `Internal` the
222 /// `NodeRef` points to an internal node, and when this is `LeafOrInternal` the
223 /// `NodeRef` could be pointing to either type of node.
224 pub struct NodeRef<BorrowType, K, V, Type> {
226 node: NonZero<*mut LeafNode<K, V>>,
227 root: *mut Root<K, V>,
228 _marker: PhantomData<(BorrowType, Type)>
231 impl<'a, K: 'a, V: 'a, Type> Copy for NodeRef<marker::Immut<'a>, K, V, Type> { }
232 impl<'a, K: 'a, V: 'a, Type> Clone for NodeRef<marker::Immut<'a>, K, V, Type> {
233 fn clone(&self) -> Self {
238 unsafe impl<BorrowType, K: Sync, V: Sync, Type> Sync
239 for NodeRef<BorrowType, K, V, Type> { }
241 unsafe impl<'a, K: Sync + 'a, V: Sync + 'a, Type> Send
242 for NodeRef<marker::Immut<'a>, K, V, Type> { }
243 unsafe impl<'a, K: Send + 'a, V: Send + 'a, Type> Send
244 for NodeRef<marker::Mut<'a>, K, V, Type> { }
245 unsafe impl<K: Send, V: Send, Type> Send
246 for NodeRef<marker::Owned, K, V, Type> { }
248 impl<BorrowType, K, V> NodeRef<BorrowType, K, V, marker::Internal> {
249 fn as_internal(&self) -> &InternalNode<K, V> {
251 &*(*self.node as *const InternalNode<K, V>)
256 impl<'a, K, V> NodeRef<marker::Mut<'a>, K, V, marker::Internal> {
257 fn as_internal_mut(&mut self) -> &mut InternalNode<K, V> {
259 &mut *(*self.node as *mut InternalNode<K, V>)
265 impl<BorrowType, K, V, Type> NodeRef<BorrowType, K, V, Type> {
266 pub fn len(&self) -> usize {
267 self.as_leaf().len as usize
270 pub fn forget_type(self) -> NodeRef<BorrowType, K, V, marker::LeafOrInternal> {
279 fn reborrow<'a>(&'a self) -> NodeRef<marker::Immut<'a>, K, V, Type> {
288 fn as_leaf(&self) -> &LeafNode<K, V> {
294 pub fn keys(&self) -> &[K] {
295 self.reborrow().into_slices().0
298 pub fn vals(&self) -> &[V] {
299 self.reborrow().into_slices().1
302 pub fn ascend(self) -> Result<
313 if self.as_leaf().parent.is_null() {
318 height: self.height + 1,
320 NonZero::new(self.as_leaf().parent as *mut LeafNode<K, V>)
325 idx: self.as_leaf().parent_idx as usize,
331 pub fn first_edge(self) -> Handle<Self, marker::Edge> {
332 Handle::new_edge(self, 0)
335 pub fn last_edge(self) -> Handle<Self, marker::Edge> {
336 let len = self.len();
337 Handle::new_edge(self, len)
341 impl<K, V> NodeRef<marker::Owned, K, V, marker::Leaf> {
342 pub unsafe fn deallocate_and_ascend(self) -> Option<
352 let ptr = self.as_leaf() as *const LeafNode<K, V> as *const u8 as *mut u8;
353 let ret = self.ascend().ok();
354 heap::deallocate(ptr, mem::size_of::<LeafNode<K, V>>(), mem::align_of::<LeafNode<K, V>>());
359 impl<K, V> NodeRef<marker::Owned, K, V, marker::Internal> {
360 pub unsafe fn deallocate_and_ascend(self) -> Option<
370 let ptr = self.as_internal() as *const InternalNode<K, V> as *const u8 as *mut u8;
371 let ret = self.ascend().ok();
374 mem::size_of::<InternalNode<K, V>>(),
375 mem::align_of::<InternalNode<K, V>>()
381 impl<'a, K, V, Type> NodeRef<marker::Mut<'a>, K, V, Type> {
382 unsafe fn cast_unchecked<NewType>(&mut self)
383 -> NodeRef<marker::Mut, K, V, NewType> {
393 unsafe fn reborrow_mut(&mut self) -> NodeRef<marker::Mut, K, V, Type> {
402 fn as_leaf_mut(&mut self) -> &mut LeafNode<K, V> {
408 pub fn keys_mut(&mut self) -> &mut [K] {
409 unsafe { self.reborrow_mut().into_slices_mut().0 }
412 pub fn vals_mut(&mut self) -> &mut [V] {
413 unsafe { self.reborrow_mut().into_slices_mut().1 }
417 impl<'a, K: 'a, V: 'a, Type> NodeRef<marker::Immut<'a>, K, V, Type> {
418 pub fn into_slices(self) -> (&'a [K], &'a [V]) {
421 slice::from_raw_parts(
422 self.as_leaf().keys.as_ptr(),
425 slice::from_raw_parts(
426 self.as_leaf().vals.as_ptr(),
434 impl<'a, K: 'a, V: 'a, Type> NodeRef<marker::Mut<'a>, K, V, Type> {
435 pub fn into_root_mut(self) -> &'a mut Root<K, V> {
441 pub fn into_slices_mut(mut self) -> (&'a mut [K], &'a mut [V]) {
444 slice::from_raw_parts_mut(
445 &mut self.as_leaf_mut().keys as *mut [K] as *mut K,
448 slice::from_raw_parts_mut(
449 &mut self.as_leaf_mut().vals as *mut [V] as *mut V,
457 impl<'a, K, V> NodeRef<marker::Mut<'a>, K, V, marker::Leaf> {
458 pub fn push(&mut self, key: K, val: V) {
459 // Necessary for correctness, but this is an internal module
460 debug_assert!(self.len() < CAPACITY);
462 let idx = self.len();
465 ptr::write(self.keys_mut().get_unchecked_mut(idx), key);
466 ptr::write(self.vals_mut().get_unchecked_mut(idx), val);
469 self.as_leaf_mut().len += 1;
472 pub fn push_front(&mut self, key: K, val: V) {
473 // Necessary for correctness, but this is an internal module
474 debug_assert!(self.len() < CAPACITY);
477 slice_insert(self.keys_mut(), 0, key);
478 slice_insert(self.vals_mut(), 0, val);
481 self.as_leaf_mut().len += 1;
485 impl<'a, K, V> NodeRef<marker::Mut<'a>, K, V, marker::Internal> {
486 pub fn push(&mut self, key: K, val: V, edge: Root<K, V>) {
487 // Necessary for correctness, but this is an internal module
488 debug_assert!(edge.height == self.height - 1);
489 debug_assert!(self.len() < CAPACITY);
491 let idx = self.len();
494 ptr::write(self.keys_mut().get_unchecked_mut(idx), key);
495 ptr::write(self.vals_mut().get_unchecked_mut(idx), val);
496 ptr::write(self.as_internal_mut().edges.get_unchecked_mut(idx + 1), edge.node);
498 self.as_leaf_mut().len += 1;
500 Handle::new_edge(self.reborrow_mut(), idx + 1).correct_parent_link();
504 pub fn push_front(&mut self, key: K, val: V, edge: Root<K, V>) {
505 // Necessary for correctness, but this is an internal module
506 debug_assert!(edge.height == self.height - 1);
507 debug_assert!(self.len() < CAPACITY);
510 slice_insert(self.keys_mut(), 0, key);
511 slice_insert(self.vals_mut(), 0, val);
513 slice::from_raw_parts_mut(
514 self.as_internal_mut().edges.as_mut_ptr(),
521 self.as_leaf_mut().len += 1;
523 for i in 0..self.len()+1 {
524 Handle::new_edge(self.reborrow_mut(), i).correct_parent_link();
531 impl<'a, K, V> NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal> {
532 pub fn pop(&mut self) -> (K, V, Option<Root<K, V>>) {
533 // Necessary for correctness, but this is an internal module
534 debug_assert!(self.len() > 0);
536 let idx = self.len() - 1;
539 let key = ptr::read(self.keys().get_unchecked(idx));
540 let val = ptr::read(self.vals().get_unchecked(idx));
541 let edge = match self.reborrow_mut().force() {
542 ForceResult::Leaf(_) => None,
543 ForceResult::Internal(internal) => {
544 let edge = ptr::read(internal.as_internal().edges.get_unchecked(idx + 1));
545 let mut new_root = Root { node: edge, height: internal.height - 1 };
546 new_root.as_mut().as_leaf_mut().parent = ptr::null();
551 self.as_leaf_mut().len -= 1;
556 pub fn pop_front(&mut self) -> (K, V, Option<Root<K, V>>) {
557 // Necessary for correctness, but this is an internal module
558 debug_assert!(self.len() > 0);
560 let old_len = self.len();
563 let key = slice_remove(self.keys_mut(), 0);
564 let val = slice_remove(self.vals_mut(), 0);
565 let edge = match self.reborrow_mut().force() {
566 ForceResult::Leaf(_) => None,
567 ForceResult::Internal(mut internal) => {
568 let edge = slice_remove(
569 slice::from_raw_parts_mut(
570 internal.as_internal_mut().edges.as_mut_ptr(),
576 let mut new_root = Root { node: edge, height: internal.height - 1 };
577 new_root.as_mut().as_leaf_mut().parent = ptr::null();
579 for i in 0..old_len {
580 Handle::new_edge(internal.reborrow_mut(), i).correct_parent_link();
587 self.as_leaf_mut().len -= 1;
594 impl<BorrowType, K, V> NodeRef<BorrowType, K, V, marker::LeafOrInternal> {
595 pub fn force(self) -> ForceResult<
596 NodeRef<BorrowType, K, V, marker::Leaf>,
597 NodeRef<BorrowType, K, V, marker::Internal>
599 if self.height == 0 {
600 ForceResult::Leaf(NodeRef {
607 ForceResult::Internal(NodeRef {
617 pub struct Handle<Node, Type> {
620 _marker: PhantomData<Type>
623 impl<Node: Copy, Type> Copy for Handle<Node, Type> { }
624 impl<Node: Copy, Type> Clone for Handle<Node, Type> {
625 fn clone(&self) -> Self {
630 impl<Node, Type> Handle<Node, Type> {
631 pub fn into_node(self) -> Node {
636 impl<BorrowType, K, V, NodeType> Handle<NodeRef<BorrowType, K, V, NodeType>, marker::KV> {
637 pub fn new_kv(node: NodeRef<BorrowType, K, V, NodeType>, idx: usize) -> Self {
638 // Necessary for correctness, but in a private module
639 debug_assert!(idx < node.len());
648 pub fn left_edge(self) -> Handle<NodeRef<BorrowType, K, V, NodeType>, marker::Edge> {
649 Handle::new_edge(self.node, self.idx)
652 pub fn right_edge(self) -> Handle<NodeRef<BorrowType, K, V, NodeType>, marker::Edge> {
653 Handle::new_edge(self.node, self.idx + 1)
657 impl<BorrowType, K, V, NodeType, HandleType> PartialEq
658 for Handle<NodeRef<BorrowType, K, V, NodeType>, HandleType> {
660 fn eq(&self, other: &Self) -> bool {
661 self.node.node == other.node.node && self.idx == other.idx
665 impl<BorrowType, K, V, NodeType, HandleType>
666 Handle<NodeRef<BorrowType, K, V, NodeType>, HandleType> {
668 pub fn reborrow(&self)
669 -> Handle<NodeRef<marker::Immut, K, V, NodeType>, HandleType> {
671 // We can't use Handle::new_kv or Handle::new_edge because we don't know our type
673 node: self.node.reborrow(),
680 impl<'a, K, V, NodeType, HandleType>
681 Handle<NodeRef<marker::Mut<'a>, K, V, NodeType>, HandleType> {
683 pub unsafe fn reborrow_mut(&mut self)
684 -> Handle<NodeRef<marker::Mut, K, V, NodeType>, HandleType> {
686 // We can't use Handle::new_kv or Handle::new_edge because we don't know our type
688 node: self.node.reborrow_mut(),
695 impl<BorrowType, K, V, NodeType>
696 Handle<NodeRef<BorrowType, K, V, NodeType>, marker::Edge> {
698 pub fn new_edge(node: NodeRef<BorrowType, K, V, NodeType>, idx: usize) -> Self {
699 // Necessary for correctness, but in a private module
700 debug_assert!(idx <= node.len());
710 -> Result<Handle<NodeRef<BorrowType, K, V, NodeType>, marker::KV>, Self> {
713 Ok(Handle::new_kv(self.node, self.idx - 1))
719 pub fn right_kv(self)
720 -> Result<Handle<NodeRef<BorrowType, K, V, NodeType>, marker::KV>, Self> {
722 if self.idx < self.node.len() {
723 Ok(Handle::new_kv(self.node, self.idx))
730 impl<'a, K, V> Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge> {
731 fn insert_fit(&mut self, key: K, val: V) -> *mut V {
732 // Necessary for correctness, but in a private module
733 debug_assert!(self.node.len() < CAPACITY);
736 slice_insert(self.node.keys_mut(), self.idx, key);
737 slice_insert(self.node.vals_mut(), self.idx, val);
739 self.node.as_leaf_mut().len += 1;
741 self.node.vals_mut().get_unchecked_mut(self.idx)
745 pub fn insert(mut self, key: K, val: V)
746 -> (InsertResult<'a, K, V, marker::Leaf>, *mut V) {
748 if self.node.len() < CAPACITY {
749 let ptr = self.insert_fit(key, val);
750 (InsertResult::Fit(Handle::new_kv(self.node, self.idx)), ptr)
752 let middle = Handle::new_kv(self.node, B);
753 let (mut left, k, v, mut right) = middle.split();
754 let ptr = if self.idx <= B {
756 Handle::new_edge(left.reborrow_mut(), self.idx).insert_fit(key, val)
761 right.as_mut().cast_unchecked::<marker::Leaf>(),
763 ).insert_fit(key, val)
766 (InsertResult::Split(left, k, v, right), ptr)
771 impl<'a, K, V> Handle<NodeRef<marker::Mut<'a>, K, V, marker::Internal>, marker::Edge> {
772 fn correct_parent_link(mut self) {
773 let idx = self.idx as u16;
774 let ptr = self.node.as_internal_mut() as *mut _;
775 let mut child = self.descend();
776 child.as_leaf_mut().parent = ptr;
777 child.as_leaf_mut().parent_idx = idx;
780 unsafe fn cast_unchecked<NewType>(&mut self)
781 -> Handle<NodeRef<marker::Mut, K, V, NewType>, marker::Edge> {
783 Handle::new_edge(self.node.cast_unchecked(), self.idx)
786 fn insert_fit(&mut self, key: K, val: V, edge: Root<K, V>) {
787 // Necessary for correctness, but in an internal module
788 debug_assert!(self.node.len() < CAPACITY);
789 debug_assert!(edge.height == self.node.height - 1);
792 self.cast_unchecked::<marker::Leaf>().insert_fit(key, val);
795 slice::from_raw_parts_mut(
796 self.node.as_internal_mut().edges.as_mut_ptr(),
803 for i in (self.idx+1)..(self.node.len()+1) {
804 Handle::new_edge(self.node.reborrow_mut(), i).correct_parent_link();
809 pub fn insert(mut self, key: K, val: V, edge: Root<K, V>)
810 -> InsertResult<'a, K, V, marker::Internal> {
812 // Necessary for correctness, but this is an internal module
813 debug_assert!(edge.height == self.node.height - 1);
815 if self.node.len() < CAPACITY {
816 self.insert_fit(key, val, edge);
817 InsertResult::Fit(Handle::new_kv(self.node, self.idx))
819 let middle = Handle::new_kv(self.node, B);
820 let (mut left, k, v, mut right) = middle.split();
823 Handle::new_edge(left.reborrow_mut(), self.idx).insert_fit(key, val, edge);
828 right.as_mut().cast_unchecked::<marker::Internal>(),
830 ).insert_fit(key, val, edge);
833 InsertResult::Split(left, k, v, right)
838 impl<BorrowType, K, V>
839 Handle<NodeRef<BorrowType, K, V, marker::Internal>, marker::Edge> {
841 pub fn descend(self) -> NodeRef<BorrowType, K, V, marker::LeafOrInternal> {
843 height: self.node.height - 1,
844 node: unsafe { self.node.as_internal().edges.get_unchecked(self.idx).as_ptr() },
845 root: self.node.root,
851 impl<'a, K: 'a, V: 'a, NodeType>
852 Handle<NodeRef<marker::Immut<'a>, K, V, NodeType>, marker::KV> {
854 pub fn into_kv(self) -> (&'a K, &'a V) {
855 let (keys, vals) = self.node.into_slices();
857 (keys.get_unchecked(self.idx), vals.get_unchecked(self.idx))
862 impl<'a, K: 'a, V: 'a, NodeType>
863 Handle<NodeRef<marker::Mut<'a>, K, V, NodeType>, marker::KV> {
865 pub fn into_kv_mut(self) -> (&'a mut K, &'a mut V) {
866 let (mut keys, mut vals) = self.node.into_slices_mut();
868 (keys.get_unchecked_mut(self.idx), vals.get_unchecked_mut(self.idx))
873 impl<'a, K, V, NodeType> Handle<NodeRef<marker::Mut<'a>, K, V, NodeType>, marker::KV> {
874 pub fn kv_mut(&mut self) -> (&mut K, &mut V) {
876 let (mut keys, mut vals) = self.node.reborrow_mut().into_slices_mut();
877 (keys.get_unchecked_mut(self.idx), vals.get_unchecked_mut(self.idx))
882 impl<'a, K, V> Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::KV> {
883 pub fn split(mut self)
884 -> (NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, K, V, Root<K, V>) {
886 let mut new_node = Box::new(LeafNode::new());
888 let k = ptr::read(self.node.keys().get_unchecked(self.idx));
889 let v = ptr::read(self.node.vals().get_unchecked(self.idx));
891 let new_len = self.node.len() - self.idx - 1;
893 ptr::copy_nonoverlapping(
894 self.node.keys().as_ptr().offset(self.idx as isize + 1),
895 new_node.keys.as_mut_ptr(),
898 ptr::copy_nonoverlapping(
899 self.node.vals().as_ptr().offset(self.idx as isize + 1),
900 new_node.vals.as_mut_ptr(),
904 self.node.as_leaf_mut().len = self.idx as u16;
905 new_node.len = new_len as u16;
911 node: BoxedNode::from_leaf(new_node),
918 pub fn remove(mut self)
919 -> (Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge>, K, V) {
921 let k = slice_remove(self.node.keys_mut(), self.idx);
922 let v = slice_remove(self.node.vals_mut(), self.idx);
923 self.node.as_leaf_mut().len -= 1;
924 (self.left_edge(), k, v)
929 impl<'a, K, V> Handle<NodeRef<marker::Mut<'a>, K, V, marker::Internal>, marker::KV> {
930 pub fn split(mut self)
931 -> (NodeRef<marker::Mut<'a>, K, V, marker::Internal>, K, V, Root<K, V>) {
933 let mut new_node = Box::new(InternalNode::new());
935 let k = ptr::read(self.node.keys().get_unchecked(self.idx));
936 let v = ptr::read(self.node.vals().get_unchecked(self.idx));
938 let height = self.node.height;
939 let new_len = self.node.len() - self.idx - 1;
941 ptr::copy_nonoverlapping(
942 self.node.keys().as_ptr().offset(self.idx as isize + 1),
943 new_node.data.keys.as_mut_ptr(),
946 ptr::copy_nonoverlapping(
947 self.node.vals().as_ptr().offset(self.idx as isize + 1),
948 new_node.data.vals.as_mut_ptr(),
951 ptr::copy_nonoverlapping(
952 self.node.as_internal().edges.as_ptr().offset(self.idx as isize + 1),
953 new_node.edges.as_mut_ptr(),
957 self.node.as_leaf_mut().len = self.idx as u16;
958 new_node.data.len = new_len as u16;
960 let mut new_root = Root {
961 node: BoxedNode::from_internal(new_node),
965 for i in 0..(new_len+1) {
966 Handle::new_edge(new_root.as_mut().cast_unchecked(), i).correct_parent_link();
977 pub fn can_merge(&self) -> bool {
991 pub fn merge(mut self)
992 -> Handle<NodeRef<marker::Mut<'a>, K, V, marker::Internal>, marker::Edge> {
993 let self1 = unsafe { ptr::read(&self) };
994 let self2 = unsafe { ptr::read(&self) };
995 let mut left_node = self1.left_edge().descend();
996 let left_len = left_node.len();
997 let mut right_node = self2.right_edge().descend();
998 let right_len = right_node.len();
1000 // necessary for correctness, but in a private module
1001 debug_assert!(left_len + right_len + 1 <= CAPACITY);
1004 ptr::write(left_node.keys_mut().get_unchecked_mut(left_len),
1005 slice_remove(self.node.keys_mut(), self.idx));
1006 ptr::copy_nonoverlapping(
1007 right_node.keys().as_ptr(),
1008 left_node.keys_mut().as_mut_ptr().offset(left_len as isize + 1),
1011 ptr::write(left_node.vals_mut().get_unchecked_mut(left_len),
1012 slice_remove(self.node.vals_mut(), self.idx));
1013 ptr::copy_nonoverlapping(
1014 right_node.vals().as_ptr(),
1015 left_node.vals_mut().as_mut_ptr().offset(left_len as isize + 1),
1019 slice_remove(&mut self.node.as_internal_mut().edges, self.idx + 1);
1020 for i in self.idx+1..self.node.len() {
1021 Handle::new_edge(self.node.reborrow_mut(), i).correct_parent_link();
1023 self.node.as_leaf_mut().len -= 1;
1025 if self.node.height > 1 {
1026 ptr::copy_nonoverlapping(
1027 right_node.cast_unchecked().as_internal().edges.as_ptr(),
1028 left_node.cast_unchecked()
1032 .offset(left_len as isize + 1),
1036 for i in left_len+1..left_len+right_len+2 {
1038 left_node.cast_unchecked().reborrow_mut(),
1040 ).correct_parent_link();
1044 *right_node.node as *mut u8,
1045 mem::size_of::<InternalNode<K, V>>(),
1046 mem::align_of::<InternalNode<K, V>>()
1050 *right_node.node as *mut u8,
1051 mem::size_of::<LeafNode<K, V>>(),
1052 mem::align_of::<LeafNode<K, V>>()
1056 left_node.as_leaf_mut().len += right_len as u16 + 1;
1058 Handle::new_edge(self.node, self.idx)
1063 impl<BorrowType, K, V, HandleType>
1064 Handle<NodeRef<BorrowType, K, V, marker::LeafOrInternal>, HandleType> {
1066 pub fn force(self) -> ForceResult<
1067 Handle<NodeRef<BorrowType, K, V, marker::Leaf>, HandleType>,
1068 Handle<NodeRef<BorrowType, K, V, marker::Internal>, HandleType>
1070 match self.node.force() {
1071 ForceResult::Leaf(node) => ForceResult::Leaf(Handle {
1074 _marker: PhantomData
1076 ForceResult::Internal(node) => ForceResult::Internal(Handle {
1079 _marker: PhantomData
1085 pub enum ForceResult<Leaf, Internal> {
1090 pub enum InsertResult<'a, K, V, Type> {
1091 Fit(Handle<NodeRef<marker::Mut<'a>, K, V, Type>, marker::KV>),
1092 Split(NodeRef<marker::Mut<'a>, K, V, Type>, K, V, Root<K, V>)
1096 use core::marker::PhantomData;
1099 pub enum Internal { }
1100 pub enum LeafOrInternal { }
1103 pub struct Immut<'a>(PhantomData<&'a ()>);
1104 pub struct Mut<'a>(PhantomData<&'a mut ()>);
1110 unsafe fn slice_insert<T>(slice: &mut [T], idx: usize, val: T) {
1112 slice.as_ptr().offset(idx as isize),
1113 slice.as_mut_ptr().offset(idx as isize + 1),
1116 ptr::write(slice.get_unchecked_mut(idx), val);
1119 unsafe fn slice_remove<T>(slice: &mut [T], idx: usize) -> T {
1120 let ret = ptr::read(slice.get_unchecked(idx));
1122 slice.as_ptr().offset(idx as isize + 1),
1123 slice.as_mut_ptr().offset(idx as isize),
1124 slice.len() - idx - 1