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