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