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