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