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