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