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