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