]> git.lizzy.rs Git - rust.git/blob - src/liballoc/collections/btree/map.rs
Implement clone_from for BTree collections
[rust.git] / src / liballoc / collections / btree / map.rs
1 use core::borrow::Borrow;
2 use core::cmp::Ordering;
3 use core::fmt::Debug;
4 use core::hash::{Hash, Hasher};
5 use core::iter::{FromIterator, FusedIterator, Peekable};
6 use core::marker::PhantomData;
7 use core::ops::Bound::{Excluded, Included, Unbounded};
8 use core::ops::{Index, RangeBounds};
9 use core::{fmt, intrinsics, mem, ptr};
10
11 use super::node::{self, marker, ForceResult::*, Handle, InsertResult::*, NodeRef};
12 use super::search::{self, SearchResult::*};
13
14 use Entry::*;
15 use UnderflowResult::*;
16
17 /// A map based on a B-Tree.
18 ///
19 /// B-Trees represent a fundamental compromise between cache-efficiency and actually minimizing
20 /// the amount of work performed in a search. In theory, a binary search tree (BST) is the optimal
21 /// choice for a sorted map, as a perfectly balanced BST performs the theoretical minimum amount of
22 /// comparisons necessary to find an element (log<sub>2</sub>n). However, in practice the way this
23 /// is done is *very* inefficient for modern computer architectures. In particular, every element
24 /// is stored in its own individually heap-allocated node. This means that every single insertion
25 /// triggers a heap-allocation, and every single comparison should be a cache-miss. Since these
26 /// are both notably expensive things to do in practice, we are forced to at very least reconsider
27 /// the BST strategy.
28 ///
29 /// A B-Tree instead makes each node contain B-1 to 2B-1 elements in a contiguous array. By doing
30 /// this, we reduce the number of allocations by a factor of B, and improve cache efficiency in
31 /// searches. However, this does mean that searches will have to do *more* comparisons on average.
32 /// The precise number of comparisons depends on the node search strategy used. For optimal cache
33 /// efficiency, one could search the nodes linearly. For optimal comparisons, one could search
34 /// the node using binary search. As a compromise, one could also perform a linear search
35 /// that initially only checks every i<sup>th</sup> element for some choice of i.
36 ///
37 /// Currently, our implementation simply performs naive linear search. This provides excellent
38 /// performance on *small* nodes of elements which are cheap to compare. However in the future we
39 /// would like to further explore choosing the optimal search strategy based on the choice of B,
40 /// and possibly other factors. Using linear search, searching for a random element is expected
41 /// to take O(B log<sub>B</sub>n) comparisons, which is generally worse than a BST. In practice,
42 /// however, performance is excellent.
43 ///
44 /// It is a logic error for a key to be modified in such a way that the key's ordering relative to
45 /// any other key, as determined by the [`Ord`] trait, changes while it is in the map. This is
46 /// normally only possible through [`Cell`], [`RefCell`], global state, I/O, or unsafe code.
47 ///
48 /// [`Ord`]: ../../std/cmp/trait.Ord.html
49 /// [`Cell`]: ../../std/cell/struct.Cell.html
50 /// [`RefCell`]: ../../std/cell/struct.RefCell.html
51 ///
52 /// # Examples
53 ///
54 /// ```
55 /// use std::collections::BTreeMap;
56 ///
57 /// // type inference lets us omit an explicit type signature (which
58 /// // would be `BTreeMap<&str, &str>` in this example).
59 /// let mut movie_reviews = BTreeMap::new();
60 ///
61 /// // review some movies.
62 /// movie_reviews.insert("Office Space",       "Deals with real issues in the workplace.");
63 /// movie_reviews.insert("Pulp Fiction",       "Masterpiece.");
64 /// movie_reviews.insert("The Godfather",      "Very enjoyable.");
65 /// movie_reviews.insert("The Blues Brothers", "Eye lyked it a lot.");
66 ///
67 /// // check for a specific one.
68 /// if !movie_reviews.contains_key("Les Misérables") {
69 ///     println!("We've got {} reviews, but Les Misérables ain't one.",
70 ///              movie_reviews.len());
71 /// }
72 ///
73 /// // oops, this review has a lot of spelling mistakes, let's delete it.
74 /// movie_reviews.remove("The Blues Brothers");
75 ///
76 /// // look up the values associated with some keys.
77 /// let to_find = ["Up!", "Office Space"];
78 /// for movie in &to_find {
79 ///     match movie_reviews.get(movie) {
80 ///        Some(review) => println!("{}: {}", movie, review),
81 ///        None => println!("{} is unreviewed.", movie)
82 ///     }
83 /// }
84 ///
85 /// // Look up the value for a key (will panic if the key is not found).
86 /// println!("Movie review: {}", movie_reviews["Office Space"]);
87 ///
88 /// // iterate over everything.
89 /// for (movie, review) in &movie_reviews {
90 ///     println!("{}: \"{}\"", movie, review);
91 /// }
92 /// ```
93 ///
94 /// `BTreeMap` also implements an [`Entry API`](#method.entry), which allows
95 /// for more complex methods of getting, setting, updating and removing keys and
96 /// their values:
97 ///
98 /// ```
99 /// use std::collections::BTreeMap;
100 ///
101 /// // type inference lets us omit an explicit type signature (which
102 /// // would be `BTreeMap<&str, u8>` in this example).
103 /// let mut player_stats = BTreeMap::new();
104 ///
105 /// fn random_stat_buff() -> u8 {
106 ///     // could actually return some random value here - let's just return
107 ///     // some fixed value for now
108 ///     42
109 /// }
110 ///
111 /// // insert a key only if it doesn't already exist
112 /// player_stats.entry("health").or_insert(100);
113 ///
114 /// // insert a key using a function that provides a new value only if it
115 /// // doesn't already exist
116 /// player_stats.entry("defence").or_insert_with(random_stat_buff);
117 ///
118 /// // update a key, guarding against the key possibly not being set
119 /// let stat = player_stats.entry("attack").or_insert(100);
120 /// *stat += random_stat_buff();
121 /// ```
122 #[stable(feature = "rust1", since = "1.0.0")]
123 pub struct BTreeMap<K, V> {
124     root: node::Root<K, V>,
125     length: usize,
126 }
127
128 #[stable(feature = "btree_drop", since = "1.7.0")]
129 unsafe impl<#[may_dangle] K, #[may_dangle] V> Drop for BTreeMap<K, V> {
130     fn drop(&mut self) {
131         unsafe {
132             drop(ptr::read(self).into_iter());
133         }
134     }
135 }
136
137 #[stable(feature = "rust1", since = "1.0.0")]
138 impl<K: Clone, V: Clone> Clone for BTreeMap<K, V> {
139     fn clone(&self) -> BTreeMap<K, V> {
140         fn clone_subtree<'a, K: Clone, V: Clone>(
141             node: node::NodeRef<marker::Immut<'a>, K, V, marker::LeafOrInternal>,
142         ) -> BTreeMap<K, V>
143         where
144             K: 'a,
145             V: 'a,
146         {
147             match node.force() {
148                 Leaf(leaf) => {
149                     let mut out_tree = BTreeMap { root: node::Root::new_leaf(), length: 0 };
150
151                     {
152                         let mut out_node = match out_tree.root.as_mut().force() {
153                             Leaf(leaf) => leaf,
154                             Internal(_) => unreachable!(),
155                         };
156
157                         let mut in_edge = leaf.first_edge();
158                         while let Ok(kv) = in_edge.right_kv() {
159                             let (k, v) = kv.into_kv();
160                             in_edge = kv.right_edge();
161
162                             out_node.push(k.clone(), v.clone());
163                             out_tree.length += 1;
164                         }
165                     }
166
167                     out_tree
168                 }
169                 Internal(internal) => {
170                     let mut out_tree = clone_subtree(internal.first_edge().descend());
171
172                     {
173                         let mut out_node = out_tree.root.push_level();
174                         let mut in_edge = internal.first_edge();
175                         while let Ok(kv) = in_edge.right_kv() {
176                             let (k, v) = kv.into_kv();
177                             in_edge = kv.right_edge();
178
179                             let k = (*k).clone();
180                             let v = (*v).clone();
181                             let subtree = clone_subtree(in_edge.descend());
182
183                             // We can't destructure subtree directly
184                             // because BTreeMap implements Drop
185                             let (subroot, sublength) = unsafe {
186                                 let root = ptr::read(&subtree.root);
187                                 let length = subtree.length;
188                                 mem::forget(subtree);
189                                 (root, length)
190                             };
191
192                             out_node.push(k, v, subroot);
193                             out_tree.length += 1 + sublength;
194                         }
195                     }
196
197                     out_tree
198                 }
199             }
200         }
201
202         if self.is_empty() {
203             // Ideally we'd call `BTreeMap::new` here, but that has the `K:
204             // Ord` constraint, which this method lacks.
205             BTreeMap { root: node::Root::shared_empty_root(), length: 0 }
206         } else {
207             clone_subtree(self.root.as_ref())
208         }
209     }
210
211     fn clone_from(&mut self, other: &Self) {
212         BTreeClone::clone_from(self, other);
213     }
214 }
215
216 trait BTreeClone {
217     fn clone_from(&mut self, other: &Self);
218 }
219
220 impl<K: Clone, V: Clone> BTreeClone for BTreeMap<K, V> {
221     default fn clone_from(&mut self, other: &Self) {
222         *self = other.clone();
223     }
224 }
225
226 impl<K: Clone + Ord, V: Clone> BTreeClone for BTreeMap<K, V> {
227     fn clone_from(&mut self, other: &Self) {
228         // This truncates `self` to `other.len()` by calling `split_off` on
229         // the first key after `other.len()` elements if it exists
230         if let Some(key) = {
231             if self.len() > other.len() {
232                 let diff = self.len() - other.len();
233                 if diff <= other.len() {
234                     self.iter().nth_back(diff - 1).map(|pair| (*pair.0).clone())
235                 } else {
236                     self.iter().nth(other.len()).map(|pair| (*pair.0).clone())
237                 }
238             } else {
239                 None
240             }
241         } {
242             self.split_off(&key);
243         }
244         let mut siter = self.range_mut(..);
245         let mut oiter = other.iter();
246         // After truncation, `self` is at most as long as `other` so this loop
247         // replaces every key-value pair in `self`. Since `oiter` is in sorted
248         // order and the structure of the `BTreeMap` stays the same,
249         // the BTree invariants are maintained at the end of the loop
250         while siter.front != siter.back {
251             if let Some((ok, ov)) = oiter.next() {
252                 // This is safe because the `siter.front != siter.back` check
253                 // ensures that `siter` is nonempty
254                 let (sk, sv) = unsafe { siter.next_unchecked() };
255                 sk.clone_from(ok);
256                 sv.clone_from(ov);
257             } else {
258                 break;
259             }
260         }
261         // If `other` is longer than `self`, the remaining elements are inserted
262         self.extend(oiter.map(|(k, v)| ((*k).clone(), (*v).clone())));
263     }
264 }
265
266 impl<K, Q: ?Sized> super::Recover<Q> for BTreeMap<K, ()>
267 where
268     K: Borrow<Q> + Ord,
269     Q: Ord,
270 {
271     type Key = K;
272
273     fn get(&self, key: &Q) -> Option<&K> {
274         match search::search_tree(self.root.as_ref(), key) {
275             Found(handle) => Some(handle.into_kv().0),
276             GoDown(_) => None,
277         }
278     }
279
280     fn take(&mut self, key: &Q) -> Option<K> {
281         match search::search_tree(self.root.as_mut(), key) {
282             Found(handle) => Some(
283                 OccupiedEntry { handle, length: &mut self.length, _marker: PhantomData }
284                     .remove_kv()
285                     .0,
286             ),
287             GoDown(_) => None,
288         }
289     }
290
291     fn replace(&mut self, key: K) -> Option<K> {
292         self.ensure_root_is_owned();
293         match search::search_tree::<marker::Mut<'_>, K, (), K>(self.root.as_mut(), &key) {
294             Found(handle) => Some(mem::replace(handle.into_kv_mut().0, key)),
295             GoDown(handle) => {
296                 VacantEntry { key, handle, length: &mut self.length, _marker: PhantomData }
297                     .insert(());
298                 None
299             }
300         }
301     }
302 }
303
304 /// An iterator over the entries of a `BTreeMap`.
305 ///
306 /// This `struct` is created by the [`iter`] method on [`BTreeMap`]. See its
307 /// documentation for more.
308 ///
309 /// [`iter`]: struct.BTreeMap.html#method.iter
310 /// [`BTreeMap`]: struct.BTreeMap.html
311 #[stable(feature = "rust1", since = "1.0.0")]
312 pub struct Iter<'a, K: 'a, V: 'a> {
313     range: Range<'a, K, V>,
314     length: usize,
315 }
316
317 #[stable(feature = "collection_debug", since = "1.17.0")]
318 impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for Iter<'_, K, V> {
319     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
320         f.debug_list().entries(self.clone()).finish()
321     }
322 }
323
324 /// A mutable iterator over the entries of a `BTreeMap`.
325 ///
326 /// This `struct` is created by the [`iter_mut`] method on [`BTreeMap`]. See its
327 /// documentation for more.
328 ///
329 /// [`iter_mut`]: struct.BTreeMap.html#method.iter_mut
330 /// [`BTreeMap`]: struct.BTreeMap.html
331 #[stable(feature = "rust1", since = "1.0.0")]
332 #[derive(Debug)]
333 pub struct IterMut<'a, K: 'a, V: 'a> {
334     range: RangeMut<'a, K, V>,
335     length: usize,
336 }
337
338 /// An owning iterator over the entries of a `BTreeMap`.
339 ///
340 /// This `struct` is created by the [`into_iter`] method on [`BTreeMap`][`BTreeMap`]
341 /// (provided by the `IntoIterator` trait). See its documentation for more.
342 ///
343 /// [`into_iter`]: struct.BTreeMap.html#method.into_iter
344 /// [`BTreeMap`]: struct.BTreeMap.html
345 #[stable(feature = "rust1", since = "1.0.0")]
346 pub struct IntoIter<K, V> {
347     front: Handle<NodeRef<marker::Owned, K, V, marker::Leaf>, marker::Edge>,
348     back: Handle<NodeRef<marker::Owned, K, V, marker::Leaf>, marker::Edge>,
349     length: usize,
350 }
351
352 #[stable(feature = "collection_debug", since = "1.17.0")]
353 impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for IntoIter<K, V> {
354     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
355         let range = Range { front: self.front.reborrow(), back: self.back.reborrow() };
356         f.debug_list().entries(range).finish()
357     }
358 }
359
360 /// An iterator over the keys of a `BTreeMap`.
361 ///
362 /// This `struct` is created by the [`keys`] method on [`BTreeMap`]. See its
363 /// documentation for more.
364 ///
365 /// [`keys`]: struct.BTreeMap.html#method.keys
366 /// [`BTreeMap`]: struct.BTreeMap.html
367 #[stable(feature = "rust1", since = "1.0.0")]
368 pub struct Keys<'a, K: 'a, V: 'a> {
369     inner: Iter<'a, K, V>,
370 }
371
372 #[stable(feature = "collection_debug", since = "1.17.0")]
373 impl<K: fmt::Debug, V> fmt::Debug for Keys<'_, K, V> {
374     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
375         f.debug_list().entries(self.clone()).finish()
376     }
377 }
378
379 /// An iterator over the values of a `BTreeMap`.
380 ///
381 /// This `struct` is created by the [`values`] method on [`BTreeMap`]. See its
382 /// documentation for more.
383 ///
384 /// [`values`]: struct.BTreeMap.html#method.values
385 /// [`BTreeMap`]: struct.BTreeMap.html
386 #[stable(feature = "rust1", since = "1.0.0")]
387 pub struct Values<'a, K: 'a, V: 'a> {
388     inner: Iter<'a, K, V>,
389 }
390
391 #[stable(feature = "collection_debug", since = "1.17.0")]
392 impl<K, V: fmt::Debug> fmt::Debug for Values<'_, K, V> {
393     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
394         f.debug_list().entries(self.clone()).finish()
395     }
396 }
397
398 /// A mutable iterator over the values of a `BTreeMap`.
399 ///
400 /// This `struct` is created by the [`values_mut`] method on [`BTreeMap`]. See its
401 /// documentation for more.
402 ///
403 /// [`values_mut`]: struct.BTreeMap.html#method.values_mut
404 /// [`BTreeMap`]: struct.BTreeMap.html
405 #[stable(feature = "map_values_mut", since = "1.10.0")]
406 #[derive(Debug)]
407 pub struct ValuesMut<'a, K: 'a, V: 'a> {
408     inner: IterMut<'a, K, V>,
409 }
410
411 /// An iterator over a sub-range of entries in a `BTreeMap`.
412 ///
413 /// This `struct` is created by the [`range`] method on [`BTreeMap`]. See its
414 /// documentation for more.
415 ///
416 /// [`range`]: struct.BTreeMap.html#method.range
417 /// [`BTreeMap`]: struct.BTreeMap.html
418 #[stable(feature = "btree_range", since = "1.17.0")]
419 pub struct Range<'a, K: 'a, V: 'a> {
420     front: Handle<NodeRef<marker::Immut<'a>, K, V, marker::Leaf>, marker::Edge>,
421     back: Handle<NodeRef<marker::Immut<'a>, K, V, marker::Leaf>, marker::Edge>,
422 }
423
424 #[stable(feature = "collection_debug", since = "1.17.0")]
425 impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for Range<'_, K, V> {
426     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
427         f.debug_list().entries(self.clone()).finish()
428     }
429 }
430
431 /// A mutable iterator over a sub-range of entries in a `BTreeMap`.
432 ///
433 /// This `struct` is created by the [`range_mut`] method on [`BTreeMap`]. See its
434 /// documentation for more.
435 ///
436 /// [`range_mut`]: struct.BTreeMap.html#method.range_mut
437 /// [`BTreeMap`]: struct.BTreeMap.html
438 #[stable(feature = "btree_range", since = "1.17.0")]
439 pub struct RangeMut<'a, K: 'a, V: 'a> {
440     front: Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge>,
441     back: Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge>,
442
443     // Be invariant in `K` and `V`
444     _marker: PhantomData<&'a mut (K, V)>,
445 }
446
447 #[stable(feature = "collection_debug", since = "1.17.0")]
448 impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for RangeMut<'_, K, V> {
449     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
450         let range = Range { front: self.front.reborrow(), back: self.back.reborrow() };
451         f.debug_list().entries(range).finish()
452     }
453 }
454
455 /// A view into a single entry in a map, which may either be vacant or occupied.
456 ///
457 /// This `enum` is constructed from the [`entry`] method on [`BTreeMap`].
458 ///
459 /// [`BTreeMap`]: struct.BTreeMap.html
460 /// [`entry`]: struct.BTreeMap.html#method.entry
461 #[stable(feature = "rust1", since = "1.0.0")]
462 pub enum Entry<'a, K: 'a, V: 'a> {
463     /// A vacant entry.
464     #[stable(feature = "rust1", since = "1.0.0")]
465     Vacant(#[stable(feature = "rust1", since = "1.0.0")] VacantEntry<'a, K, V>),
466
467     /// An occupied entry.
468     #[stable(feature = "rust1", since = "1.0.0")]
469     Occupied(#[stable(feature = "rust1", since = "1.0.0")] OccupiedEntry<'a, K, V>),
470 }
471
472 #[stable(feature = "debug_btree_map", since = "1.12.0")]
473 impl<K: Debug + Ord, V: Debug> Debug for Entry<'_, K, V> {
474     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
475         match *self {
476             Vacant(ref v) => f.debug_tuple("Entry").field(v).finish(),
477             Occupied(ref o) => f.debug_tuple("Entry").field(o).finish(),
478         }
479     }
480 }
481
482 /// A view into a vacant entry in a `BTreeMap`.
483 /// It is part of the [`Entry`] enum.
484 ///
485 /// [`Entry`]: enum.Entry.html
486 #[stable(feature = "rust1", since = "1.0.0")]
487 pub struct VacantEntry<'a, K: 'a, V: 'a> {
488     key: K,
489     handle: Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge>,
490     length: &'a mut usize,
491
492     // Be invariant in `K` and `V`
493     _marker: PhantomData<&'a mut (K, V)>,
494 }
495
496 #[stable(feature = "debug_btree_map", since = "1.12.0")]
497 impl<K: Debug + Ord, V> Debug for VacantEntry<'_, K, V> {
498     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
499         f.debug_tuple("VacantEntry").field(self.key()).finish()
500     }
501 }
502
503 /// A view into an occupied entry in a `BTreeMap`.
504 /// It is part of the [`Entry`] enum.
505 ///
506 /// [`Entry`]: enum.Entry.html
507 #[stable(feature = "rust1", since = "1.0.0")]
508 pub struct OccupiedEntry<'a, K: 'a, V: 'a> {
509     handle: Handle<NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal>, marker::KV>,
510
511     length: &'a mut usize,
512
513     // Be invariant in `K` and `V`
514     _marker: PhantomData<&'a mut (K, V)>,
515 }
516
517 #[stable(feature = "debug_btree_map", since = "1.12.0")]
518 impl<K: Debug + Ord, V: Debug> Debug for OccupiedEntry<'_, K, V> {
519     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
520         f.debug_struct("OccupiedEntry").field("key", self.key()).field("value", self.get()).finish()
521     }
522 }
523
524 // An iterator for merging two sorted sequences into one
525 struct MergeIter<K, V, I: Iterator<Item = (K, V)>> {
526     left: Peekable<I>,
527     right: Peekable<I>,
528 }
529
530 impl<K: Ord, V> BTreeMap<K, V> {
531     /// Makes a new empty BTreeMap with a reasonable choice for B.
532     ///
533     /// # Examples
534     ///
535     /// Basic usage:
536     ///
537     /// ```
538     /// use std::collections::BTreeMap;
539     ///
540     /// let mut map = BTreeMap::new();
541     ///
542     /// // entries can now be inserted into the empty map
543     /// map.insert(1, "a");
544     /// ```
545     #[stable(feature = "rust1", since = "1.0.0")]
546     pub fn new() -> BTreeMap<K, V> {
547         BTreeMap { root: node::Root::shared_empty_root(), length: 0 }
548     }
549
550     /// Clears the map, removing all values.
551     ///
552     /// # Examples
553     ///
554     /// Basic usage:
555     ///
556     /// ```
557     /// use std::collections::BTreeMap;
558     ///
559     /// let mut a = BTreeMap::new();
560     /// a.insert(1, "a");
561     /// a.clear();
562     /// assert!(a.is_empty());
563     /// ```
564     #[stable(feature = "rust1", since = "1.0.0")]
565     pub fn clear(&mut self) {
566         *self = BTreeMap::new();
567     }
568
569     /// Returns a reference to the value corresponding to the key.
570     ///
571     /// The key may be any borrowed form of the map's key type, but the ordering
572     /// on the borrowed form *must* match the ordering on the key type.
573     ///
574     /// # Examples
575     ///
576     /// Basic usage:
577     ///
578     /// ```
579     /// use std::collections::BTreeMap;
580     ///
581     /// let mut map = BTreeMap::new();
582     /// map.insert(1, "a");
583     /// assert_eq!(map.get(&1), Some(&"a"));
584     /// assert_eq!(map.get(&2), None);
585     /// ```
586     #[stable(feature = "rust1", since = "1.0.0")]
587     pub fn get<Q: ?Sized>(&self, key: &Q) -> Option<&V>
588     where
589         K: Borrow<Q>,
590         Q: Ord,
591     {
592         match search::search_tree(self.root.as_ref(), key) {
593             Found(handle) => Some(handle.into_kv().1),
594             GoDown(_) => None,
595         }
596     }
597
598     /// Returns the key-value pair corresponding to the supplied key.
599     ///
600     /// The supplied key may be any borrowed form of the map's key type, but the ordering
601     /// on the borrowed form *must* match the ordering on the key type.
602     ///
603     /// # Examples
604     ///
605     /// ```
606     /// use std::collections::BTreeMap;
607     ///
608     /// let mut map = BTreeMap::new();
609     /// map.insert(1, "a");
610     /// assert_eq!(map.get_key_value(&1), Some((&1, &"a")));
611     /// assert_eq!(map.get_key_value(&2), None);
612     /// ```
613     #[stable(feature = "map_get_key_value", since = "1.40.0")]
614     pub fn get_key_value<Q: ?Sized>(&self, k: &Q) -> Option<(&K, &V)>
615     where
616         K: Borrow<Q>,
617         Q: Ord,
618     {
619         match search::search_tree(self.root.as_ref(), k) {
620             Found(handle) => Some(handle.into_kv()),
621             GoDown(_) => None,
622         }
623     }
624
625     /// Returns the first key-value pair in the map.
626     /// The key in this pair is the minimum key in the map.
627     ///
628     /// # Examples
629     ///
630     /// Basic usage:
631     ///
632     /// ```
633     /// #![feature(map_first_last)]
634     /// use std::collections::BTreeMap;
635     ///
636     /// let mut map = BTreeMap::new();
637     /// assert_eq!(map.first_key_value(), None);
638     /// map.insert(1, "b");
639     /// map.insert(2, "a");
640     /// assert_eq!(map.first_key_value(), Some((&1, &"b")));
641     /// ```
642     #[unstable(feature = "map_first_last", issue = "62924")]
643     pub fn first_key_value<T: ?Sized>(&self) -> Option<(&K, &V)>
644     where
645         T: Ord,
646         K: Borrow<T>,
647     {
648         let front = first_leaf_edge(self.root.as_ref());
649         front.right_kv().ok().map(Handle::into_kv)
650     }
651
652     /// Returns the first entry in the map for in-place manipulation.
653     /// The key of this entry is the minimum key in the map.
654     ///
655     /// # Examples
656     ///
657     /// Contrived way to `clear` a map:
658     ///
659     /// ```
660     /// #![feature(map_first_last)]
661     /// use std::collections::BTreeMap;
662     ///
663     /// let mut map = BTreeMap::new();
664     /// map.insert(1, "a");
665     /// map.insert(2, "b");
666     /// while let Some(entry) = map.first_entry() {
667     ///     let (key, val) = entry.remove_entry();
668     ///     assert!(!map.contains_key(&key));
669     /// }
670     /// ```
671     #[unstable(feature = "map_first_last", issue = "62924")]
672     pub fn first_entry<T: ?Sized>(&mut self) -> Option<OccupiedEntry<'_, K, V>>
673     where
674         T: Ord,
675         K: Borrow<T>,
676     {
677         match self.length {
678             0 => None,
679             _ => Some(OccupiedEntry {
680                 handle: self.root.as_mut().first_kv(),
681                 length: &mut self.length,
682                 _marker: PhantomData,
683             }),
684         }
685     }
686
687     /// Returns the last key-value pair in the map.
688     /// The key in this pair is the maximum key in the map.
689     ///
690     /// # Examples
691     ///
692     /// Basic usage:
693     ///
694     /// ```
695     /// #![feature(map_first_last)]
696     /// use std::collections::BTreeMap;
697     ///
698     /// let mut map = BTreeMap::new();
699     /// map.insert(1, "b");
700     /// map.insert(2, "a");
701     /// assert_eq!(map.last_key_value(), Some((&2, &"a")));
702     /// ```
703     #[unstable(feature = "map_first_last", issue = "62924")]
704     pub fn last_key_value<T: ?Sized>(&self) -> Option<(&K, &V)>
705     where
706         T: Ord,
707         K: Borrow<T>,
708     {
709         let back = last_leaf_edge(self.root.as_ref());
710         back.left_kv().ok().map(Handle::into_kv)
711     }
712
713     /// Returns the last entry in the map for in-place manipulation.
714     /// The key of this entry is the maximum key in the map.
715     ///
716     /// # Examples
717     ///
718     /// Contrived way to `clear` a map:
719     ///
720     /// ```
721     /// #![feature(map_first_last)]
722     /// use std::collections::BTreeMap;
723     ///
724     /// let mut map = BTreeMap::new();
725     /// map.insert(1, "a");
726     /// map.insert(2, "b");
727     /// while let Some(entry) = map.last_entry() {
728     ///     let (key, val) = entry.remove_entry();
729     ///     assert!(!map.contains_key(&key));
730     /// }
731     /// ```
732     #[unstable(feature = "map_first_last", issue = "62924")]
733     pub fn last_entry<T: ?Sized>(&mut self) -> Option<OccupiedEntry<'_, K, V>>
734     where
735         T: Ord,
736         K: Borrow<T>,
737     {
738         match self.length {
739             0 => None,
740             _ => Some(OccupiedEntry {
741                 handle: self.root.as_mut().last_kv(),
742                 length: &mut self.length,
743                 _marker: PhantomData,
744             }),
745         }
746     }
747
748     /// Returns `true` if the map contains a value for the specified key.
749     ///
750     /// The key may be any borrowed form of the map's key type, but the ordering
751     /// on the borrowed form *must* match the ordering on the key type.
752     ///
753     /// # Examples
754     ///
755     /// Basic usage:
756     ///
757     /// ```
758     /// use std::collections::BTreeMap;
759     ///
760     /// let mut map = BTreeMap::new();
761     /// map.insert(1, "a");
762     /// assert_eq!(map.contains_key(&1), true);
763     /// assert_eq!(map.contains_key(&2), false);
764     /// ```
765     #[stable(feature = "rust1", since = "1.0.0")]
766     pub fn contains_key<Q: ?Sized>(&self, key: &Q) -> bool
767     where
768         K: Borrow<Q>,
769         Q: Ord,
770     {
771         self.get(key).is_some()
772     }
773
774     /// Returns a mutable reference to the value corresponding to the key.
775     ///
776     /// The key may be any borrowed form of the map's key type, but the ordering
777     /// on the borrowed form *must* match the ordering on the key type.
778     ///
779     /// # Examples
780     ///
781     /// Basic usage:
782     ///
783     /// ```
784     /// use std::collections::BTreeMap;
785     ///
786     /// let mut map = BTreeMap::new();
787     /// map.insert(1, "a");
788     /// if let Some(x) = map.get_mut(&1) {
789     ///     *x = "b";
790     /// }
791     /// assert_eq!(map[&1], "b");
792     /// ```
793     // See `get` for implementation notes, this is basically a copy-paste with mut's added
794     #[stable(feature = "rust1", since = "1.0.0")]
795     pub fn get_mut<Q: ?Sized>(&mut self, key: &Q) -> Option<&mut V>
796     where
797         K: Borrow<Q>,
798         Q: Ord,
799     {
800         match search::search_tree(self.root.as_mut(), key) {
801             Found(handle) => Some(handle.into_kv_mut().1),
802             GoDown(_) => None,
803         }
804     }
805
806     /// Inserts a key-value pair into the map.
807     ///
808     /// If the map did not have this key present, `None` is returned.
809     ///
810     /// If the map did have this key present, the value is updated, and the old
811     /// value is returned. The key is not updated, though; this matters for
812     /// types that can be `==` without being identical. See the [module-level
813     /// documentation] for more.
814     ///
815     /// [module-level documentation]: index.html#insert-and-complex-keys
816     ///
817     /// # Examples
818     ///
819     /// Basic usage:
820     ///
821     /// ```
822     /// use std::collections::BTreeMap;
823     ///
824     /// let mut map = BTreeMap::new();
825     /// assert_eq!(map.insert(37, "a"), None);
826     /// assert_eq!(map.is_empty(), false);
827     ///
828     /// map.insert(37, "b");
829     /// assert_eq!(map.insert(37, "c"), Some("b"));
830     /// assert_eq!(map[&37], "c");
831     /// ```
832     #[stable(feature = "rust1", since = "1.0.0")]
833     pub fn insert(&mut self, key: K, value: V) -> Option<V> {
834         match self.entry(key) {
835             Occupied(mut entry) => Some(entry.insert(value)),
836             Vacant(entry) => {
837                 entry.insert(value);
838                 None
839             }
840         }
841     }
842
843     /// Removes a key from the map, returning the value at the key if the key
844     /// was previously in the map.
845     ///
846     /// The key may be any borrowed form of the map's key type, but the ordering
847     /// on the borrowed form *must* match the ordering on the key type.
848     ///
849     /// # Examples
850     ///
851     /// Basic usage:
852     ///
853     /// ```
854     /// use std::collections::BTreeMap;
855     ///
856     /// let mut map = BTreeMap::new();
857     /// map.insert(1, "a");
858     /// assert_eq!(map.remove(&1), Some("a"));
859     /// assert_eq!(map.remove(&1), None);
860     /// ```
861     #[stable(feature = "rust1", since = "1.0.0")]
862     pub fn remove<Q: ?Sized>(&mut self, key: &Q) -> Option<V>
863     where
864         K: Borrow<Q>,
865         Q: Ord,
866     {
867         match search::search_tree(self.root.as_mut(), key) {
868             Found(handle) => Some(
869                 OccupiedEntry { handle, length: &mut self.length, _marker: PhantomData }.remove(),
870             ),
871             GoDown(_) => None,
872         }
873     }
874
875     /// Moves all elements from `other` into `Self`, leaving `other` empty.
876     ///
877     /// # Examples
878     ///
879     /// ```
880     /// use std::collections::BTreeMap;
881     ///
882     /// let mut a = BTreeMap::new();
883     /// a.insert(1, "a");
884     /// a.insert(2, "b");
885     /// a.insert(3, "c");
886     ///
887     /// let mut b = BTreeMap::new();
888     /// b.insert(3, "d");
889     /// b.insert(4, "e");
890     /// b.insert(5, "f");
891     ///
892     /// a.append(&mut b);
893     ///
894     /// assert_eq!(a.len(), 5);
895     /// assert_eq!(b.len(), 0);
896     ///
897     /// assert_eq!(a[&1], "a");
898     /// assert_eq!(a[&2], "b");
899     /// assert_eq!(a[&3], "d");
900     /// assert_eq!(a[&4], "e");
901     /// assert_eq!(a[&5], "f");
902     /// ```
903     #[stable(feature = "btree_append", since = "1.11.0")]
904     pub fn append(&mut self, other: &mut Self) {
905         // Do we have to append anything at all?
906         if other.is_empty() {
907             return;
908         }
909
910         // We can just swap `self` and `other` if `self` is empty.
911         if self.is_empty() {
912             mem::swap(self, other);
913             return;
914         }
915
916         // First, we merge `self` and `other` into a sorted sequence in linear time.
917         let self_iter = mem::take(self).into_iter();
918         let other_iter = mem::take(other).into_iter();
919         let iter = MergeIter { left: self_iter.peekable(), right: other_iter.peekable() };
920
921         // Second, we build a tree from the sorted sequence in linear time.
922         self.from_sorted_iter(iter);
923         self.fix_right_edge();
924     }
925
926     /// Constructs a double-ended iterator over a sub-range of elements in the map.
927     /// The simplest way is to use the range syntax `min..max`, thus `range(min..max)` will
928     /// yield elements from min (inclusive) to max (exclusive).
929     /// The range may also be entered as `(Bound<T>, Bound<T>)`, so for example
930     /// `range((Excluded(4), Included(10)))` will yield a left-exclusive, right-inclusive
931     /// range from 4 to 10.
932     ///
933     /// # Panics
934     ///
935     /// Panics if range `start > end`.
936     /// Panics if range `start == end` and both bounds are `Excluded`.
937     ///
938     /// # Examples
939     ///
940     /// Basic usage:
941     ///
942     /// ```
943     /// use std::collections::BTreeMap;
944     /// use std::ops::Bound::Included;
945     ///
946     /// let mut map = BTreeMap::new();
947     /// map.insert(3, "a");
948     /// map.insert(5, "b");
949     /// map.insert(8, "c");
950     /// for (&key, &value) in map.range((Included(&4), Included(&8))) {
951     ///     println!("{}: {}", key, value);
952     /// }
953     /// assert_eq!(Some((&5, &"b")), map.range(4..).next());
954     /// ```
955     #[stable(feature = "btree_range", since = "1.17.0")]
956     pub fn range<T: ?Sized, R>(&self, range: R) -> Range<'_, K, V>
957     where
958         T: Ord,
959         K: Borrow<T>,
960         R: RangeBounds<T>,
961     {
962         let root1 = self.root.as_ref();
963         let root2 = self.root.as_ref();
964         let (f, b) = range_search(root1, root2, range);
965
966         Range { front: f, back: b }
967     }
968
969     /// Constructs a mutable double-ended iterator over a sub-range of elements in the map.
970     /// The simplest way is to use the range syntax `min..max`, thus `range(min..max)` will
971     /// yield elements from min (inclusive) to max (exclusive).
972     /// The range may also be entered as `(Bound<T>, Bound<T>)`, so for example
973     /// `range((Excluded(4), Included(10)))` will yield a left-exclusive, right-inclusive
974     /// range from 4 to 10.
975     ///
976     /// # Panics
977     ///
978     /// Panics if range `start > end`.
979     /// Panics if range `start == end` and both bounds are `Excluded`.
980     ///
981     /// # Examples
982     ///
983     /// Basic usage:
984     ///
985     /// ```
986     /// use std::collections::BTreeMap;
987     ///
988     /// let mut map: BTreeMap<&str, i32> = ["Alice", "Bob", "Carol", "Cheryl"]
989     ///     .iter()
990     ///     .map(|&s| (s, 0))
991     ///     .collect();
992     /// for (_, balance) in map.range_mut("B".."Cheryl") {
993     ///     *balance += 100;
994     /// }
995     /// for (name, balance) in &map {
996     ///     println!("{} => {}", name, balance);
997     /// }
998     /// ```
999     #[stable(feature = "btree_range", since = "1.17.0")]
1000     pub fn range_mut<T: ?Sized, R>(&mut self, range: R) -> RangeMut<'_, K, V>
1001     where
1002         T: Ord,
1003         K: Borrow<T>,
1004         R: RangeBounds<T>,
1005     {
1006         let root1 = self.root.as_mut();
1007         let root2 = unsafe { ptr::read(&root1) };
1008         let (f, b) = range_search(root1, root2, range);
1009
1010         RangeMut { front: f, back: b, _marker: PhantomData }
1011     }
1012
1013     /// Gets the given key's corresponding entry in the map for in-place manipulation.
1014     ///
1015     /// # Examples
1016     ///
1017     /// Basic usage:
1018     ///
1019     /// ```
1020     /// use std::collections::BTreeMap;
1021     ///
1022     /// let mut count: BTreeMap<&str, usize> = BTreeMap::new();
1023     ///
1024     /// // count the number of occurrences of letters in the vec
1025     /// for x in vec!["a","b","a","c","a","b"] {
1026     ///     *count.entry(x).or_insert(0) += 1;
1027     /// }
1028     ///
1029     /// assert_eq!(count["a"], 3);
1030     /// ```
1031     #[stable(feature = "rust1", since = "1.0.0")]
1032     pub fn entry(&mut self, key: K) -> Entry<'_, K, V> {
1033         // FIXME(@porglezomp) Avoid allocating if we don't insert
1034         self.ensure_root_is_owned();
1035         match search::search_tree(self.root.as_mut(), &key) {
1036             Found(handle) => {
1037                 Occupied(OccupiedEntry { handle, length: &mut self.length, _marker: PhantomData })
1038             }
1039             GoDown(handle) => {
1040                 Vacant(VacantEntry { key, handle, length: &mut self.length, _marker: PhantomData })
1041             }
1042         }
1043     }
1044
1045     fn from_sorted_iter<I: Iterator<Item = (K, V)>>(&mut self, iter: I) {
1046         self.ensure_root_is_owned();
1047         let mut cur_node = last_leaf_edge(self.root.as_mut()).into_node();
1048         // Iterate through all key-value pairs, pushing them into nodes at the right level.
1049         for (key, value) in iter {
1050             // Try to push key-value pair into the current leaf node.
1051             if cur_node.len() < node::CAPACITY {
1052                 cur_node.push(key, value);
1053             } else {
1054                 // No space left, go up and push there.
1055                 let mut open_node;
1056                 let mut test_node = cur_node.forget_type();
1057                 loop {
1058                     match test_node.ascend() {
1059                         Ok(parent) => {
1060                             let parent = parent.into_node();
1061                             if parent.len() < node::CAPACITY {
1062                                 // Found a node with space left, push here.
1063                                 open_node = parent;
1064                                 break;
1065                             } else {
1066                                 // Go up again.
1067                                 test_node = parent.forget_type();
1068                             }
1069                         }
1070                         Err(node) => {
1071                             // We are at the top, create a new root node and push there.
1072                             open_node = node.into_root_mut().push_level();
1073                             break;
1074                         }
1075                     }
1076                 }
1077
1078                 // Push key-value pair and new right subtree.
1079                 let tree_height = open_node.height() - 1;
1080                 let mut right_tree = node::Root::new_leaf();
1081                 for _ in 0..tree_height {
1082                     right_tree.push_level();
1083                 }
1084                 open_node.push(key, value, right_tree);
1085
1086                 // Go down to the right-most leaf again.
1087                 cur_node = last_leaf_edge(open_node.forget_type()).into_node();
1088             }
1089
1090             self.length += 1;
1091         }
1092     }
1093
1094     fn fix_right_edge(&mut self) {
1095         // Handle underfull nodes, start from the top.
1096         let mut cur_node = self.root.as_mut();
1097         while let Internal(internal) = cur_node.force() {
1098             // Check if right-most child is underfull.
1099             let mut last_edge = internal.last_edge();
1100             let right_child_len = last_edge.reborrow().descend().len();
1101             if right_child_len < node::MIN_LEN {
1102                 // We need to steal.
1103                 let mut last_kv = match last_edge.left_kv() {
1104                     Ok(left) => left,
1105                     Err(_) => unreachable!(),
1106                 };
1107                 last_kv.bulk_steal_left(node::MIN_LEN - right_child_len);
1108                 last_edge = last_kv.right_edge();
1109             }
1110
1111             // Go further down.
1112             cur_node = last_edge.descend();
1113         }
1114     }
1115
1116     /// Splits the collection into two at the given key. Returns everything after the given key,
1117     /// including the key.
1118     ///
1119     /// # Examples
1120     ///
1121     /// Basic usage:
1122     ///
1123     /// ```
1124     /// use std::collections::BTreeMap;
1125     ///
1126     /// let mut a = BTreeMap::new();
1127     /// a.insert(1, "a");
1128     /// a.insert(2, "b");
1129     /// a.insert(3, "c");
1130     /// a.insert(17, "d");
1131     /// a.insert(41, "e");
1132     ///
1133     /// let b = a.split_off(&3);
1134     ///
1135     /// assert_eq!(a.len(), 2);
1136     /// assert_eq!(b.len(), 3);
1137     ///
1138     /// assert_eq!(a[&1], "a");
1139     /// assert_eq!(a[&2], "b");
1140     ///
1141     /// assert_eq!(b[&3], "c");
1142     /// assert_eq!(b[&17], "d");
1143     /// assert_eq!(b[&41], "e");
1144     /// ```
1145     #[stable(feature = "btree_split_off", since = "1.11.0")]
1146     pub fn split_off<Q: ?Sized + Ord>(&mut self, key: &Q) -> Self
1147     where
1148         K: Borrow<Q>,
1149     {
1150         if self.is_empty() {
1151             return Self::new();
1152         }
1153
1154         let total_num = self.len();
1155
1156         let mut right = Self::new();
1157         right.root = node::Root::new_leaf();
1158         for _ in 0..(self.root.as_ref().height()) {
1159             right.root.push_level();
1160         }
1161
1162         {
1163             let mut left_node = self.root.as_mut();
1164             let mut right_node = right.root.as_mut();
1165
1166             loop {
1167                 let mut split_edge = match search::search_node(left_node, key) {
1168                     // key is going to the right tree
1169                     Found(handle) => handle.left_edge(),
1170                     GoDown(handle) => handle,
1171                 };
1172
1173                 split_edge.move_suffix(&mut right_node);
1174
1175                 match (split_edge.force(), right_node.force()) {
1176                     (Internal(edge), Internal(node)) => {
1177                         left_node = edge.descend();
1178                         right_node = node.first_edge().descend();
1179                     }
1180                     (Leaf(_), Leaf(_)) => {
1181                         break;
1182                     }
1183                     _ => {
1184                         unreachable!();
1185                     }
1186                 }
1187             }
1188         }
1189
1190         self.fix_right_border();
1191         right.fix_left_border();
1192
1193         if self.root.as_ref().height() < right.root.as_ref().height() {
1194             self.recalc_length();
1195             right.length = total_num - self.len();
1196         } else {
1197             right.recalc_length();
1198             self.length = total_num - right.len();
1199         }
1200
1201         right
1202     }
1203
1204     /// Calculates the number of elements if it is incorrect.
1205     fn recalc_length(&mut self) {
1206         fn dfs<'a, K, V>(node: NodeRef<marker::Immut<'a>, K, V, marker::LeafOrInternal>) -> usize
1207         where
1208             K: 'a,
1209             V: 'a,
1210         {
1211             let mut res = node.len();
1212
1213             if let Internal(node) = node.force() {
1214                 let mut edge = node.first_edge();
1215                 loop {
1216                     res += dfs(edge.reborrow().descend());
1217                     match edge.right_kv() {
1218                         Ok(right_kv) => {
1219                             edge = right_kv.right_edge();
1220                         }
1221                         Err(_) => {
1222                             break;
1223                         }
1224                     }
1225                 }
1226             }
1227
1228             res
1229         }
1230
1231         self.length = dfs(self.root.as_ref());
1232     }
1233
1234     /// Removes empty levels on the top.
1235     fn fix_top(&mut self) {
1236         loop {
1237             {
1238                 let node = self.root.as_ref();
1239                 if node.height() == 0 || node.len() > 0 {
1240                     break;
1241                 }
1242             }
1243             self.root.pop_level();
1244         }
1245     }
1246
1247     fn fix_right_border(&mut self) {
1248         self.fix_top();
1249
1250         {
1251             let mut cur_node = self.root.as_mut();
1252
1253             while let Internal(node) = cur_node.force() {
1254                 let mut last_kv = node.last_kv();
1255
1256                 if last_kv.can_merge() {
1257                     cur_node = last_kv.merge().descend();
1258                 } else {
1259                     let right_len = last_kv.reborrow().right_edge().descend().len();
1260                     // `MINLEN + 1` to avoid readjust if merge happens on the next level.
1261                     if right_len < node::MIN_LEN + 1 {
1262                         last_kv.bulk_steal_left(node::MIN_LEN + 1 - right_len);
1263                     }
1264                     cur_node = last_kv.right_edge().descend();
1265                 }
1266             }
1267         }
1268
1269         self.fix_top();
1270     }
1271
1272     /// The symmetric clone of `fix_right_border`.
1273     fn fix_left_border(&mut self) {
1274         self.fix_top();
1275
1276         {
1277             let mut cur_node = self.root.as_mut();
1278
1279             while let Internal(node) = cur_node.force() {
1280                 let mut first_kv = node.first_kv();
1281
1282                 if first_kv.can_merge() {
1283                     cur_node = first_kv.merge().descend();
1284                 } else {
1285                     let left_len = first_kv.reborrow().left_edge().descend().len();
1286                     if left_len < node::MIN_LEN + 1 {
1287                         first_kv.bulk_steal_right(node::MIN_LEN + 1 - left_len);
1288                     }
1289                     cur_node = first_kv.left_edge().descend();
1290                 }
1291             }
1292         }
1293
1294         self.fix_top();
1295     }
1296
1297     /// If the root node is the shared root node, allocate our own node.
1298     fn ensure_root_is_owned(&mut self) {
1299         if self.root.is_shared_root() {
1300             self.root = node::Root::new_leaf();
1301         }
1302     }
1303 }
1304
1305 #[stable(feature = "rust1", since = "1.0.0")]
1306 impl<'a, K: 'a, V: 'a> IntoIterator for &'a BTreeMap<K, V> {
1307     type Item = (&'a K, &'a V);
1308     type IntoIter = Iter<'a, K, V>;
1309
1310     fn into_iter(self) -> Iter<'a, K, V> {
1311         self.iter()
1312     }
1313 }
1314
1315 #[stable(feature = "rust1", since = "1.0.0")]
1316 impl<'a, K: 'a, V: 'a> Iterator for Iter<'a, K, V> {
1317     type Item = (&'a K, &'a V);
1318
1319     fn next(&mut self) -> Option<(&'a K, &'a V)> {
1320         if self.length == 0 {
1321             None
1322         } else {
1323             self.length -= 1;
1324             unsafe { Some(self.range.next_unchecked()) }
1325         }
1326     }
1327
1328     fn size_hint(&self) -> (usize, Option<usize>) {
1329         (self.length, Some(self.length))
1330     }
1331
1332     fn last(mut self) -> Option<(&'a K, &'a V)> {
1333         self.next_back()
1334     }
1335 }
1336
1337 #[stable(feature = "fused", since = "1.26.0")]
1338 impl<K, V> FusedIterator for Iter<'_, K, V> {}
1339
1340 #[stable(feature = "rust1", since = "1.0.0")]
1341 impl<'a, K: 'a, V: 'a> DoubleEndedIterator for Iter<'a, K, V> {
1342     fn next_back(&mut self) -> Option<(&'a K, &'a V)> {
1343         if self.length == 0 {
1344             None
1345         } else {
1346             self.length -= 1;
1347             unsafe { Some(self.range.next_back_unchecked()) }
1348         }
1349     }
1350 }
1351
1352 #[stable(feature = "rust1", since = "1.0.0")]
1353 impl<K, V> ExactSizeIterator for Iter<'_, K, V> {
1354     fn len(&self) -> usize {
1355         self.length
1356     }
1357 }
1358
1359 #[stable(feature = "rust1", since = "1.0.0")]
1360 impl<K, V> Clone for Iter<'_, K, V> {
1361     fn clone(&self) -> Self {
1362         Iter { range: self.range.clone(), length: self.length }
1363     }
1364 }
1365
1366 #[stable(feature = "rust1", since = "1.0.0")]
1367 impl<'a, K: 'a, V: 'a> IntoIterator for &'a mut BTreeMap<K, V> {
1368     type Item = (&'a K, &'a mut V);
1369     type IntoIter = IterMut<'a, K, V>;
1370
1371     fn into_iter(self) -> IterMut<'a, K, V> {
1372         self.iter_mut()
1373     }
1374 }
1375
1376 #[stable(feature = "rust1", since = "1.0.0")]
1377 impl<'a, K: 'a, V: 'a> Iterator for IterMut<'a, K, V> {
1378     type Item = (&'a K, &'a mut V);
1379
1380     fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
1381         if self.length == 0 {
1382             None
1383         } else {
1384             self.length -= 1;
1385             unsafe {
1386                 let (k, v) = self.range.next_unchecked();
1387                 Some((k, v)) // coerce k from `&mut K` to `&K`
1388             }
1389         }
1390     }
1391
1392     fn size_hint(&self) -> (usize, Option<usize>) {
1393         (self.length, Some(self.length))
1394     }
1395
1396     fn last(mut self) -> Option<(&'a K, &'a mut V)> {
1397         self.next_back()
1398     }
1399 }
1400
1401 #[stable(feature = "rust1", since = "1.0.0")]
1402 impl<'a, K: 'a, V: 'a> DoubleEndedIterator for IterMut<'a, K, V> {
1403     fn next_back(&mut self) -> Option<(&'a K, &'a mut V)> {
1404         if self.length == 0 {
1405             None
1406         } else {
1407             self.length -= 1;
1408             unsafe { Some(self.range.next_back_unchecked()) }
1409         }
1410     }
1411 }
1412
1413 #[stable(feature = "rust1", since = "1.0.0")]
1414 impl<K, V> ExactSizeIterator for IterMut<'_, K, V> {
1415     fn len(&self) -> usize {
1416         self.length
1417     }
1418 }
1419
1420 #[stable(feature = "fused", since = "1.26.0")]
1421 impl<K, V> FusedIterator for IterMut<'_, K, V> {}
1422
1423 #[stable(feature = "rust1", since = "1.0.0")]
1424 impl<K, V> IntoIterator for BTreeMap<K, V> {
1425     type Item = (K, V);
1426     type IntoIter = IntoIter<K, V>;
1427
1428     fn into_iter(self) -> IntoIter<K, V> {
1429         let root1 = unsafe { ptr::read(&self.root).into_ref() };
1430         let root2 = unsafe { ptr::read(&self.root).into_ref() };
1431         let len = self.length;
1432         mem::forget(self);
1433
1434         IntoIter { front: first_leaf_edge(root1), back: last_leaf_edge(root2), length: len }
1435     }
1436 }
1437
1438 #[stable(feature = "btree_drop", since = "1.7.0")]
1439 impl<K, V> Drop for IntoIter<K, V> {
1440     fn drop(&mut self) {
1441         self.for_each(drop);
1442         unsafe {
1443             let leaf_node = ptr::read(&self.front).into_node();
1444             if leaf_node.is_shared_root() {
1445                 return;
1446             }
1447
1448             if let Some(first_parent) = leaf_node.deallocate_and_ascend() {
1449                 let mut cur_node = first_parent.into_node();
1450                 while let Some(parent) = cur_node.deallocate_and_ascend() {
1451                     cur_node = parent.into_node()
1452                 }
1453             }
1454         }
1455     }
1456 }
1457
1458 #[stable(feature = "rust1", since = "1.0.0")]
1459 impl<K, V> Iterator for IntoIter<K, V> {
1460     type Item = (K, V);
1461
1462     fn next(&mut self) -> Option<(K, V)> {
1463         if self.length == 0 {
1464             return None;
1465         } else {
1466             self.length -= 1;
1467         }
1468
1469         let handle = unsafe { ptr::read(&self.front) };
1470
1471         let mut cur_handle = match handle.right_kv() {
1472             Ok(kv) => {
1473                 let k = unsafe { ptr::read(kv.reborrow().into_kv().0) };
1474                 let v = unsafe { ptr::read(kv.reborrow().into_kv().1) };
1475                 self.front = kv.right_edge();
1476                 return Some((k, v));
1477             }
1478             Err(last_edge) => unsafe {
1479                 unwrap_unchecked(last_edge.into_node().deallocate_and_ascend())
1480             },
1481         };
1482
1483         loop {
1484             match cur_handle.right_kv() {
1485                 Ok(kv) => {
1486                     let k = unsafe { ptr::read(kv.reborrow().into_kv().0) };
1487                     let v = unsafe { ptr::read(kv.reborrow().into_kv().1) };
1488                     self.front = first_leaf_edge(kv.right_edge().descend());
1489                     return Some((k, v));
1490                 }
1491                 Err(last_edge) => unsafe {
1492                     cur_handle = unwrap_unchecked(last_edge.into_node().deallocate_and_ascend());
1493                 },
1494             }
1495         }
1496     }
1497
1498     fn size_hint(&self) -> (usize, Option<usize>) {
1499         (self.length, Some(self.length))
1500     }
1501 }
1502
1503 #[stable(feature = "rust1", since = "1.0.0")]
1504 impl<K, V> DoubleEndedIterator for IntoIter<K, V> {
1505     fn next_back(&mut self) -> Option<(K, V)> {
1506         if self.length == 0 {
1507             return None;
1508         } else {
1509             self.length -= 1;
1510         }
1511
1512         let handle = unsafe { ptr::read(&self.back) };
1513
1514         let mut cur_handle = match handle.left_kv() {
1515             Ok(kv) => {
1516                 let k = unsafe { ptr::read(kv.reborrow().into_kv().0) };
1517                 let v = unsafe { ptr::read(kv.reborrow().into_kv().1) };
1518                 self.back = kv.left_edge();
1519                 return Some((k, v));
1520             }
1521             Err(last_edge) => unsafe {
1522                 unwrap_unchecked(last_edge.into_node().deallocate_and_ascend())
1523             },
1524         };
1525
1526         loop {
1527             match cur_handle.left_kv() {
1528                 Ok(kv) => {
1529                     let k = unsafe { ptr::read(kv.reborrow().into_kv().0) };
1530                     let v = unsafe { ptr::read(kv.reborrow().into_kv().1) };
1531                     self.back = last_leaf_edge(kv.left_edge().descend());
1532                     return Some((k, v));
1533                 }
1534                 Err(last_edge) => unsafe {
1535                     cur_handle = unwrap_unchecked(last_edge.into_node().deallocate_and_ascend());
1536                 },
1537             }
1538         }
1539     }
1540 }
1541
1542 #[stable(feature = "rust1", since = "1.0.0")]
1543 impl<K, V> ExactSizeIterator for IntoIter<K, V> {
1544     fn len(&self) -> usize {
1545         self.length
1546     }
1547 }
1548
1549 #[stable(feature = "fused", since = "1.26.0")]
1550 impl<K, V> FusedIterator for IntoIter<K, V> {}
1551
1552 #[stable(feature = "rust1", since = "1.0.0")]
1553 impl<'a, K, V> Iterator for Keys<'a, K, V> {
1554     type Item = &'a K;
1555
1556     fn next(&mut self) -> Option<&'a K> {
1557         self.inner.next().map(|(k, _)| k)
1558     }
1559
1560     fn size_hint(&self) -> (usize, Option<usize>) {
1561         self.inner.size_hint()
1562     }
1563
1564     fn last(mut self) -> Option<&'a K> {
1565         self.next_back()
1566     }
1567 }
1568
1569 #[stable(feature = "rust1", since = "1.0.0")]
1570 impl<'a, K, V> DoubleEndedIterator for Keys<'a, K, V> {
1571     fn next_back(&mut self) -> Option<&'a K> {
1572         self.inner.next_back().map(|(k, _)| k)
1573     }
1574 }
1575
1576 #[stable(feature = "rust1", since = "1.0.0")]
1577 impl<K, V> ExactSizeIterator for Keys<'_, K, V> {
1578     fn len(&self) -> usize {
1579         self.inner.len()
1580     }
1581 }
1582
1583 #[stable(feature = "fused", since = "1.26.0")]
1584 impl<K, V> FusedIterator for Keys<'_, K, V> {}
1585
1586 #[stable(feature = "rust1", since = "1.0.0")]
1587 impl<K, V> Clone for Keys<'_, K, V> {
1588     fn clone(&self) -> Self {
1589         Keys { inner: self.inner.clone() }
1590     }
1591 }
1592
1593 #[stable(feature = "rust1", since = "1.0.0")]
1594 impl<'a, K, V> Iterator for Values<'a, K, V> {
1595     type Item = &'a V;
1596
1597     fn next(&mut self) -> Option<&'a V> {
1598         self.inner.next().map(|(_, v)| v)
1599     }
1600
1601     fn size_hint(&self) -> (usize, Option<usize>) {
1602         self.inner.size_hint()
1603     }
1604
1605     fn last(mut self) -> Option<&'a V> {
1606         self.next_back()
1607     }
1608 }
1609
1610 #[stable(feature = "rust1", since = "1.0.0")]
1611 impl<'a, K, V> DoubleEndedIterator for Values<'a, K, V> {
1612     fn next_back(&mut self) -> Option<&'a V> {
1613         self.inner.next_back().map(|(_, v)| v)
1614     }
1615 }
1616
1617 #[stable(feature = "rust1", since = "1.0.0")]
1618 impl<K, V> ExactSizeIterator for Values<'_, K, V> {
1619     fn len(&self) -> usize {
1620         self.inner.len()
1621     }
1622 }
1623
1624 #[stable(feature = "fused", since = "1.26.0")]
1625 impl<K, V> FusedIterator for Values<'_, K, V> {}
1626
1627 #[stable(feature = "rust1", since = "1.0.0")]
1628 impl<K, V> Clone for Values<'_, K, V> {
1629     fn clone(&self) -> Self {
1630         Values { inner: self.inner.clone() }
1631     }
1632 }
1633
1634 #[stable(feature = "btree_range", since = "1.17.0")]
1635 impl<'a, K, V> Iterator for Range<'a, K, V> {
1636     type Item = (&'a K, &'a V);
1637
1638     fn next(&mut self) -> Option<(&'a K, &'a V)> {
1639         if self.front == self.back { None } else { unsafe { Some(self.next_unchecked()) } }
1640     }
1641
1642     fn last(mut self) -> Option<(&'a K, &'a V)> {
1643         self.next_back()
1644     }
1645 }
1646
1647 #[stable(feature = "map_values_mut", since = "1.10.0")]
1648 impl<'a, K, V> Iterator for ValuesMut<'a, K, V> {
1649     type Item = &'a mut V;
1650
1651     fn next(&mut self) -> Option<&'a mut V> {
1652         self.inner.next().map(|(_, v)| v)
1653     }
1654
1655     fn size_hint(&self) -> (usize, Option<usize>) {
1656         self.inner.size_hint()
1657     }
1658
1659     fn last(mut self) -> Option<&'a mut V> {
1660         self.next_back()
1661     }
1662 }
1663
1664 #[stable(feature = "map_values_mut", since = "1.10.0")]
1665 impl<'a, K, V> DoubleEndedIterator for ValuesMut<'a, K, V> {
1666     fn next_back(&mut self) -> Option<&'a mut V> {
1667         self.inner.next_back().map(|(_, v)| v)
1668     }
1669 }
1670
1671 #[stable(feature = "map_values_mut", since = "1.10.0")]
1672 impl<K, V> ExactSizeIterator for ValuesMut<'_, K, V> {
1673     fn len(&self) -> usize {
1674         self.inner.len()
1675     }
1676 }
1677
1678 #[stable(feature = "fused", since = "1.26.0")]
1679 impl<K, V> FusedIterator for ValuesMut<'_, K, V> {}
1680
1681 impl<'a, K, V> Range<'a, K, V> {
1682     unsafe fn next_unchecked(&mut self) -> (&'a K, &'a V) {
1683         let handle = self.front;
1684
1685         let mut cur_handle = match handle.right_kv() {
1686             Ok(kv) => {
1687                 let ret = kv.into_kv();
1688                 self.front = kv.right_edge();
1689                 return ret;
1690             }
1691             Err(last_edge) => {
1692                 let next_level = last_edge.into_node().ascend().ok();
1693                 unwrap_unchecked(next_level)
1694             }
1695         };
1696
1697         loop {
1698             match cur_handle.right_kv() {
1699                 Ok(kv) => {
1700                     let ret = kv.into_kv();
1701                     self.front = first_leaf_edge(kv.right_edge().descend());
1702                     return ret;
1703                 }
1704                 Err(last_edge) => {
1705                     let next_level = last_edge.into_node().ascend().ok();
1706                     cur_handle = unwrap_unchecked(next_level);
1707                 }
1708             }
1709         }
1710     }
1711 }
1712
1713 #[stable(feature = "btree_range", since = "1.17.0")]
1714 impl<'a, K, V> DoubleEndedIterator for Range<'a, K, V> {
1715     fn next_back(&mut self) -> Option<(&'a K, &'a V)> {
1716         if self.front == self.back { None } else { unsafe { Some(self.next_back_unchecked()) } }
1717     }
1718 }
1719
1720 impl<'a, K, V> Range<'a, K, V> {
1721     unsafe fn next_back_unchecked(&mut self) -> (&'a K, &'a V) {
1722         let handle = self.back;
1723
1724         let mut cur_handle = match handle.left_kv() {
1725             Ok(kv) => {
1726                 let ret = kv.into_kv();
1727                 self.back = kv.left_edge();
1728                 return ret;
1729             }
1730             Err(last_edge) => {
1731                 let next_level = last_edge.into_node().ascend().ok();
1732                 unwrap_unchecked(next_level)
1733             }
1734         };
1735
1736         loop {
1737             match cur_handle.left_kv() {
1738                 Ok(kv) => {
1739                     let ret = kv.into_kv();
1740                     self.back = last_leaf_edge(kv.left_edge().descend());
1741                     return ret;
1742                 }
1743                 Err(last_edge) => {
1744                     let next_level = last_edge.into_node().ascend().ok();
1745                     cur_handle = unwrap_unchecked(next_level);
1746                 }
1747             }
1748         }
1749     }
1750 }
1751
1752 #[stable(feature = "fused", since = "1.26.0")]
1753 impl<K, V> FusedIterator for Range<'_, K, V> {}
1754
1755 #[stable(feature = "btree_range", since = "1.17.0")]
1756 impl<K, V> Clone for Range<'_, K, V> {
1757     fn clone(&self) -> Self {
1758         Range { front: self.front, back: self.back }
1759     }
1760 }
1761
1762 #[stable(feature = "btree_range", since = "1.17.0")]
1763 impl<'a, K, V> Iterator for RangeMut<'a, K, V> {
1764     type Item = (&'a K, &'a mut V);
1765
1766     fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
1767         if self.front == self.back {
1768             None
1769         } else {
1770             unsafe {
1771                 let (k, v) = self.next_unchecked();
1772                 Some((k, v)) // coerce k from `&mut K` to `&K`
1773             }
1774         }
1775     }
1776
1777     fn last(mut self) -> Option<(&'a K, &'a mut V)> {
1778         self.next_back()
1779     }
1780 }
1781
1782 impl<'a, K, V> RangeMut<'a, K, V> {
1783     unsafe fn next_unchecked(&mut self) -> (&'a mut K, &'a mut V) {
1784         let handle = ptr::read(&self.front);
1785
1786         let mut cur_handle = match handle.right_kv() {
1787             Ok(kv) => {
1788                 self.front = ptr::read(&kv).right_edge();
1789                 // Doing the descend invalidates the references returned by `into_kv_mut`,
1790                 // so we have to do this last.
1791                 return kv.into_kv_mut();
1792             }
1793             Err(last_edge) => {
1794                 let next_level = last_edge.into_node().ascend().ok();
1795                 unwrap_unchecked(next_level)
1796             }
1797         };
1798
1799         loop {
1800             match cur_handle.right_kv() {
1801                 Ok(kv) => {
1802                     self.front = first_leaf_edge(ptr::read(&kv).right_edge().descend());
1803                     // Doing the descend invalidates the references returned by `into_kv_mut`,
1804                     // so we have to do this last.
1805                     return kv.into_kv_mut();
1806                 }
1807                 Err(last_edge) => {
1808                     let next_level = last_edge.into_node().ascend().ok();
1809                     cur_handle = unwrap_unchecked(next_level);
1810                 }
1811             }
1812         }
1813     }
1814 }
1815
1816 #[stable(feature = "btree_range", since = "1.17.0")]
1817 impl<'a, K, V> DoubleEndedIterator for RangeMut<'a, K, V> {
1818     fn next_back(&mut self) -> Option<(&'a K, &'a mut V)> {
1819         if self.front == self.back { None } else { unsafe { Some(self.next_back_unchecked()) } }
1820     }
1821 }
1822
1823 #[stable(feature = "fused", since = "1.26.0")]
1824 impl<K, V> FusedIterator for RangeMut<'_, K, V> {}
1825
1826 impl<'a, K, V> RangeMut<'a, K, V> {
1827     unsafe fn next_back_unchecked(&mut self) -> (&'a K, &'a mut V) {
1828         let handle = ptr::read(&self.back);
1829
1830         let mut cur_handle = match handle.left_kv() {
1831             Ok(kv) => {
1832                 self.back = ptr::read(&kv).left_edge();
1833                 // Doing the descend invalidates the references returned by `into_kv_mut`,
1834                 // so we have to do this last.
1835                 let (k, v) = kv.into_kv_mut();
1836                 return (k, v); // coerce k from `&mut K` to `&K`
1837             }
1838             Err(last_edge) => {
1839                 let next_level = last_edge.into_node().ascend().ok();
1840                 unwrap_unchecked(next_level)
1841             }
1842         };
1843
1844         loop {
1845             match cur_handle.left_kv() {
1846                 Ok(kv) => {
1847                     self.back = last_leaf_edge(ptr::read(&kv).left_edge().descend());
1848                     // Doing the descend invalidates the references returned by `into_kv_mut`,
1849                     // so we have to do this last.
1850                     let (k, v) = kv.into_kv_mut();
1851                     return (k, v); // coerce k from `&mut K` to `&K`
1852                 }
1853                 Err(last_edge) => {
1854                     let next_level = last_edge.into_node().ascend().ok();
1855                     cur_handle = unwrap_unchecked(next_level);
1856                 }
1857             }
1858         }
1859     }
1860 }
1861
1862 #[stable(feature = "rust1", since = "1.0.0")]
1863 impl<K: Ord, V> FromIterator<(K, V)> for BTreeMap<K, V> {
1864     fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> BTreeMap<K, V> {
1865         let mut map = BTreeMap::new();
1866         map.extend(iter);
1867         map
1868     }
1869 }
1870
1871 #[stable(feature = "rust1", since = "1.0.0")]
1872 impl<K: Ord, V> Extend<(K, V)> for BTreeMap<K, V> {
1873     #[inline]
1874     fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) {
1875         iter.into_iter().for_each(move |(k, v)| {
1876             self.insert(k, v);
1877         });
1878     }
1879 }
1880
1881 #[stable(feature = "extend_ref", since = "1.2.0")]
1882 impl<'a, K: Ord + Copy, V: Copy> Extend<(&'a K, &'a V)> for BTreeMap<K, V> {
1883     fn extend<I: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: I) {
1884         self.extend(iter.into_iter().map(|(&key, &value)| (key, value)));
1885     }
1886 }
1887
1888 #[stable(feature = "rust1", since = "1.0.0")]
1889 impl<K: Hash, V: Hash> Hash for BTreeMap<K, V> {
1890     fn hash<H: Hasher>(&self, state: &mut H) {
1891         for elt in self {
1892             elt.hash(state);
1893         }
1894     }
1895 }
1896
1897 #[stable(feature = "rust1", since = "1.0.0")]
1898 impl<K: Ord, V> Default for BTreeMap<K, V> {
1899     /// Creates an empty `BTreeMap<K, V>`.
1900     fn default() -> BTreeMap<K, V> {
1901         BTreeMap::new()
1902     }
1903 }
1904
1905 #[stable(feature = "rust1", since = "1.0.0")]
1906 impl<K: PartialEq, V: PartialEq> PartialEq for BTreeMap<K, V> {
1907     fn eq(&self, other: &BTreeMap<K, V>) -> bool {
1908         self.len() == other.len() && self.iter().zip(other).all(|(a, b)| a == b)
1909     }
1910 }
1911
1912 #[stable(feature = "rust1", since = "1.0.0")]
1913 impl<K: Eq, V: Eq> Eq for BTreeMap<K, V> {}
1914
1915 #[stable(feature = "rust1", since = "1.0.0")]
1916 impl<K: PartialOrd, V: PartialOrd> PartialOrd for BTreeMap<K, V> {
1917     #[inline]
1918     fn partial_cmp(&self, other: &BTreeMap<K, V>) -> Option<Ordering> {
1919         self.iter().partial_cmp(other.iter())
1920     }
1921 }
1922
1923 #[stable(feature = "rust1", since = "1.0.0")]
1924 impl<K: Ord, V: Ord> Ord for BTreeMap<K, V> {
1925     #[inline]
1926     fn cmp(&self, other: &BTreeMap<K, V>) -> Ordering {
1927         self.iter().cmp(other.iter())
1928     }
1929 }
1930
1931 #[stable(feature = "rust1", since = "1.0.0")]
1932 impl<K: Debug, V: Debug> Debug for BTreeMap<K, V> {
1933     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1934         f.debug_map().entries(self.iter()).finish()
1935     }
1936 }
1937
1938 #[stable(feature = "rust1", since = "1.0.0")]
1939 impl<K: Ord, Q: ?Sized, V> Index<&Q> for BTreeMap<K, V>
1940 where
1941     K: Borrow<Q>,
1942     Q: Ord,
1943 {
1944     type Output = V;
1945
1946     /// Returns a reference to the value corresponding to the supplied key.
1947     ///
1948     /// # Panics
1949     ///
1950     /// Panics if the key is not present in the `BTreeMap`.
1951     #[inline]
1952     fn index(&self, key: &Q) -> &V {
1953         self.get(key).expect("no entry found for key")
1954     }
1955 }
1956
1957 fn first_leaf_edge<BorrowType, K, V>(
1958     mut node: NodeRef<BorrowType, K, V, marker::LeafOrInternal>,
1959 ) -> Handle<NodeRef<BorrowType, K, V, marker::Leaf>, marker::Edge> {
1960     loop {
1961         match node.force() {
1962             Leaf(leaf) => return leaf.first_edge(),
1963             Internal(internal) => {
1964                 node = internal.first_edge().descend();
1965             }
1966         }
1967     }
1968 }
1969
1970 fn last_leaf_edge<BorrowType, K, V>(
1971     mut node: NodeRef<BorrowType, K, V, marker::LeafOrInternal>,
1972 ) -> Handle<NodeRef<BorrowType, K, V, marker::Leaf>, marker::Edge> {
1973     loop {
1974         match node.force() {
1975             Leaf(leaf) => return leaf.last_edge(),
1976             Internal(internal) => {
1977                 node = internal.last_edge().descend();
1978             }
1979         }
1980     }
1981 }
1982
1983 fn range_search<BorrowType, K, V, Q: ?Sized, R: RangeBounds<Q>>(
1984     root1: NodeRef<BorrowType, K, V, marker::LeafOrInternal>,
1985     root2: NodeRef<BorrowType, K, V, marker::LeafOrInternal>,
1986     range: R,
1987 ) -> (
1988     Handle<NodeRef<BorrowType, K, V, marker::Leaf>, marker::Edge>,
1989     Handle<NodeRef<BorrowType, K, V, marker::Leaf>, marker::Edge>,
1990 )
1991 where
1992     Q: Ord,
1993     K: Borrow<Q>,
1994 {
1995     match (range.start_bound(), range.end_bound()) {
1996         (Excluded(s), Excluded(e)) if s == e => {
1997             panic!("range start and end are equal and excluded in BTreeMap")
1998         }
1999         (Included(s), Included(e))
2000         | (Included(s), Excluded(e))
2001         | (Excluded(s), Included(e))
2002         | (Excluded(s), Excluded(e))
2003             if s > e =>
2004         {
2005             panic!("range start is greater than range end in BTreeMap")
2006         }
2007         _ => {}
2008     };
2009
2010     let mut min_node = root1;
2011     let mut max_node = root2;
2012     let mut min_found = false;
2013     let mut max_found = false;
2014     let mut diverged = false;
2015
2016     loop {
2017         let min_edge = match (min_found, range.start_bound()) {
2018             (false, Included(key)) => match search::search_linear(&min_node, key) {
2019                 (i, true) => {
2020                     min_found = true;
2021                     i
2022                 }
2023                 (i, false) => i,
2024             },
2025             (false, Excluded(key)) => match search::search_linear(&min_node, key) {
2026                 (i, true) => {
2027                     min_found = true;
2028                     i + 1
2029                 }
2030                 (i, false) => i,
2031             },
2032             (_, Unbounded) => 0,
2033             (true, Included(_)) => min_node.keys().len(),
2034             (true, Excluded(_)) => 0,
2035         };
2036
2037         let max_edge = match (max_found, range.end_bound()) {
2038             (false, Included(key)) => match search::search_linear(&max_node, key) {
2039                 (i, true) => {
2040                     max_found = true;
2041                     i + 1
2042                 }
2043                 (i, false) => i,
2044             },
2045             (false, Excluded(key)) => match search::search_linear(&max_node, key) {
2046                 (i, true) => {
2047                     max_found = true;
2048                     i
2049                 }
2050                 (i, false) => i,
2051             },
2052             (_, Unbounded) => max_node.keys().len(),
2053             (true, Included(_)) => 0,
2054             (true, Excluded(_)) => max_node.keys().len(),
2055         };
2056
2057         if !diverged {
2058             if max_edge < min_edge {
2059                 panic!("Ord is ill-defined in BTreeMap range")
2060             }
2061             if min_edge != max_edge {
2062                 diverged = true;
2063             }
2064         }
2065
2066         let front = Handle::new_edge(min_node, min_edge);
2067         let back = Handle::new_edge(max_node, max_edge);
2068         match (front.force(), back.force()) {
2069             (Leaf(f), Leaf(b)) => {
2070                 return (f, b);
2071             }
2072             (Internal(min_int), Internal(max_int)) => {
2073                 min_node = min_int.descend();
2074                 max_node = max_int.descend();
2075             }
2076             _ => unreachable!("BTreeMap has different depths"),
2077         };
2078     }
2079 }
2080
2081 #[inline(always)]
2082 unsafe fn unwrap_unchecked<T>(val: Option<T>) -> T {
2083     val.unwrap_or_else(|| {
2084         if cfg!(debug_assertions) {
2085             panic!("'unchecked' unwrap on None in BTreeMap");
2086         } else {
2087             intrinsics::unreachable();
2088         }
2089     })
2090 }
2091
2092 impl<K, V> BTreeMap<K, V> {
2093     /// Gets an iterator over the entries of the map, sorted by key.
2094     ///
2095     /// # Examples
2096     ///
2097     /// Basic usage:
2098     ///
2099     /// ```
2100     /// use std::collections::BTreeMap;
2101     ///
2102     /// let mut map = BTreeMap::new();
2103     /// map.insert(3, "c");
2104     /// map.insert(2, "b");
2105     /// map.insert(1, "a");
2106     ///
2107     /// for (key, value) in map.iter() {
2108     ///     println!("{}: {}", key, value);
2109     /// }
2110     ///
2111     /// let (first_key, first_value) = map.iter().next().unwrap();
2112     /// assert_eq!((*first_key, *first_value), (1, "a"));
2113     /// ```
2114     #[stable(feature = "rust1", since = "1.0.0")]
2115     pub fn iter(&self) -> Iter<'_, K, V> {
2116         Iter {
2117             range: Range {
2118                 front: first_leaf_edge(self.root.as_ref()),
2119                 back: last_leaf_edge(self.root.as_ref()),
2120             },
2121             length: self.length,
2122         }
2123     }
2124
2125     /// Gets a mutable iterator over the entries of the map, sorted by key.
2126     ///
2127     /// # Examples
2128     ///
2129     /// Basic usage:
2130     ///
2131     /// ```
2132     /// use std::collections::BTreeMap;
2133     ///
2134     /// let mut map = BTreeMap::new();
2135     /// map.insert("a", 1);
2136     /// map.insert("b", 2);
2137     /// map.insert("c", 3);
2138     ///
2139     /// // add 10 to the value if the key isn't "a"
2140     /// for (key, value) in map.iter_mut() {
2141     ///     if key != &"a" {
2142     ///         *value += 10;
2143     ///     }
2144     /// }
2145     /// ```
2146     #[stable(feature = "rust1", since = "1.0.0")]
2147     pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {
2148         let root1 = self.root.as_mut();
2149         let root2 = unsafe { ptr::read(&root1) };
2150         IterMut {
2151             range: RangeMut {
2152                 front: first_leaf_edge(root1),
2153                 back: last_leaf_edge(root2),
2154                 _marker: PhantomData,
2155             },
2156             length: self.length,
2157         }
2158     }
2159
2160     /// Gets an iterator over the keys of the map, in sorted order.
2161     ///
2162     /// # Examples
2163     ///
2164     /// Basic usage:
2165     ///
2166     /// ```
2167     /// use std::collections::BTreeMap;
2168     ///
2169     /// let mut a = BTreeMap::new();
2170     /// a.insert(2, "b");
2171     /// a.insert(1, "a");
2172     ///
2173     /// let keys: Vec<_> = a.keys().cloned().collect();
2174     /// assert_eq!(keys, [1, 2]);
2175     /// ```
2176     #[stable(feature = "rust1", since = "1.0.0")]
2177     pub fn keys(&self) -> Keys<'_, K, V> {
2178         Keys { inner: self.iter() }
2179     }
2180
2181     /// Gets an iterator over the values of the map, in order by key.
2182     ///
2183     /// # Examples
2184     ///
2185     /// Basic usage:
2186     ///
2187     /// ```
2188     /// use std::collections::BTreeMap;
2189     ///
2190     /// let mut a = BTreeMap::new();
2191     /// a.insert(1, "hello");
2192     /// a.insert(2, "goodbye");
2193     ///
2194     /// let values: Vec<&str> = a.values().cloned().collect();
2195     /// assert_eq!(values, ["hello", "goodbye"]);
2196     /// ```
2197     #[stable(feature = "rust1", since = "1.0.0")]
2198     pub fn values(&self) -> Values<'_, K, V> {
2199         Values { inner: self.iter() }
2200     }
2201
2202     /// Gets a mutable iterator over the values of the map, in order by key.
2203     ///
2204     /// # Examples
2205     ///
2206     /// Basic usage:
2207     ///
2208     /// ```
2209     /// use std::collections::BTreeMap;
2210     ///
2211     /// let mut a = BTreeMap::new();
2212     /// a.insert(1, String::from("hello"));
2213     /// a.insert(2, String::from("goodbye"));
2214     ///
2215     /// for value in a.values_mut() {
2216     ///     value.push_str("!");
2217     /// }
2218     ///
2219     /// let values: Vec<String> = a.values().cloned().collect();
2220     /// assert_eq!(values, [String::from("hello!"),
2221     ///                     String::from("goodbye!")]);
2222     /// ```
2223     #[stable(feature = "map_values_mut", since = "1.10.0")]
2224     pub fn values_mut(&mut self) -> ValuesMut<'_, K, V> {
2225         ValuesMut { inner: self.iter_mut() }
2226     }
2227
2228     /// Returns the number of elements in the map.
2229     ///
2230     /// # Examples
2231     ///
2232     /// Basic usage:
2233     ///
2234     /// ```
2235     /// use std::collections::BTreeMap;
2236     ///
2237     /// let mut a = BTreeMap::new();
2238     /// assert_eq!(a.len(), 0);
2239     /// a.insert(1, "a");
2240     /// assert_eq!(a.len(), 1);
2241     /// ```
2242     #[stable(feature = "rust1", since = "1.0.0")]
2243     pub fn len(&self) -> usize {
2244         self.length
2245     }
2246
2247     /// Returns `true` if the map contains no elements.
2248     ///
2249     /// # Examples
2250     ///
2251     /// Basic usage:
2252     ///
2253     /// ```
2254     /// use std::collections::BTreeMap;
2255     ///
2256     /// let mut a = BTreeMap::new();
2257     /// assert!(a.is_empty());
2258     /// a.insert(1, "a");
2259     /// assert!(!a.is_empty());
2260     /// ```
2261     #[stable(feature = "rust1", since = "1.0.0")]
2262     pub fn is_empty(&self) -> bool {
2263         self.len() == 0
2264     }
2265 }
2266
2267 impl<'a, K: Ord, V> Entry<'a, K, V> {
2268     /// Ensures a value is in the entry by inserting the default if empty, and returns
2269     /// a mutable reference to the value in the entry.
2270     ///
2271     /// # Examples
2272     ///
2273     /// ```
2274     /// use std::collections::BTreeMap;
2275     ///
2276     /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2277     /// map.entry("poneyland").or_insert(12);
2278     ///
2279     /// assert_eq!(map["poneyland"], 12);
2280     /// ```
2281     #[stable(feature = "rust1", since = "1.0.0")]
2282     pub fn or_insert(self, default: V) -> &'a mut V {
2283         match self {
2284             Occupied(entry) => entry.into_mut(),
2285             Vacant(entry) => entry.insert(default),
2286         }
2287     }
2288
2289     /// Ensures a value is in the entry by inserting the result of the default function if empty,
2290     /// and returns a mutable reference to the value in the entry.
2291     ///
2292     /// # Examples
2293     ///
2294     /// ```
2295     /// use std::collections::BTreeMap;
2296     ///
2297     /// let mut map: BTreeMap<&str, String> = BTreeMap::new();
2298     /// let s = "hoho".to_string();
2299     ///
2300     /// map.entry("poneyland").or_insert_with(|| s);
2301     ///
2302     /// assert_eq!(map["poneyland"], "hoho".to_string());
2303     /// ```
2304     #[stable(feature = "rust1", since = "1.0.0")]
2305     pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V {
2306         match self {
2307             Occupied(entry) => entry.into_mut(),
2308             Vacant(entry) => entry.insert(default()),
2309         }
2310     }
2311
2312     /// Returns a reference to this entry's key.
2313     ///
2314     /// # Examples
2315     ///
2316     /// ```
2317     /// use std::collections::BTreeMap;
2318     ///
2319     /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2320     /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2321     /// ```
2322     #[stable(feature = "map_entry_keys", since = "1.10.0")]
2323     pub fn key(&self) -> &K {
2324         match *self {
2325             Occupied(ref entry) => entry.key(),
2326             Vacant(ref entry) => entry.key(),
2327         }
2328     }
2329
2330     /// Provides in-place mutable access to an occupied entry before any
2331     /// potential inserts into the map.
2332     ///
2333     /// # Examples
2334     ///
2335     /// ```
2336     /// use std::collections::BTreeMap;
2337     ///
2338     /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2339     ///
2340     /// map.entry("poneyland")
2341     ///    .and_modify(|e| { *e += 1 })
2342     ///    .or_insert(42);
2343     /// assert_eq!(map["poneyland"], 42);
2344     ///
2345     /// map.entry("poneyland")
2346     ///    .and_modify(|e| { *e += 1 })
2347     ///    .or_insert(42);
2348     /// assert_eq!(map["poneyland"], 43);
2349     /// ```
2350     #[stable(feature = "entry_and_modify", since = "1.26.0")]
2351     pub fn and_modify<F>(self, f: F) -> Self
2352     where
2353         F: FnOnce(&mut V),
2354     {
2355         match self {
2356             Occupied(mut entry) => {
2357                 f(entry.get_mut());
2358                 Occupied(entry)
2359             }
2360             Vacant(entry) => Vacant(entry),
2361         }
2362     }
2363 }
2364
2365 impl<'a, K: Ord, V: Default> Entry<'a, K, V> {
2366     #[stable(feature = "entry_or_default", since = "1.28.0")]
2367     /// Ensures a value is in the entry by inserting the default value if empty,
2368     /// and returns a mutable reference to the value in the entry.
2369     ///
2370     /// # Examples
2371     ///
2372     /// ```
2373     /// use std::collections::BTreeMap;
2374     ///
2375     /// let mut map: BTreeMap<&str, Option<usize>> = BTreeMap::new();
2376     /// map.entry("poneyland").or_default();
2377     ///
2378     /// assert_eq!(map["poneyland"], None);
2379     /// ```
2380     pub fn or_default(self) -> &'a mut V {
2381         match self {
2382             Occupied(entry) => entry.into_mut(),
2383             Vacant(entry) => entry.insert(Default::default()),
2384         }
2385     }
2386 }
2387
2388 impl<'a, K: Ord, V> VacantEntry<'a, K, V> {
2389     /// Gets a reference to the key that would be used when inserting a value
2390     /// through the VacantEntry.
2391     ///
2392     /// # Examples
2393     ///
2394     /// ```
2395     /// use std::collections::BTreeMap;
2396     ///
2397     /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2398     /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2399     /// ```
2400     #[stable(feature = "map_entry_keys", since = "1.10.0")]
2401     pub fn key(&self) -> &K {
2402         &self.key
2403     }
2404
2405     /// Take ownership of the key.
2406     ///
2407     /// # Examples
2408     ///
2409     /// ```
2410     /// use std::collections::BTreeMap;
2411     /// use std::collections::btree_map::Entry;
2412     ///
2413     /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2414     ///
2415     /// if let Entry::Vacant(v) = map.entry("poneyland") {
2416     ///     v.into_key();
2417     /// }
2418     /// ```
2419     #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")]
2420     pub fn into_key(self) -> K {
2421         self.key
2422     }
2423
2424     /// Sets the value of the entry with the `VacantEntry`'s key,
2425     /// and returns a mutable reference to it.
2426     ///
2427     /// # Examples
2428     ///
2429     /// ```
2430     /// use std::collections::BTreeMap;
2431     ///
2432     /// let mut count: BTreeMap<&str, usize> = BTreeMap::new();
2433     ///
2434     /// // count the number of occurrences of letters in the vec
2435     /// for x in vec!["a","b","a","c","a","b"] {
2436     ///     *count.entry(x).or_insert(0) += 1;
2437     /// }
2438     ///
2439     /// assert_eq!(count["a"], 3);
2440     /// ```
2441     #[stable(feature = "rust1", since = "1.0.0")]
2442     pub fn insert(self, value: V) -> &'a mut V {
2443         *self.length += 1;
2444
2445         let out_ptr;
2446
2447         let mut ins_k;
2448         let mut ins_v;
2449         let mut ins_edge;
2450
2451         let mut cur_parent = match self.handle.insert(self.key, value) {
2452             (Fit(handle), _) => return handle.into_kv_mut().1,
2453             (Split(left, k, v, right), ptr) => {
2454                 ins_k = k;
2455                 ins_v = v;
2456                 ins_edge = right;
2457                 out_ptr = ptr;
2458                 left.ascend().map_err(|n| n.into_root_mut())
2459             }
2460         };
2461
2462         loop {
2463             match cur_parent {
2464                 Ok(parent) => match parent.insert(ins_k, ins_v, ins_edge) {
2465                     Fit(_) => return unsafe { &mut *out_ptr },
2466                     Split(left, k, v, right) => {
2467                         ins_k = k;
2468                         ins_v = v;
2469                         ins_edge = right;
2470                         cur_parent = left.ascend().map_err(|n| n.into_root_mut());
2471                     }
2472                 },
2473                 Err(root) => {
2474                     root.push_level().push(ins_k, ins_v, ins_edge);
2475                     return unsafe { &mut *out_ptr };
2476                 }
2477             }
2478         }
2479     }
2480 }
2481
2482 impl<'a, K: Ord, V> OccupiedEntry<'a, K, V> {
2483     /// Gets a reference to the key in the entry.
2484     ///
2485     /// # Examples
2486     ///
2487     /// ```
2488     /// use std::collections::BTreeMap;
2489     ///
2490     /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2491     /// map.entry("poneyland").or_insert(12);
2492     /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2493     /// ```
2494     #[stable(feature = "map_entry_keys", since = "1.10.0")]
2495     pub fn key(&self) -> &K {
2496         self.handle.reborrow().into_kv().0
2497     }
2498
2499     /// Take ownership of the key and value from the map.
2500     ///
2501     /// # Examples
2502     ///
2503     /// ```
2504     /// use std::collections::BTreeMap;
2505     /// use std::collections::btree_map::Entry;
2506     ///
2507     /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2508     /// map.entry("poneyland").or_insert(12);
2509     ///
2510     /// if let Entry::Occupied(o) = map.entry("poneyland") {
2511     ///     // We delete the entry from the map.
2512     ///     o.remove_entry();
2513     /// }
2514     ///
2515     /// // If now try to get the value, it will panic:
2516     /// // println!("{}", map["poneyland"]);
2517     /// ```
2518     #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")]
2519     pub fn remove_entry(self) -> (K, V) {
2520         self.remove_kv()
2521     }
2522
2523     /// Gets a reference to the value in the entry.
2524     ///
2525     /// # Examples
2526     ///
2527     /// ```
2528     /// use std::collections::BTreeMap;
2529     /// use std::collections::btree_map::Entry;
2530     ///
2531     /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2532     /// map.entry("poneyland").or_insert(12);
2533     ///
2534     /// if let Entry::Occupied(o) = map.entry("poneyland") {
2535     ///     assert_eq!(o.get(), &12);
2536     /// }
2537     /// ```
2538     #[stable(feature = "rust1", since = "1.0.0")]
2539     pub fn get(&self) -> &V {
2540         self.handle.reborrow().into_kv().1
2541     }
2542
2543     /// Gets a mutable reference to the value in the entry.
2544     ///
2545     /// If you need a reference to the `OccupiedEntry` that may outlive the
2546     /// destruction of the `Entry` value, see [`into_mut`].
2547     ///
2548     /// [`into_mut`]: #method.into_mut
2549     ///
2550     /// # Examples
2551     ///
2552     /// ```
2553     /// use std::collections::BTreeMap;
2554     /// use std::collections::btree_map::Entry;
2555     ///
2556     /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2557     /// map.entry("poneyland").or_insert(12);
2558     ///
2559     /// assert_eq!(map["poneyland"], 12);
2560     /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
2561     ///     *o.get_mut() += 10;
2562     ///     assert_eq!(*o.get(), 22);
2563     ///
2564     ///     // We can use the same Entry multiple times.
2565     ///     *o.get_mut() += 2;
2566     /// }
2567     /// assert_eq!(map["poneyland"], 24);
2568     /// ```
2569     #[stable(feature = "rust1", since = "1.0.0")]
2570     pub fn get_mut(&mut self) -> &mut V {
2571         self.handle.kv_mut().1
2572     }
2573
2574     /// Converts the entry into a mutable reference to its value.
2575     ///
2576     /// If you need multiple references to the `OccupiedEntry`, see [`get_mut`].
2577     ///
2578     /// [`get_mut`]: #method.get_mut
2579     ///
2580     /// # Examples
2581     ///
2582     /// ```
2583     /// use std::collections::BTreeMap;
2584     /// use std::collections::btree_map::Entry;
2585     ///
2586     /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2587     /// map.entry("poneyland").or_insert(12);
2588     ///
2589     /// assert_eq!(map["poneyland"], 12);
2590     /// if let Entry::Occupied(o) = map.entry("poneyland") {
2591     ///     *o.into_mut() += 10;
2592     /// }
2593     /// assert_eq!(map["poneyland"], 22);
2594     /// ```
2595     #[stable(feature = "rust1", since = "1.0.0")]
2596     pub fn into_mut(self) -> &'a mut V {
2597         self.handle.into_kv_mut().1
2598     }
2599
2600     /// Sets the value of the entry with the `OccupiedEntry`'s key,
2601     /// and returns the entry's old value.
2602     ///
2603     /// # Examples
2604     ///
2605     /// ```
2606     /// use std::collections::BTreeMap;
2607     /// use std::collections::btree_map::Entry;
2608     ///
2609     /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2610     /// map.entry("poneyland").or_insert(12);
2611     ///
2612     /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
2613     ///     assert_eq!(o.insert(15), 12);
2614     /// }
2615     /// assert_eq!(map["poneyland"], 15);
2616     /// ```
2617     #[stable(feature = "rust1", since = "1.0.0")]
2618     pub fn insert(&mut self, value: V) -> V {
2619         mem::replace(self.get_mut(), value)
2620     }
2621
2622     /// Takes the value of the entry out of the map, and returns it.
2623     ///
2624     /// # Examples
2625     ///
2626     /// ```
2627     /// use std::collections::BTreeMap;
2628     /// use std::collections::btree_map::Entry;
2629     ///
2630     /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2631     /// map.entry("poneyland").or_insert(12);
2632     ///
2633     /// if let Entry::Occupied(o) = map.entry("poneyland") {
2634     ///     assert_eq!(o.remove(), 12);
2635     /// }
2636     /// // If we try to get "poneyland"'s value, it'll panic:
2637     /// // println!("{}", map["poneyland"]);
2638     /// ```
2639     #[stable(feature = "rust1", since = "1.0.0")]
2640     pub fn remove(self) -> V {
2641         self.remove_kv().1
2642     }
2643
2644     fn remove_kv(self) -> (K, V) {
2645         *self.length -= 1;
2646
2647         let (small_leaf, old_key, old_val) = match self.handle.force() {
2648             Leaf(leaf) => {
2649                 let (hole, old_key, old_val) = leaf.remove();
2650                 (hole.into_node(), old_key, old_val)
2651             }
2652             Internal(mut internal) => {
2653                 let key_loc = internal.kv_mut().0 as *mut K;
2654                 let val_loc = internal.kv_mut().1 as *mut V;
2655
2656                 let to_remove = first_leaf_edge(internal.right_edge().descend()).right_kv().ok();
2657                 let to_remove = unsafe { unwrap_unchecked(to_remove) };
2658
2659                 let (hole, key, val) = to_remove.remove();
2660
2661                 let old_key = unsafe { mem::replace(&mut *key_loc, key) };
2662                 let old_val = unsafe { mem::replace(&mut *val_loc, val) };
2663
2664                 (hole.into_node(), old_key, old_val)
2665             }
2666         };
2667
2668         // Handle underflow
2669         let mut cur_node = small_leaf.forget_type();
2670         while cur_node.len() < node::CAPACITY / 2 {
2671             match handle_underfull_node(cur_node) {
2672                 AtRoot => break,
2673                 EmptyParent(_) => unreachable!(),
2674                 Merged(parent) => {
2675                     if parent.len() == 0 {
2676                         // We must be at the root
2677                         parent.into_root_mut().pop_level();
2678                         break;
2679                     } else {
2680                         cur_node = parent.forget_type();
2681                     }
2682                 }
2683                 Stole(_) => break,
2684             }
2685         }
2686
2687         (old_key, old_val)
2688     }
2689 }
2690
2691 enum UnderflowResult<'a, K, V> {
2692     AtRoot,
2693     EmptyParent(NodeRef<marker::Mut<'a>, K, V, marker::Internal>),
2694     Merged(NodeRef<marker::Mut<'a>, K, V, marker::Internal>),
2695     Stole(NodeRef<marker::Mut<'a>, K, V, marker::Internal>),
2696 }
2697
2698 fn handle_underfull_node<K, V>(
2699     node: NodeRef<marker::Mut<'_>, K, V, marker::LeafOrInternal>,
2700 ) -> UnderflowResult<'_, K, V> {
2701     let parent = if let Ok(parent) = node.ascend() {
2702         parent
2703     } else {
2704         return AtRoot;
2705     };
2706
2707     let (is_left, mut handle) = match parent.left_kv() {
2708         Ok(left) => (true, left),
2709         Err(parent) => match parent.right_kv() {
2710             Ok(right) => (false, right),
2711             Err(parent) => {
2712                 return EmptyParent(parent.into_node());
2713             }
2714         },
2715     };
2716
2717     if handle.can_merge() {
2718         Merged(handle.merge().into_node())
2719     } else {
2720         if is_left {
2721             handle.steal_left();
2722         } else {
2723             handle.steal_right();
2724         }
2725         Stole(handle.into_node())
2726     }
2727 }
2728
2729 impl<K: Ord, V, I: Iterator<Item = (K, V)>> Iterator for MergeIter<K, V, I> {
2730     type Item = (K, V);
2731
2732     fn next(&mut self) -> Option<(K, V)> {
2733         let res = match (self.left.peek(), self.right.peek()) {
2734             (Some(&(ref left_key, _)), Some(&(ref right_key, _))) => left_key.cmp(right_key),
2735             (Some(_), None) => Ordering::Less,
2736             (None, Some(_)) => Ordering::Greater,
2737             (None, None) => return None,
2738         };
2739
2740         // Check which elements comes first and only advance the corresponding iterator.
2741         // If two keys are equal, take the value from `right`.
2742         match res {
2743             Ordering::Less => self.left.next(),
2744             Ordering::Greater => self.right.next(),
2745             Ordering::Equal => {
2746                 self.left.next();
2747                 self.right.next()
2748             }
2749         }
2750     }
2751 }