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