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