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