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