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 actually have dependent types and polymorphic recursion,
32 // we make do with lots of unsafety.
34 // A major goal of this module is to avoid complexity by treating the tree as a generic (if
35 // weirdly shaped) container and avoiding dealing with most of the B-Tree invariants. As such,
36 // this module doesn't care whether the entries are sorted, which nodes can be underfull, or
37 // even what underfull means. However, we do rely on a few invariants:
39 // - Trees must have uniform depth/height. This means that every path down to a leaf from a
40 // given node has exactly the same length.
41 // - A node of length `n` has `n` keys, `n` values, and (in an internal node) `n + 1` edges.
42 // This implies that even an empty internal node has at least one edge.
44 use core::marker::PhantomData;
46 use core::nonzero::NonZero;
47 use core::ptr::{self, Unique};
51 use heap::{Heap, Alloc, Layout};
54 pub const MIN_LEN: usize = B - 1;
55 pub const CAPACITY: usize = 2 * B - 1;
57 /// The underlying representation of leaf nodes. Note that it is often unsafe to actually store
58 /// these, since only the first `len` keys and values are assumed to be initialized. As such,
59 /// these should always be put behind pointers, and specifically behind `BoxedNode` in the owned
62 /// See also rust-lang/rfcs#197, which would make this structure significantly more safe by
63 /// avoiding accidentally dropping unused and uninitialized keys and values.
64 struct LeafNode<K, V> {
65 /// The arrays storing the actual data of the node. Only the first `len` elements of each
66 /// array are initialized and valid.
70 /// We use `*const` as opposed to `*mut` so as to be covariant in `K` and `V`.
71 /// This either points to an actual node or is null.
72 parent: *const InternalNode<K, V>,
74 /// This node's index into the parent node's `edges` array.
75 /// `*node.parent.edges[node.parent_idx]` should be the same thing as `node`.
76 /// This is only guaranteed to be initialized when `parent` is nonnull.
79 /// The number of keys and values this node stores.
81 /// This is at the end of the node's representation and next to `parent_idx` to encourage
82 /// the compiler to join `len` and `parent_idx` into the same 32-bit word, reducing space
87 impl<K, V> LeafNode<K, V> {
88 /// Creates a new `LeafNode`. Unsafe because all nodes should really be hidden behind
89 /// `BoxedNode`, preventing accidental dropping of uninitialized keys and values.
90 unsafe fn new() -> Self {
92 // As a general policy, we leave fields uninitialized if they can be, as this should
93 // be both slightly faster and easier to track in Valgrind.
94 keys: mem::uninitialized(),
95 vals: mem::uninitialized(),
97 parent_idx: mem::uninitialized(),
103 /// The underlying representation of internal nodes. As with `LeafNode`s, these should be hidden
104 /// behind `BoxedNode`s to prevent dropping uninitialized keys and values. Any pointer to an
105 /// `InternalNode` can be directly casted to a pointer to the underlying `LeafNode` portion of the
106 /// node, allowing code to act on leaf and internal nodes generically without having to even check
107 /// which of the two a pointer is pointing at. This property is enabled by the use of `repr(C)`.
109 struct InternalNode<K, V> {
110 data: LeafNode<K, V>,
112 /// The pointers to the children of this node. `len + 1` of these are considered
113 /// initialized and valid.
114 edges: [BoxedNode<K, V>; 2 * B],
117 impl<K, V> InternalNode<K, V> {
118 /// Creates a new `InternalNode`.
120 /// This is unsafe for two reasons. First, it returns an `InternalNode` by value, risking
121 /// dropping of uninitialized fields. Second, an invariant of internal nodes is that `len + 1`
122 /// edges are initialized and valid, meaning that even when the node is empty (having a
123 /// `len` of 0), there must be one initialized and valid edge. This function does not set up
125 unsafe fn new() -> Self {
127 data: LeafNode::new(),
128 edges: mem::uninitialized()
133 /// An owned pointer to a node. This basically is either `Box<LeafNode<K, V>>` or
134 /// `Box<InternalNode<K, V>>`. However, it contains no information as to which of the two types
135 /// of nodes is actually behind the box, and, partially due to this lack of information, has no
137 struct BoxedNode<K, V> {
138 ptr: Unique<LeafNode<K, V>>
141 impl<K, V> BoxedNode<K, V> {
142 fn from_leaf(node: Box<LeafNode<K, V>>) -> Self {
143 BoxedNode { ptr: Box::into_unique(node) }
146 fn from_internal(node: Box<InternalNode<K, V>>) -> Self {
148 BoxedNode { ptr: Unique::new_unchecked(Box::into_raw(node) as *mut LeafNode<K, V>) }
152 unsafe fn from_ptr(ptr: NonZero<*const LeafNode<K, V>>) -> Self {
153 BoxedNode { ptr: Unique::new_unchecked(ptr.get() as *mut LeafNode<K, V>) }
156 fn as_ptr(&self) -> NonZero<*const LeafNode<K, V>> {
158 NonZero::from(self.ptr.as_ref())
163 /// An owned tree. Note that despite being owned, this does not have a destructor,
164 /// and must be cleaned up manually.
165 pub struct Root<K, V> {
166 node: BoxedNode<K, V>,
170 unsafe impl<K: Sync, V: Sync> Sync for Root<K, V> { }
171 unsafe impl<K: Send, V: Send> Send for Root<K, V> { }
173 impl<K, V> Root<K, V> {
174 pub fn new_leaf() -> Self {
176 node: BoxedNode::from_leaf(Box::new(unsafe { LeafNode::new() })),
182 -> NodeRef<marker::Immut, K, V, marker::LeafOrInternal> {
185 node: self.node.as_ptr(),
186 root: self as *const _ as *mut _,
187 _marker: PhantomData,
191 pub fn as_mut(&mut self)
192 -> NodeRef<marker::Mut, K, V, marker::LeafOrInternal> {
195 node: self.node.as_ptr(),
196 root: self as *mut _,
197 _marker: PhantomData,
201 pub fn into_ref(self)
202 -> NodeRef<marker::Owned, K, V, marker::LeafOrInternal> {
205 node: self.node.as_ptr(),
206 root: ptr::null_mut(), // FIXME: Is there anything better to do here?
207 _marker: PhantomData,
211 /// Adds a new internal node with a single edge, pointing to the previous root, and make that
212 /// new node the root. This increases the height by 1 and is the opposite of `pop_level`.
213 pub fn push_level(&mut self)
214 -> NodeRef<marker::Mut, K, V, marker::Internal> {
215 let mut new_node = Box::new(unsafe { InternalNode::new() });
216 new_node.edges[0] = unsafe { BoxedNode::from_ptr(self.node.as_ptr()) };
218 self.node = BoxedNode::from_internal(new_node);
221 let mut ret = NodeRef {
223 node: self.node.as_ptr(),
224 root: self as *mut _,
229 ret.reborrow_mut().first_edge().correct_parent_link();
235 /// Removes the root node, using its first child as the new root. This cannot be called when
236 /// the tree consists only of a leaf node. As it is intended only to be called when the root
237 /// has only one edge, no cleanup is done on any of the other children are elements of the root.
238 /// This decreases the height by 1 and is the opposite of `push_level`.
239 pub fn pop_level(&mut self) {
240 debug_assert!(self.height > 0);
242 let top = self.node.ptr.as_ptr() as *mut u8;
245 BoxedNode::from_ptr(self.as_mut()
246 .cast_unchecked::<marker::Internal>()
252 self.as_mut().as_leaf_mut().parent = ptr::null();
255 Heap.dealloc(top, Layout::new::<InternalNode<K, V>>());
260 // N.B. `NodeRef` is always covariant in `K` and `V`, even when the `BorrowType`
261 // is `Mut`. This is technically wrong, but cannot result in any unsafety due to
262 // internal use of `NodeRef` because we stay completely generic over `K` and `V`.
263 // However, whenever a public type wraps `NodeRef`, make sure that it has the
265 /// A reference to a node.
267 /// This type has a number of parameters that controls how it acts:
268 /// - `BorrowType`: This can be `Immut<'a>` or `Mut<'a>` for some `'a` or `Owned`.
269 /// When this is `Immut<'a>`, the `NodeRef` acts roughly like `&'a Node`,
270 /// when this is `Mut<'a>`, the `NodeRef` acts roughly like `&'a mut Node`,
271 /// and when this is `Owned`, the `NodeRef` acts roughly like `Box<Node>`.
272 /// - `K` and `V`: These control what types of things are stored in the nodes.
273 /// - `Type`: This can be `Leaf`, `Internal`, or `LeafOrInternal`. When this is
274 /// `Leaf`, the `NodeRef` points to a leaf node, when this is `Internal` the
275 /// `NodeRef` points to an internal node, and when this is `LeafOrInternal` the
276 /// `NodeRef` could be pointing to either type of node.
277 pub struct NodeRef<BorrowType, K, V, Type> {
279 node: NonZero<*const LeafNode<K, V>>,
280 // This is null unless the borrow type is `Mut`
281 root: *const Root<K, V>,
282 _marker: PhantomData<(BorrowType, Type)>
285 impl<'a, K: 'a, V: 'a, Type> Copy for NodeRef<marker::Immut<'a>, K, V, Type> { }
286 impl<'a, K: 'a, V: 'a, Type> Clone for NodeRef<marker::Immut<'a>, K, V, Type> {
287 fn clone(&self) -> Self {
292 unsafe impl<BorrowType, K: Sync, V: Sync, Type> Sync
293 for NodeRef<BorrowType, K, V, Type> { }
295 unsafe impl<'a, K: Sync + 'a, V: Sync + 'a, Type> Send
296 for NodeRef<marker::Immut<'a>, K, V, Type> { }
297 unsafe impl<'a, K: Send + 'a, V: Send + 'a, Type> Send
298 for NodeRef<marker::Mut<'a>, K, V, Type> { }
299 unsafe impl<K: Send, V: Send, Type> Send
300 for NodeRef<marker::Owned, K, V, Type> { }
302 impl<BorrowType, K, V> NodeRef<BorrowType, K, V, marker::Internal> {
303 fn as_internal(&self) -> &InternalNode<K, V> {
305 &*(self.node.get() as *const InternalNode<K, V>)
310 impl<'a, K, V> NodeRef<marker::Mut<'a>, K, V, marker::Internal> {
311 fn as_internal_mut(&mut self) -> &mut InternalNode<K, V> {
313 &mut *(self.node.get() as *mut InternalNode<K, V>)
319 impl<BorrowType, K, V, Type> NodeRef<BorrowType, K, V, Type> {
320 /// Finds the length of the node. This is the number of keys or values. In an
321 /// internal node, the number of edges is `len() + 1`.
322 pub fn len(&self) -> usize {
323 self.as_leaf().len as usize
326 /// Returns the height of this node in the whole tree. Zero height denotes the
328 pub fn height(&self) -> usize {
332 /// Removes any static information about whether this node is a `Leaf` or an
334 pub fn forget_type(self) -> NodeRef<BorrowType, K, V, marker::LeafOrInternal> {
343 /// Temporarily takes out another, immutable reference to the same node.
344 fn reborrow<'a>(&'a self) -> NodeRef<marker::Immut<'a>, K, V, Type> {
353 fn as_leaf(&self) -> &LeafNode<K, V> {
359 pub fn keys(&self) -> &[K] {
360 self.reborrow().into_slices().0
363 pub fn vals(&self) -> &[V] {
364 self.reborrow().into_slices().1
367 /// Finds the parent of the current node. Returns `Ok(handle)` if the current
368 /// node actually has a parent, where `handle` points to the edge of the parent
369 /// that points to the current node. Returns `Err(self)` if the current node has
370 /// no parent, giving back the original `NodeRef`.
372 /// `edge.descend().ascend().unwrap()` and `node.ascend().unwrap().descend()` should
373 /// both, upon success, do nothing.
374 pub fn ascend(self) -> Result<
385 if let Some(non_zero) = NonZero::new(self.as_leaf().parent as *const LeafNode<K, V>) {
388 height: self.height + 1,
393 idx: self.as_leaf().parent_idx as usize,
401 pub fn first_edge(self) -> Handle<Self, marker::Edge> {
402 Handle::new_edge(self, 0)
405 pub fn last_edge(self) -> Handle<Self, marker::Edge> {
406 let len = self.len();
407 Handle::new_edge(self, len)
410 /// Note that `self` must be nonempty.
411 pub fn first_kv(self) -> Handle<Self, marker::KV> {
412 debug_assert!(self.len() > 0);
413 Handle::new_kv(self, 0)
416 /// Note that `self` must be nonempty.
417 pub fn last_kv(self) -> Handle<Self, marker::KV> {
418 let len = self.len();
419 debug_assert!(len > 0);
420 Handle::new_kv(self, len - 1)
424 impl<K, V> NodeRef<marker::Owned, K, V, marker::Leaf> {
425 /// Similar to `ascend`, gets a reference to a node's parent node, but also
426 /// deallocate the current node in the process. This is unsafe because the
427 /// current node will still be accessible despite being deallocated.
428 pub unsafe fn deallocate_and_ascend(self) -> Option<
438 let ptr = self.as_leaf() as *const LeafNode<K, V> as *const u8 as *mut u8;
439 let ret = self.ascend().ok();
440 Heap.dealloc(ptr, Layout::new::<LeafNode<K, V>>());
445 impl<K, V> NodeRef<marker::Owned, K, V, marker::Internal> {
446 /// Similar to `ascend`, gets a reference to a node's parent node, but also
447 /// deallocate the current node in the process. This is unsafe because the
448 /// current node will still be accessible despite being deallocated.
449 pub unsafe fn deallocate_and_ascend(self) -> Option<
459 let ptr = self.as_internal() as *const InternalNode<K, V> as *const u8 as *mut u8;
460 let ret = self.ascend().ok();
461 Heap.dealloc(ptr, Layout::new::<InternalNode<K, V>>());
466 impl<'a, K, V, Type> NodeRef<marker::Mut<'a>, K, V, Type> {
467 /// Unsafely asserts to the compiler some static information about whether this
468 /// node is a `Leaf`.
469 unsafe fn cast_unchecked<NewType>(&mut self)
470 -> NodeRef<marker::Mut, K, V, NewType> {
480 /// Temporarily takes out another, mutable reference to the same node. Beware, as
481 /// this method is very dangerous, doubly so since it may not immediately appear
484 /// Because mutable pointers can roam anywhere around the tree and can even (through
485 /// `into_root_mut`) mess with the root of the tree, the result of `reborrow_mut`
486 /// can easily be used to make the original mutable pointer dangling, or, in the case
487 /// of a reborrowed handle, out of bounds.
488 // FIXME(@gereeter) consider adding yet another type parameter to `NodeRef` that restricts
489 // the use of `ascend` and `into_root_mut` on reborrowed pointers, preventing this unsafety.
490 unsafe fn reborrow_mut(&mut self) -> NodeRef<marker::Mut, K, V, Type> {
499 fn as_leaf_mut(&mut self) -> &mut LeafNode<K, V> {
501 &mut *(self.node.get() as *mut LeafNode<K, V>)
505 pub fn keys_mut(&mut self) -> &mut [K] {
506 unsafe { self.reborrow_mut().into_slices_mut().0 }
509 pub fn vals_mut(&mut self) -> &mut [V] {
510 unsafe { self.reborrow_mut().into_slices_mut().1 }
514 impl<'a, K: 'a, V: 'a, Type> NodeRef<marker::Immut<'a>, K, V, Type> {
515 pub fn into_slices(self) -> (&'a [K], &'a [V]) {
518 slice::from_raw_parts(
519 self.as_leaf().keys.as_ptr(),
522 slice::from_raw_parts(
523 self.as_leaf().vals.as_ptr(),
531 impl<'a, K: 'a, V: 'a, Type> NodeRef<marker::Mut<'a>, K, V, Type> {
532 /// Gets a mutable reference to the root itself. This is useful primarily when the
533 /// height of the tree needs to be adjusted. Never call this on a reborrowed pointer.
534 pub fn into_root_mut(self) -> &'a mut Root<K, V> {
536 &mut *(self.root as *mut Root<K, V>)
540 pub fn into_slices_mut(mut self) -> (&'a mut [K], &'a mut [V]) {
543 slice::from_raw_parts_mut(
544 &mut self.as_leaf_mut().keys as *mut [K] as *mut K,
547 slice::from_raw_parts_mut(
548 &mut self.as_leaf_mut().vals as *mut [V] as *mut V,
556 impl<'a, K, V> NodeRef<marker::Mut<'a>, K, V, marker::Leaf> {
557 /// Adds a key/value pair the end of the node.
558 pub fn push(&mut self, key: K, val: V) {
559 // Necessary for correctness, but this is an internal module
560 debug_assert!(self.len() < CAPACITY);
562 let idx = self.len();
565 ptr::write(self.keys_mut().get_unchecked_mut(idx), key);
566 ptr::write(self.vals_mut().get_unchecked_mut(idx), val);
569 self.as_leaf_mut().len += 1;
572 /// Adds a key/value pair to the beginning of the node.
573 pub fn push_front(&mut self, key: K, val: V) {
574 // Necessary for correctness, but this is an internal module
575 debug_assert!(self.len() < CAPACITY);
578 slice_insert(self.keys_mut(), 0, key);
579 slice_insert(self.vals_mut(), 0, val);
582 self.as_leaf_mut().len += 1;
586 impl<'a, K, V> NodeRef<marker::Mut<'a>, K, V, marker::Internal> {
587 /// Adds a key/value pair and an edge to go to the right of that pair to
588 /// the end of the node.
589 pub fn push(&mut self, key: K, val: V, edge: Root<K, V>) {
590 // Necessary for correctness, but this is an internal module
591 debug_assert!(edge.height == self.height - 1);
592 debug_assert!(self.len() < CAPACITY);
594 let idx = self.len();
597 ptr::write(self.keys_mut().get_unchecked_mut(idx), key);
598 ptr::write(self.vals_mut().get_unchecked_mut(idx), val);
599 ptr::write(self.as_internal_mut().edges.get_unchecked_mut(idx + 1), edge.node);
601 self.as_leaf_mut().len += 1;
603 Handle::new_edge(self.reborrow_mut(), idx + 1).correct_parent_link();
607 fn correct_childrens_parent_links(&mut self, first: usize, after_last: usize) {
608 for i in first..after_last {
609 Handle::new_edge(unsafe { self.reborrow_mut() }, i).correct_parent_link();
613 fn correct_all_childrens_parent_links(&mut self) {
614 let len = self.len();
615 self.correct_childrens_parent_links(0, len + 1);
618 /// Adds a key/value pair and an edge to go to the left of that pair to
619 /// the beginning of the node.
620 pub fn push_front(&mut self, key: K, val: V, edge: Root<K, V>) {
621 // Necessary for correctness, but this is an internal module
622 debug_assert!(edge.height == self.height - 1);
623 debug_assert!(self.len() < CAPACITY);
626 slice_insert(self.keys_mut(), 0, key);
627 slice_insert(self.vals_mut(), 0, val);
629 slice::from_raw_parts_mut(
630 self.as_internal_mut().edges.as_mut_ptr(),
637 self.as_leaf_mut().len += 1;
639 self.correct_all_childrens_parent_links();
644 impl<'a, K, V> NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal> {
645 /// Removes a key/value pair from the end of this node. If this is an internal node,
646 /// also removes the edge that was to the right of that pair.
647 pub fn pop(&mut self) -> (K, V, Option<Root<K, V>>) {
648 // Necessary for correctness, but this is an internal module
649 debug_assert!(self.len() > 0);
651 let idx = self.len() - 1;
654 let key = ptr::read(self.keys().get_unchecked(idx));
655 let val = ptr::read(self.vals().get_unchecked(idx));
656 let edge = match self.reborrow_mut().force() {
657 ForceResult::Leaf(_) => None,
658 ForceResult::Internal(internal) => {
659 let edge = ptr::read(internal.as_internal().edges.get_unchecked(idx + 1));
660 let mut new_root = Root { node: edge, height: internal.height - 1 };
661 new_root.as_mut().as_leaf_mut().parent = ptr::null();
666 self.as_leaf_mut().len -= 1;
671 /// Removes a key/value pair from the beginning of this node. If this is an internal node,
672 /// also removes the edge that was to the left of that pair.
673 pub fn pop_front(&mut self) -> (K, V, Option<Root<K, V>>) {
674 // Necessary for correctness, but this is an internal module
675 debug_assert!(self.len() > 0);
677 let old_len = self.len();
680 let key = slice_remove(self.keys_mut(), 0);
681 let val = slice_remove(self.vals_mut(), 0);
682 let edge = match self.reborrow_mut().force() {
683 ForceResult::Leaf(_) => None,
684 ForceResult::Internal(mut internal) => {
685 let edge = slice_remove(
686 slice::from_raw_parts_mut(
687 internal.as_internal_mut().edges.as_mut_ptr(),
693 let mut new_root = Root { node: edge, height: internal.height - 1 };
694 new_root.as_mut().as_leaf_mut().parent = ptr::null();
696 for i in 0..old_len {
697 Handle::new_edge(internal.reborrow_mut(), i).correct_parent_link();
704 self.as_leaf_mut().len -= 1;
710 fn into_kv_pointers_mut(mut self) -> (*mut K, *mut V) {
712 self.keys_mut().as_mut_ptr(),
713 self.vals_mut().as_mut_ptr()
718 impl<BorrowType, K, V> NodeRef<BorrowType, K, V, marker::LeafOrInternal> {
719 /// Checks whether a node is an `Internal` node or a `Leaf` node.
720 pub fn force(self) -> ForceResult<
721 NodeRef<BorrowType, K, V, marker::Leaf>,
722 NodeRef<BorrowType, K, V, marker::Internal>
724 if self.height == 0 {
725 ForceResult::Leaf(NodeRef {
732 ForceResult::Internal(NodeRef {
742 /// A reference to a specific key/value pair or edge within a node. The `Node` parameter
743 /// must be a `NodeRef`, while the `Type` can either be `KV` (signifying a handle on a key/value
744 /// pair) or `Edge` (signifying a handle on an edge).
746 /// Note that even `Leaf` nodes can have `Edge` handles. Instead of representing a pointer to
747 /// a child node, these represent the spaces where child pointers would go between the key/value
748 /// pairs. For example, in a node with length 2, there would be 3 possible edge locations - one
749 /// to the left of the node, one between the two pairs, and one at the right of the node.
750 pub struct Handle<Node, Type> {
753 _marker: PhantomData<Type>
756 impl<Node: Copy, Type> Copy for Handle<Node, Type> { }
757 // We don't need the full generality of `#[derive(Clone)]`, as the only time `Node` will be
758 // `Clone`able is when it is an immutable reference and therefore `Copy`.
759 impl<Node: Copy, Type> Clone for Handle<Node, Type> {
760 fn clone(&self) -> Self {
765 impl<Node, Type> Handle<Node, Type> {
766 /// Retrieves the node that contains the edge of key/value pair this handle points to.
767 pub fn into_node(self) -> Node {
772 impl<BorrowType, K, V, NodeType> Handle<NodeRef<BorrowType, K, V, NodeType>, marker::KV> {
773 /// Creates a new handle to a key/value pair in `node`. `idx` must be less than `node.len()`.
774 pub fn new_kv(node: NodeRef<BorrowType, K, V, NodeType>, idx: usize) -> Self {
775 // Necessary for correctness, but in a private module
776 debug_assert!(idx < node.len());
785 pub fn left_edge(self) -> Handle<NodeRef<BorrowType, K, V, NodeType>, marker::Edge> {
786 Handle::new_edge(self.node, self.idx)
789 pub fn right_edge(self) -> Handle<NodeRef<BorrowType, K, V, NodeType>, marker::Edge> {
790 Handle::new_edge(self.node, self.idx + 1)
794 impl<BorrowType, K, V, NodeType, HandleType> PartialEq
795 for Handle<NodeRef<BorrowType, K, V, NodeType>, HandleType> {
797 fn eq(&self, other: &Self) -> bool {
798 self.node.node == other.node.node && self.idx == other.idx
802 impl<BorrowType, K, V, NodeType, HandleType>
803 Handle<NodeRef<BorrowType, K, V, NodeType>, HandleType> {
805 /// Temporarily takes out another, immutable handle on the same location.
806 pub fn reborrow(&self)
807 -> Handle<NodeRef<marker::Immut, K, V, NodeType>, HandleType> {
809 // We can't use Handle::new_kv or Handle::new_edge because we don't know our type
811 node: self.node.reborrow(),
818 impl<'a, K, V, NodeType, HandleType>
819 Handle<NodeRef<marker::Mut<'a>, K, V, NodeType>, HandleType> {
821 /// Temporarily takes out another, mutable handle on the same location. Beware, as
822 /// this method is very dangerous, doubly so since it may not immediately appear
825 /// Because mutable pointers can roam anywhere around the tree and can even (through
826 /// `into_root_mut`) mess with the root of the tree, the result of `reborrow_mut`
827 /// can easily be used to make the original mutable pointer dangling, or, in the case
828 /// of a reborrowed handle, out of bounds.
829 // FIXME(@gereeter) consider adding yet another type parameter to `NodeRef` that restricts
830 // the use of `ascend` and `into_root_mut` on reborrowed pointers, preventing this unsafety.
831 pub unsafe fn reborrow_mut(&mut self)
832 -> Handle<NodeRef<marker::Mut, K, V, NodeType>, HandleType> {
834 // We can't use Handle::new_kv or Handle::new_edge because we don't know our type
836 node: self.node.reborrow_mut(),
843 impl<BorrowType, K, V, NodeType>
844 Handle<NodeRef<BorrowType, K, V, NodeType>, marker::Edge> {
846 /// Creates a new handle to an edge in `node`. `idx` must be less than or equal to
848 pub fn new_edge(node: NodeRef<BorrowType, K, V, NodeType>, idx: usize) -> Self {
849 // Necessary for correctness, but in a private module
850 debug_assert!(idx <= node.len());
860 -> Result<Handle<NodeRef<BorrowType, K, V, NodeType>, marker::KV>, Self> {
863 Ok(Handle::new_kv(self.node, self.idx - 1))
869 pub fn right_kv(self)
870 -> Result<Handle<NodeRef<BorrowType, K, V, NodeType>, marker::KV>, Self> {
872 if self.idx < self.node.len() {
873 Ok(Handle::new_kv(self.node, self.idx))
880 impl<'a, K, V> Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge> {
881 /// Inserts a new key/value pair between the key/value pairs to the right and left of
882 /// this edge. This method assumes that there is enough space in the node for the new
885 /// The returned pointer points to the inserted value.
886 fn insert_fit(&mut self, key: K, val: V) -> *mut V {
887 // Necessary for correctness, but in a private module
888 debug_assert!(self.node.len() < CAPACITY);
891 slice_insert(self.node.keys_mut(), self.idx, key);
892 slice_insert(self.node.vals_mut(), self.idx, val);
894 self.node.as_leaf_mut().len += 1;
896 self.node.vals_mut().get_unchecked_mut(self.idx)
900 /// Inserts a new key/value pair between the key/value pairs to the right and left of
901 /// this edge. This method splits the node if there isn't enough room.
903 /// The returned pointer points to the inserted value.
904 pub fn insert(mut self, key: K, val: V)
905 -> (InsertResult<'a, K, V, marker::Leaf>, *mut V) {
907 if self.node.len() < CAPACITY {
908 let ptr = self.insert_fit(key, val);
909 (InsertResult::Fit(Handle::new_kv(self.node, self.idx)), ptr)
911 let middle = Handle::new_kv(self.node, B);
912 let (mut left, k, v, mut right) = middle.split();
913 let ptr = if self.idx <= B {
915 Handle::new_edge(left.reborrow_mut(), self.idx).insert_fit(key, val)
920 right.as_mut().cast_unchecked::<marker::Leaf>(),
922 ).insert_fit(key, val)
925 (InsertResult::Split(left, k, v, right), ptr)
930 impl<'a, K, V> Handle<NodeRef<marker::Mut<'a>, K, V, marker::Internal>, marker::Edge> {
931 /// Fixes the parent pointer and index in the child node below this edge. This is useful
932 /// when the ordering of edges has been changed, such as in the various `insert` methods.
933 fn correct_parent_link(mut self) {
934 let idx = self.idx as u16;
935 let ptr = self.node.as_internal_mut() as *mut _;
936 let mut child = self.descend();
937 child.as_leaf_mut().parent = ptr;
938 child.as_leaf_mut().parent_idx = idx;
941 /// Unsafely asserts to the compiler some static information about whether the underlying
942 /// node of this handle is a `Leaf`.
943 unsafe fn cast_unchecked<NewType>(&mut self)
944 -> Handle<NodeRef<marker::Mut, K, V, NewType>, marker::Edge> {
946 Handle::new_edge(self.node.cast_unchecked(), self.idx)
949 /// Inserts a new key/value pair and an edge that will go to the right of that new pair
950 /// between this edge and the key/value pair to the right of this edge. This method assumes
951 /// that there is enough space in the node for the new pair to fit.
952 fn insert_fit(&mut self, key: K, val: V, edge: Root<K, V>) {
953 // Necessary for correctness, but in an internal module
954 debug_assert!(self.node.len() < CAPACITY);
955 debug_assert!(edge.height == self.node.height - 1);
958 // This cast is a lie, but it allows us to reuse the key/value insertion logic.
959 self.cast_unchecked::<marker::Leaf>().insert_fit(key, val);
962 slice::from_raw_parts_mut(
963 self.node.as_internal_mut().edges.as_mut_ptr(),
970 for i in (self.idx+1)..(self.node.len()+1) {
971 Handle::new_edge(self.node.reborrow_mut(), i).correct_parent_link();
976 /// Inserts a new key/value pair and an edge that will go to the right of that new pair
977 /// between this edge and the key/value pair to the right of this edge. This method splits
978 /// the node if there isn't enough room.
979 pub fn insert(mut self, key: K, val: V, edge: Root<K, V>)
980 -> InsertResult<'a, K, V, marker::Internal> {
982 // Necessary for correctness, but this is an internal module
983 debug_assert!(edge.height == self.node.height - 1);
985 if self.node.len() < CAPACITY {
986 self.insert_fit(key, val, edge);
987 InsertResult::Fit(Handle::new_kv(self.node, self.idx))
989 let middle = Handle::new_kv(self.node, B);
990 let (mut left, k, v, mut right) = middle.split();
993 Handle::new_edge(left.reborrow_mut(), self.idx).insert_fit(key, val, edge);
998 right.as_mut().cast_unchecked::<marker::Internal>(),
1000 ).insert_fit(key, val, edge);
1003 InsertResult::Split(left, k, v, right)
1008 impl<BorrowType, K, V>
1009 Handle<NodeRef<BorrowType, K, V, marker::Internal>, marker::Edge> {
1011 /// Finds the node pointed to by this edge.
1013 /// `edge.descend().ascend().unwrap()` and `node.ascend().unwrap().descend()` should
1014 /// both, upon success, do nothing.
1015 pub fn descend(self) -> NodeRef<BorrowType, K, V, marker::LeafOrInternal> {
1017 height: self.node.height - 1,
1018 node: unsafe { self.node.as_internal().edges.get_unchecked(self.idx).as_ptr() },
1019 root: self.node.root,
1020 _marker: PhantomData
1025 impl<'a, K: 'a, V: 'a, NodeType>
1026 Handle<NodeRef<marker::Immut<'a>, K, V, NodeType>, marker::KV> {
1028 pub fn into_kv(self) -> (&'a K, &'a V) {
1029 let (keys, vals) = self.node.into_slices();
1031 (keys.get_unchecked(self.idx), vals.get_unchecked(self.idx))
1036 impl<'a, K: 'a, V: 'a, NodeType>
1037 Handle<NodeRef<marker::Mut<'a>, K, V, NodeType>, marker::KV> {
1039 pub fn into_kv_mut(self) -> (&'a mut K, &'a mut V) {
1040 let (keys, vals) = self.node.into_slices_mut();
1042 (keys.get_unchecked_mut(self.idx), vals.get_unchecked_mut(self.idx))
1047 impl<'a, K, V, NodeType> Handle<NodeRef<marker::Mut<'a>, K, V, NodeType>, marker::KV> {
1048 pub fn kv_mut(&mut self) -> (&mut K, &mut V) {
1050 let (keys, vals) = self.node.reborrow_mut().into_slices_mut();
1051 (keys.get_unchecked_mut(self.idx), vals.get_unchecked_mut(self.idx))
1056 impl<'a, K, V> Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::KV> {
1057 /// Splits the underlying node into three parts:
1059 /// - The node is truncated to only contain the key/value pairs to the right of
1061 /// - The key and value pointed to by this handle and extracted.
1062 /// - All the key/value pairs to the right of this handle are put into a newly
1064 pub fn split(mut self)
1065 -> (NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, K, V, Root<K, V>) {
1067 let mut new_node = Box::new(LeafNode::new());
1069 let k = ptr::read(self.node.keys().get_unchecked(self.idx));
1070 let v = ptr::read(self.node.vals().get_unchecked(self.idx));
1072 let new_len = self.node.len() - self.idx - 1;
1074 ptr::copy_nonoverlapping(
1075 self.node.keys().as_ptr().offset(self.idx as isize + 1),
1076 new_node.keys.as_mut_ptr(),
1079 ptr::copy_nonoverlapping(
1080 self.node.vals().as_ptr().offset(self.idx as isize + 1),
1081 new_node.vals.as_mut_ptr(),
1085 self.node.as_leaf_mut().len = self.idx as u16;
1086 new_node.len = new_len as u16;
1092 node: BoxedNode::from_leaf(new_node),
1099 /// Removes the key/value pair pointed to by this handle, returning the edge between the
1100 /// now adjacent key/value pairs to the left and right of this handle.
1101 pub fn remove(mut self)
1102 -> (Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge>, K, V) {
1104 let k = slice_remove(self.node.keys_mut(), self.idx);
1105 let v = slice_remove(self.node.vals_mut(), self.idx);
1106 self.node.as_leaf_mut().len -= 1;
1107 (self.left_edge(), k, v)
1112 impl<'a, K, V> Handle<NodeRef<marker::Mut<'a>, K, V, marker::Internal>, marker::KV> {
1113 /// Splits the underlying node into three parts:
1115 /// - The node is truncated to only contain the edges and key/value pairs to the
1116 /// right of this handle.
1117 /// - The key and value pointed to by this handle and extracted.
1118 /// - All the edges and key/value pairs to the right of this handle are put into
1119 /// a newly allocated node.
1120 pub fn split(mut self)
1121 -> (NodeRef<marker::Mut<'a>, K, V, marker::Internal>, K, V, Root<K, V>) {
1123 let mut new_node = Box::new(InternalNode::new());
1125 let k = ptr::read(self.node.keys().get_unchecked(self.idx));
1126 let v = ptr::read(self.node.vals().get_unchecked(self.idx));
1128 let height = self.node.height;
1129 let new_len = self.node.len() - self.idx - 1;
1131 ptr::copy_nonoverlapping(
1132 self.node.keys().as_ptr().offset(self.idx as isize + 1),
1133 new_node.data.keys.as_mut_ptr(),
1136 ptr::copy_nonoverlapping(
1137 self.node.vals().as_ptr().offset(self.idx as isize + 1),
1138 new_node.data.vals.as_mut_ptr(),
1141 ptr::copy_nonoverlapping(
1142 self.node.as_internal().edges.as_ptr().offset(self.idx as isize + 1),
1143 new_node.edges.as_mut_ptr(),
1147 self.node.as_leaf_mut().len = self.idx as u16;
1148 new_node.data.len = new_len as u16;
1150 let mut new_root = Root {
1151 node: BoxedNode::from_internal(new_node),
1155 for i in 0..(new_len+1) {
1156 Handle::new_edge(new_root.as_mut().cast_unchecked(), i).correct_parent_link();
1167 /// Returns whether it is valid to call `.merge()`, i.e., whether there is enough room in
1168 /// a node to hold the combination of the nodes to the left and right of this handle along
1169 /// with the key/value pair at this handle.
1170 pub fn can_merge(&self) -> bool {
1184 /// Combines the node immediately to the left of this handle, the key/value pair pointed
1185 /// to by this handle, and the node immediately to the right of this handle into one new
1186 /// child of the underlying node, returning an edge referencing that new child.
1188 /// Assumes that this edge `.can_merge()`.
1189 pub fn merge(mut self)
1190 -> Handle<NodeRef<marker::Mut<'a>, K, V, marker::Internal>, marker::Edge> {
1191 let self1 = unsafe { ptr::read(&self) };
1192 let self2 = unsafe { ptr::read(&self) };
1193 let mut left_node = self1.left_edge().descend();
1194 let left_len = left_node.len();
1195 let mut right_node = self2.right_edge().descend();
1196 let right_len = right_node.len();
1198 // necessary for correctness, but in a private module
1199 debug_assert!(left_len + right_len + 1 <= CAPACITY);
1202 ptr::write(left_node.keys_mut().get_unchecked_mut(left_len),
1203 slice_remove(self.node.keys_mut(), self.idx));
1204 ptr::copy_nonoverlapping(
1205 right_node.keys().as_ptr(),
1206 left_node.keys_mut().as_mut_ptr().offset(left_len as isize + 1),
1209 ptr::write(left_node.vals_mut().get_unchecked_mut(left_len),
1210 slice_remove(self.node.vals_mut(), self.idx));
1211 ptr::copy_nonoverlapping(
1212 right_node.vals().as_ptr(),
1213 left_node.vals_mut().as_mut_ptr().offset(left_len as isize + 1),
1217 slice_remove(&mut self.node.as_internal_mut().edges, self.idx + 1);
1218 for i in self.idx+1..self.node.len() {
1219 Handle::new_edge(self.node.reborrow_mut(), i).correct_parent_link();
1221 self.node.as_leaf_mut().len -= 1;
1223 left_node.as_leaf_mut().len += right_len as u16 + 1;
1225 if self.node.height > 1 {
1226 ptr::copy_nonoverlapping(
1227 right_node.cast_unchecked().as_internal().edges.as_ptr(),
1228 left_node.cast_unchecked()
1232 .offset(left_len as isize + 1),
1236 for i in left_len+1..left_len+right_len+2 {
1238 left_node.cast_unchecked().reborrow_mut(),
1240 ).correct_parent_link();
1244 right_node.node.get() as *mut u8,
1245 Layout::new::<InternalNode<K, V>>(),
1249 right_node.node.get() as *mut u8,
1250 Layout::new::<LeafNode<K, V>>(),
1254 Handle::new_edge(self.node, self.idx)
1258 /// This removes a key/value pair from the left child and replaces it with the key/value pair
1259 /// pointed to by this handle while pushing the old key/value pair of this handle into the right
1261 pub fn steal_left(&mut self) {
1263 let (k, v, edge) = self.reborrow_mut().left_edge().descend().pop();
1265 let k = mem::replace(self.reborrow_mut().into_kv_mut().0, k);
1266 let v = mem::replace(self.reborrow_mut().into_kv_mut().1, v);
1268 match self.reborrow_mut().right_edge().descend().force() {
1269 ForceResult::Leaf(mut leaf) => leaf.push_front(k, v),
1270 ForceResult::Internal(mut internal) => internal.push_front(k, v, edge.unwrap())
1275 /// This removes a key/value pair from the right child and replaces it with the key/value pair
1276 /// pointed to by this handle while pushing the old key/value pair of this handle into the left
1278 pub fn steal_right(&mut self) {
1280 let (k, v, edge) = self.reborrow_mut().right_edge().descend().pop_front();
1282 let k = mem::replace(self.reborrow_mut().into_kv_mut().0, k);
1283 let v = mem::replace(self.reborrow_mut().into_kv_mut().1, v);
1285 match self.reborrow_mut().left_edge().descend().force() {
1286 ForceResult::Leaf(mut leaf) => leaf.push(k, v),
1287 ForceResult::Internal(mut internal) => internal.push(k, v, edge.unwrap())
1292 /// This does stealing similar to `steal_left` but steals multiple elements at once.
1293 pub fn bulk_steal_left(&mut self, count: usize) {
1295 let mut left_node = ptr::read(self).left_edge().descend();
1296 let left_len = left_node.len();
1297 let mut right_node = ptr::read(self).right_edge().descend();
1298 let right_len = right_node.len();
1300 // Make sure that we may steal safely.
1301 debug_assert!(right_len + count <= CAPACITY);
1302 debug_assert!(left_len >= count);
1304 let new_left_len = left_len - count;
1308 let left_kv = left_node.reborrow_mut().into_kv_pointers_mut();
1309 let right_kv = right_node.reborrow_mut().into_kv_pointers_mut();
1311 let kv = self.reborrow_mut().into_kv_mut();
1312 (kv.0 as *mut K, kv.1 as *mut V)
1315 // Make room for stolen elements in the right child.
1316 ptr::copy(right_kv.0,
1317 right_kv.0.offset(count as isize),
1319 ptr::copy(right_kv.1,
1320 right_kv.1.offset(count as isize),
1323 // Move elements from the left child to the right one.
1324 move_kv(left_kv, new_left_len + 1, right_kv, 0, count - 1);
1326 // Move parent's key/value pair to the right child.
1327 move_kv(parent_kv, 0, right_kv, count - 1, 1);
1329 // Move the left-most stolen pair to the parent.
1330 move_kv(left_kv, new_left_len, parent_kv, 0, 1);
1333 left_node.reborrow_mut().as_leaf_mut().len -= count as u16;
1334 right_node.reborrow_mut().as_leaf_mut().len += count as u16;
1336 match (left_node.force(), right_node.force()) {
1337 (ForceResult::Internal(left), ForceResult::Internal(mut right)) => {
1338 // Make room for stolen edges.
1339 let right_edges = right.reborrow_mut().as_internal_mut().edges.as_mut_ptr();
1340 ptr::copy(right_edges,
1341 right_edges.offset(count as isize),
1343 right.correct_childrens_parent_links(count, count + right_len + 1);
1345 move_edges(left, new_left_len + 1, right, 0, count);
1347 (ForceResult::Leaf(_), ForceResult::Leaf(_)) => { }
1348 _ => { unreachable!(); }
1353 /// The symmetric clone of `bulk_steal_left`.
1354 pub fn bulk_steal_right(&mut self, count: usize) {
1356 let mut left_node = ptr::read(self).left_edge().descend();
1357 let left_len = left_node.len();
1358 let mut right_node = ptr::read(self).right_edge().descend();
1359 let right_len = right_node.len();
1361 // Make sure that we may steal safely.
1362 debug_assert!(left_len + count <= CAPACITY);
1363 debug_assert!(right_len >= count);
1365 let new_right_len = right_len - count;
1369 let left_kv = left_node.reborrow_mut().into_kv_pointers_mut();
1370 let right_kv = right_node.reborrow_mut().into_kv_pointers_mut();
1372 let kv = self.reborrow_mut().into_kv_mut();
1373 (kv.0 as *mut K, kv.1 as *mut V)
1376 // Move parent's key/value pair to the left child.
1377 move_kv(parent_kv, 0, left_kv, left_len, 1);
1379 // Move elements from the right child to the left one.
1380 move_kv(right_kv, 0, left_kv, left_len + 1, count - 1);
1382 // Move the right-most stolen pair to the parent.
1383 move_kv(right_kv, count - 1, parent_kv, 0, 1);
1385 // Fix right indexing
1386 ptr::copy(right_kv.0.offset(count as isize),
1389 ptr::copy(right_kv.1.offset(count as isize),
1394 left_node.reborrow_mut().as_leaf_mut().len += count as u16;
1395 right_node.reborrow_mut().as_leaf_mut().len -= count as u16;
1397 match (left_node.force(), right_node.force()) {
1398 (ForceResult::Internal(left), ForceResult::Internal(mut right)) => {
1399 move_edges(right.reborrow_mut(), 0, left, left_len + 1, count);
1401 // Fix right indexing.
1402 let right_edges = right.reborrow_mut().as_internal_mut().edges.as_mut_ptr();
1403 ptr::copy(right_edges.offset(count as isize),
1406 right.correct_childrens_parent_links(0, new_right_len + 1);
1408 (ForceResult::Leaf(_), ForceResult::Leaf(_)) => { }
1409 _ => { unreachable!(); }
1415 unsafe fn move_kv<K, V>(
1416 source: (*mut K, *mut V), source_offset: usize,
1417 dest: (*mut K, *mut V), dest_offset: usize,
1420 ptr::copy_nonoverlapping(source.0.offset(source_offset as isize),
1421 dest.0.offset(dest_offset as isize),
1423 ptr::copy_nonoverlapping(source.1.offset(source_offset as isize),
1424 dest.1.offset(dest_offset as isize),
1428 // Source and destination must have the same height.
1429 unsafe fn move_edges<K, V>(
1430 mut source: NodeRef<marker::Mut, K, V, marker::Internal>, source_offset: usize,
1431 mut dest: NodeRef<marker::Mut, K, V, marker::Internal>, dest_offset: usize,
1434 let source_ptr = source.as_internal_mut().edges.as_mut_ptr();
1435 let dest_ptr = dest.as_internal_mut().edges.as_mut_ptr();
1436 ptr::copy_nonoverlapping(source_ptr.offset(source_offset as isize),
1437 dest_ptr.offset(dest_offset as isize),
1439 dest.correct_childrens_parent_links(dest_offset, dest_offset + count);
1442 impl<BorrowType, K, V, HandleType>
1443 Handle<NodeRef<BorrowType, K, V, marker::LeafOrInternal>, HandleType> {
1445 /// Check whether the underlying node is an `Internal` node or a `Leaf` node.
1446 pub fn force(self) -> ForceResult<
1447 Handle<NodeRef<BorrowType, K, V, marker::Leaf>, HandleType>,
1448 Handle<NodeRef<BorrowType, K, V, marker::Internal>, HandleType>
1450 match self.node.force() {
1451 ForceResult::Leaf(node) => ForceResult::Leaf(Handle {
1454 _marker: PhantomData
1456 ForceResult::Internal(node) => ForceResult::Internal(Handle {
1459 _marker: PhantomData
1465 impl<'a, K, V> Handle<NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal>, marker::Edge> {
1466 /// Move the suffix after `self` from one node to another one. `right` must be empty.
1467 /// The first edge of `right` remains unchanged.
1468 pub fn move_suffix(&mut self,
1469 right: &mut NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal>) {
1471 let left_new_len = self.idx;
1472 let mut left_node = self.reborrow_mut().into_node();
1474 let right_new_len = left_node.len() - left_new_len;
1475 let mut right_node = right.reborrow_mut();
1477 debug_assert!(right_node.len() == 0);
1478 debug_assert!(left_node.height == right_node.height);
1480 let left_kv = left_node.reborrow_mut().into_kv_pointers_mut();
1481 let right_kv = right_node.reborrow_mut().into_kv_pointers_mut();
1484 move_kv(left_kv, left_new_len, right_kv, 0, right_new_len);
1486 left_node.reborrow_mut().as_leaf_mut().len = left_new_len as u16;
1487 right_node.reborrow_mut().as_leaf_mut().len = right_new_len as u16;
1489 match (left_node.force(), right_node.force()) {
1490 (ForceResult::Internal(left), ForceResult::Internal(right)) => {
1491 move_edges(left, left_new_len + 1, right, 1, right_new_len);
1493 (ForceResult::Leaf(_), ForceResult::Leaf(_)) => { }
1494 _ => { unreachable!(); }
1500 pub enum ForceResult<Leaf, Internal> {
1505 pub enum InsertResult<'a, K, V, Type> {
1506 Fit(Handle<NodeRef<marker::Mut<'a>, K, V, Type>, marker::KV>),
1507 Split(NodeRef<marker::Mut<'a>, K, V, Type>, K, V, Root<K, V>)
1511 use core::marker::PhantomData;
1514 pub enum Internal { }
1515 pub enum LeafOrInternal { }
1518 pub struct Immut<'a>(PhantomData<&'a ()>);
1519 pub struct Mut<'a>(PhantomData<&'a mut ()>);
1525 unsafe fn slice_insert<T>(slice: &mut [T], idx: usize, val: T) {
1527 slice.as_ptr().offset(idx as isize),
1528 slice.as_mut_ptr().offset(idx as isize + 1),
1531 ptr::write(slice.get_unchecked_mut(idx), val);
1534 unsafe fn slice_remove<T>(slice: &mut [T], idx: usize) -> T {
1535 let ret = ptr::read(slice.get_unchecked(idx));
1537 slice.as_ptr().offset(idx as isize + 1),
1538 slice.as_mut_ptr().offset(idx as isize),
1539 slice.len() - idx - 1