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