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