]> git.lizzy.rs Git - rust.git/blob - src/libcollections/btree/map.rs
Changed issue number to 36105
[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};
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 impl<'a, K: 'a, V: 'a> DoubleEndedIterator for Iter<'a, K, V> {
1151     fn next_back(&mut self) -> Option<(&'a K, &'a V)> {
1152         if self.length == 0 {
1153             None
1154         } else {
1155             self.length -= 1;
1156             unsafe { Some(self.range.next_back_unchecked()) }
1157         }
1158     }
1159 }
1160
1161 impl<'a, K: 'a, V: 'a> ExactSizeIterator for Iter<'a, K, V> {
1162     fn len(&self) -> usize {
1163         self.length
1164     }
1165 }
1166
1167 impl<'a, K, V> Clone for Iter<'a, K, V> {
1168     fn clone(&self) -> Iter<'a, K, V> {
1169         Iter {
1170             range: self.range.clone(),
1171             length: self.length,
1172         }
1173     }
1174 }
1175
1176 impl<'a, K: 'a, V: 'a> IntoIterator for &'a mut BTreeMap<K, V> {
1177     type Item = (&'a K, &'a mut V);
1178     type IntoIter = IterMut<'a, K, V>;
1179
1180     fn into_iter(self) -> IterMut<'a, K, V> {
1181         self.iter_mut()
1182     }
1183 }
1184
1185 impl<'a, K: 'a, V: 'a> Iterator for IterMut<'a, K, V> {
1186     type Item = (&'a K, &'a mut V);
1187
1188     fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
1189         if self.length == 0 {
1190             None
1191         } else {
1192             self.length -= 1;
1193             unsafe { Some(self.range.next_unchecked()) }
1194         }
1195     }
1196
1197     fn size_hint(&self) -> (usize, Option<usize>) {
1198         (self.length, Some(self.length))
1199     }
1200 }
1201
1202 impl<'a, K: 'a, V: 'a> DoubleEndedIterator for IterMut<'a, K, V> {
1203     fn next_back(&mut self) -> Option<(&'a K, &'a mut V)> {
1204         if self.length == 0 {
1205             None
1206         } else {
1207             self.length -= 1;
1208             unsafe { Some(self.range.next_back_unchecked()) }
1209         }
1210     }
1211 }
1212
1213 impl<'a, K: 'a, V: 'a> ExactSizeIterator for IterMut<'a, K, V> {
1214     fn len(&self) -> usize {
1215         self.length
1216     }
1217 }
1218
1219 impl<K, V> IntoIterator for BTreeMap<K, V> {
1220     type Item = (K, V);
1221     type IntoIter = IntoIter<K, V>;
1222
1223     fn into_iter(self) -> IntoIter<K, V> {
1224         let root1 = unsafe { ptr::read(&self.root).into_ref() };
1225         let root2 = unsafe { ptr::read(&self.root).into_ref() };
1226         let len = self.length;
1227         mem::forget(self);
1228
1229         IntoIter {
1230             front: first_leaf_edge(root1),
1231             back: last_leaf_edge(root2),
1232             length: len,
1233         }
1234     }
1235 }
1236
1237 impl<K, V> Drop for IntoIter<K, V> {
1238     fn drop(&mut self) {
1239         for _ in &mut *self {
1240         }
1241         unsafe {
1242             let leaf_node = ptr::read(&self.front).into_node();
1243             if let Some(first_parent) = leaf_node.deallocate_and_ascend() {
1244                 let mut cur_node = first_parent.into_node();
1245                 while let Some(parent) = cur_node.deallocate_and_ascend() {
1246                     cur_node = parent.into_node()
1247                 }
1248             }
1249         }
1250     }
1251 }
1252
1253 impl<K, V> Iterator for IntoIter<K, V> {
1254     type Item = (K, V);
1255
1256     fn next(&mut self) -> Option<(K, V)> {
1257         if self.length == 0 {
1258             return None;
1259         } else {
1260             self.length -= 1;
1261         }
1262
1263         let handle = unsafe { ptr::read(&self.front) };
1264
1265         let mut cur_handle = match handle.right_kv() {
1266             Ok(kv) => {
1267                 let k = unsafe { ptr::read(kv.reborrow().into_kv().0) };
1268                 let v = unsafe { ptr::read(kv.reborrow().into_kv().1) };
1269                 self.front = kv.right_edge();
1270                 return Some((k, v));
1271             }
1272             Err(last_edge) => unsafe {
1273                 unwrap_unchecked(last_edge.into_node().deallocate_and_ascend())
1274             },
1275         };
1276
1277         loop {
1278             match cur_handle.right_kv() {
1279                 Ok(kv) => {
1280                     let k = unsafe { ptr::read(kv.reborrow().into_kv().0) };
1281                     let v = unsafe { ptr::read(kv.reborrow().into_kv().1) };
1282                     self.front = first_leaf_edge(kv.right_edge().descend());
1283                     return Some((k, v));
1284                 }
1285                 Err(last_edge) => unsafe {
1286                     cur_handle = unwrap_unchecked(last_edge.into_node().deallocate_and_ascend());
1287                 },
1288             }
1289         }
1290     }
1291
1292     fn size_hint(&self) -> (usize, Option<usize>) {
1293         (self.length, Some(self.length))
1294     }
1295 }
1296
1297 impl<K, V> DoubleEndedIterator for IntoIter<K, V> {
1298     fn next_back(&mut self) -> Option<(K, V)> {
1299         if self.length == 0 {
1300             return None;
1301         } else {
1302             self.length -= 1;
1303         }
1304
1305         let handle = unsafe { ptr::read(&self.back) };
1306
1307         let mut cur_handle = match handle.left_kv() {
1308             Ok(kv) => {
1309                 let k = unsafe { ptr::read(kv.reborrow().into_kv().0) };
1310                 let v = unsafe { ptr::read(kv.reborrow().into_kv().1) };
1311                 self.back = kv.left_edge();
1312                 return Some((k, v));
1313             }
1314             Err(last_edge) => unsafe {
1315                 unwrap_unchecked(last_edge.into_node().deallocate_and_ascend())
1316             },
1317         };
1318
1319         loop {
1320             match cur_handle.left_kv() {
1321                 Ok(kv) => {
1322                     let k = unsafe { ptr::read(kv.reborrow().into_kv().0) };
1323                     let v = unsafe { ptr::read(kv.reborrow().into_kv().1) };
1324                     self.back = last_leaf_edge(kv.left_edge().descend());
1325                     return Some((k, v));
1326                 }
1327                 Err(last_edge) => unsafe {
1328                     cur_handle = unwrap_unchecked(last_edge.into_node().deallocate_and_ascend());
1329                 },
1330             }
1331         }
1332     }
1333 }
1334
1335 impl<K, V> ExactSizeIterator for IntoIter<K, V> {
1336     fn len(&self) -> usize {
1337         self.length
1338     }
1339 }
1340
1341 impl<'a, K, V> Iterator for Keys<'a, K, V> {
1342     type Item = &'a K;
1343
1344     fn next(&mut self) -> Option<&'a K> {
1345         self.inner.next().map(|(k, _)| k)
1346     }
1347
1348     fn size_hint(&self) -> (usize, Option<usize>) {
1349         self.inner.size_hint()
1350     }
1351 }
1352
1353 impl<'a, K, V> DoubleEndedIterator for Keys<'a, K, V> {
1354     fn next_back(&mut self) -> Option<&'a K> {
1355         self.inner.next_back().map(|(k, _)| k)
1356     }
1357 }
1358
1359 impl<'a, K, V> ExactSizeIterator for Keys<'a, K, V> {
1360     fn len(&self) -> usize {
1361         self.inner.len()
1362     }
1363 }
1364
1365 impl<'a, K, V> Clone for Keys<'a, K, V> {
1366     fn clone(&self) -> Keys<'a, K, V> {
1367         Keys { inner: self.inner.clone() }
1368     }
1369 }
1370
1371 impl<'a, K, V> Iterator for Values<'a, K, V> {
1372     type Item = &'a V;
1373
1374     fn next(&mut self) -> Option<&'a V> {
1375         self.inner.next().map(|(_, v)| v)
1376     }
1377
1378     fn size_hint(&self) -> (usize, Option<usize>) {
1379         self.inner.size_hint()
1380     }
1381 }
1382
1383 impl<'a, K, V> DoubleEndedIterator for Values<'a, K, V> {
1384     fn next_back(&mut self) -> Option<&'a V> {
1385         self.inner.next_back().map(|(_, v)| v)
1386     }
1387 }
1388
1389 impl<'a, K, V> ExactSizeIterator for Values<'a, K, V> {
1390     fn len(&self) -> usize {
1391         self.inner.len()
1392     }
1393 }
1394
1395 impl<'a, K, V> Clone for Values<'a, K, V> {
1396     fn clone(&self) -> Values<'a, K, V> {
1397         Values { inner: self.inner.clone() }
1398     }
1399 }
1400
1401 impl<'a, K, V> Iterator for Range<'a, K, V> {
1402     type Item = (&'a K, &'a V);
1403
1404     fn next(&mut self) -> Option<(&'a K, &'a V)> {
1405         if self.front == self.back {
1406             None
1407         } else {
1408             unsafe { Some(self.next_unchecked()) }
1409         }
1410     }
1411 }
1412
1413 #[stable(feature = "map_values_mut", since = "1.10.0")]
1414 impl<'a, K, V> Iterator for ValuesMut<'a, K, V> {
1415     type Item = &'a mut V;
1416
1417     fn next(&mut self) -> Option<&'a mut V> {
1418         self.inner.next().map(|(_, v)| v)
1419     }
1420
1421     fn size_hint(&self) -> (usize, Option<usize>) {
1422         self.inner.size_hint()
1423     }
1424 }
1425
1426 #[stable(feature = "map_values_mut", since = "1.10.0")]
1427 impl<'a, K, V> DoubleEndedIterator for ValuesMut<'a, K, V> {
1428     fn next_back(&mut self) -> Option<&'a mut V> {
1429         self.inner.next_back().map(|(_, v)| v)
1430     }
1431 }
1432
1433 #[stable(feature = "map_values_mut", since = "1.10.0")]
1434 impl<'a, K, V> ExactSizeIterator for ValuesMut<'a, K, V> {
1435     fn len(&self) -> usize {
1436         self.inner.len()
1437     }
1438 }
1439
1440 impl<'a, K, V> Range<'a, K, V> {
1441     unsafe fn next_unchecked(&mut self) -> (&'a K, &'a V) {
1442         let handle = self.front;
1443
1444         let mut cur_handle = match handle.right_kv() {
1445             Ok(kv) => {
1446                 let ret = kv.into_kv();
1447                 self.front = kv.right_edge();
1448                 return ret;
1449             }
1450             Err(last_edge) => {
1451                 let next_level = last_edge.into_node().ascend().ok();
1452                 unwrap_unchecked(next_level)
1453             }
1454         };
1455
1456         loop {
1457             match cur_handle.right_kv() {
1458                 Ok(kv) => {
1459                     let ret = kv.into_kv();
1460                     self.front = first_leaf_edge(kv.right_edge().descend());
1461                     return ret;
1462                 }
1463                 Err(last_edge) => {
1464                     let next_level = last_edge.into_node().ascend().ok();
1465                     cur_handle = unwrap_unchecked(next_level);
1466                 }
1467             }
1468         }
1469     }
1470 }
1471
1472 impl<'a, K, V> DoubleEndedIterator for Range<'a, K, V> {
1473     fn next_back(&mut self) -> Option<(&'a K, &'a V)> {
1474         if self.front == self.back {
1475             None
1476         } else {
1477             unsafe { Some(self.next_back_unchecked()) }
1478         }
1479     }
1480 }
1481
1482 impl<'a, K, V> Range<'a, K, V> {
1483     unsafe fn next_back_unchecked(&mut self) -> (&'a K, &'a V) {
1484         let handle = self.back;
1485
1486         let mut cur_handle = match handle.left_kv() {
1487             Ok(kv) => {
1488                 let ret = kv.into_kv();
1489                 self.back = kv.left_edge();
1490                 return ret;
1491             }
1492             Err(last_edge) => {
1493                 let next_level = last_edge.into_node().ascend().ok();
1494                 unwrap_unchecked(next_level)
1495             }
1496         };
1497
1498         loop {
1499             match cur_handle.left_kv() {
1500                 Ok(kv) => {
1501                     let ret = kv.into_kv();
1502                     self.back = last_leaf_edge(kv.left_edge().descend());
1503                     return ret;
1504                 }
1505                 Err(last_edge) => {
1506                     let next_level = last_edge.into_node().ascend().ok();
1507                     cur_handle = unwrap_unchecked(next_level);
1508                 }
1509             }
1510         }
1511     }
1512 }
1513
1514 impl<'a, K, V> Clone for Range<'a, K, V> {
1515     fn clone(&self) -> Range<'a, K, V> {
1516         Range {
1517             front: self.front,
1518             back: self.back,
1519         }
1520     }
1521 }
1522
1523 impl<'a, K, V> Iterator for RangeMut<'a, K, V> {
1524     type Item = (&'a K, &'a mut V);
1525
1526     fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
1527         if self.front == self.back {
1528             None
1529         } else {
1530             unsafe { Some(self.next_unchecked()) }
1531         }
1532     }
1533 }
1534
1535 impl<'a, K, V> RangeMut<'a, K, V> {
1536     unsafe fn next_unchecked(&mut self) -> (&'a K, &'a mut V) {
1537         let handle = ptr::read(&self.front);
1538
1539         let mut cur_handle = match handle.right_kv() {
1540             Ok(kv) => {
1541                 let (k, v) = ptr::read(&kv).into_kv_mut();
1542                 self.front = kv.right_edge();
1543                 return (k, v);
1544             }
1545             Err(last_edge) => {
1546                 let next_level = last_edge.into_node().ascend().ok();
1547                 unwrap_unchecked(next_level)
1548             }
1549         };
1550
1551         loop {
1552             match cur_handle.right_kv() {
1553                 Ok(kv) => {
1554                     let (k, v) = ptr::read(&kv).into_kv_mut();
1555                     self.front = first_leaf_edge(kv.right_edge().descend());
1556                     return (k, v);
1557                 }
1558                 Err(last_edge) => {
1559                     let next_level = last_edge.into_node().ascend().ok();
1560                     cur_handle = unwrap_unchecked(next_level);
1561                 }
1562             }
1563         }
1564     }
1565 }
1566
1567 impl<'a, K, V> DoubleEndedIterator for RangeMut<'a, K, V> {
1568     fn next_back(&mut self) -> Option<(&'a K, &'a mut V)> {
1569         if self.front == self.back {
1570             None
1571         } else {
1572             unsafe { Some(self.next_back_unchecked()) }
1573         }
1574     }
1575 }
1576
1577 impl<'a, K, V> RangeMut<'a, K, V> {
1578     unsafe fn next_back_unchecked(&mut self) -> (&'a K, &'a mut V) {
1579         let handle = ptr::read(&self.back);
1580
1581         let mut cur_handle = match handle.left_kv() {
1582             Ok(kv) => {
1583                 let (k, v) = ptr::read(&kv).into_kv_mut();
1584                 self.back = kv.left_edge();
1585                 return (k, v);
1586             }
1587             Err(last_edge) => {
1588                 let next_level = last_edge.into_node().ascend().ok();
1589                 unwrap_unchecked(next_level)
1590             }
1591         };
1592
1593         loop {
1594             match cur_handle.left_kv() {
1595                 Ok(kv) => {
1596                     let (k, v) = ptr::read(&kv).into_kv_mut();
1597                     self.back = last_leaf_edge(kv.left_edge().descend());
1598                     return (k, v);
1599                 }
1600                 Err(last_edge) => {
1601                     let next_level = last_edge.into_node().ascend().ok();
1602                     cur_handle = unwrap_unchecked(next_level);
1603                 }
1604             }
1605         }
1606     }
1607 }
1608
1609 impl<K: Ord, V> FromIterator<(K, V)> for BTreeMap<K, V> {
1610     fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> BTreeMap<K, V> {
1611         let mut map = BTreeMap::new();
1612         map.extend(iter);
1613         map
1614     }
1615 }
1616
1617 impl<K: Ord, V> Extend<(K, V)> for BTreeMap<K, V> {
1618     #[inline]
1619     fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) {
1620         for (k, v) in iter {
1621             self.insert(k, v);
1622         }
1623     }
1624 }
1625
1626 impl<'a, K: Ord + Copy, V: Copy> Extend<(&'a K, &'a V)> for BTreeMap<K, V> {
1627     fn extend<I: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: I) {
1628         self.extend(iter.into_iter().map(|(&key, &value)| (key, value)));
1629     }
1630 }
1631
1632 impl<K: Hash, V: Hash> Hash for BTreeMap<K, V> {
1633     fn hash<H: Hasher>(&self, state: &mut H) {
1634         for elt in self {
1635             elt.hash(state);
1636         }
1637     }
1638 }
1639
1640 impl<K: Ord, V> Default for BTreeMap<K, V> {
1641     fn default() -> BTreeMap<K, V> {
1642         BTreeMap::new()
1643     }
1644 }
1645
1646 impl<K: PartialEq, V: PartialEq> PartialEq for BTreeMap<K, V> {
1647     fn eq(&self, other: &BTreeMap<K, V>) -> bool {
1648         self.len() == other.len() && self.iter().zip(other).all(|(a, b)| a == b)
1649     }
1650 }
1651
1652 impl<K: Eq, V: Eq> Eq for BTreeMap<K, V> {}
1653
1654 impl<K: PartialOrd, V: PartialOrd> PartialOrd for BTreeMap<K, V> {
1655     #[inline]
1656     fn partial_cmp(&self, other: &BTreeMap<K, V>) -> Option<Ordering> {
1657         self.iter().partial_cmp(other.iter())
1658     }
1659 }
1660
1661 impl<K: Ord, V: Ord> Ord for BTreeMap<K, V> {
1662     #[inline]
1663     fn cmp(&self, other: &BTreeMap<K, V>) -> Ordering {
1664         self.iter().cmp(other.iter())
1665     }
1666 }
1667
1668 impl<K: Debug, V: Debug> Debug for BTreeMap<K, V> {
1669     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1670         f.debug_map().entries(self.iter()).finish()
1671     }
1672 }
1673
1674 impl<'a, K: Ord, Q: ?Sized, V> Index<&'a Q> for BTreeMap<K, V>
1675     where K: Borrow<Q>,
1676           Q: Ord
1677 {
1678     type Output = V;
1679
1680     #[inline]
1681     fn index(&self, key: &Q) -> &V {
1682         self.get(key).expect("no entry found for key")
1683     }
1684 }
1685
1686 fn first_leaf_edge<BorrowType, K, V>
1687     (mut node: NodeRef<BorrowType, K, V, marker::LeafOrInternal>)
1688      -> Handle<NodeRef<BorrowType, K, V, marker::Leaf>, marker::Edge> {
1689     loop {
1690         match node.force() {
1691             Leaf(leaf) => return leaf.first_edge(),
1692             Internal(internal) => {
1693                 node = internal.first_edge().descend();
1694             }
1695         }
1696     }
1697 }
1698
1699 fn last_leaf_edge<BorrowType, K, V>
1700     (mut node: NodeRef<BorrowType, K, V, marker::LeafOrInternal>)
1701      -> Handle<NodeRef<BorrowType, K, V, marker::Leaf>, marker::Edge> {
1702     loop {
1703         match node.force() {
1704             Leaf(leaf) => return leaf.last_edge(),
1705             Internal(internal) => {
1706                 node = internal.last_edge().descend();
1707             }
1708         }
1709     }
1710 }
1711
1712 #[inline(always)]
1713 unsafe fn unwrap_unchecked<T>(val: Option<T>) -> T {
1714     val.unwrap_or_else(|| {
1715         if cfg!(debug_assertions) {
1716             panic!("'unchecked' unwrap on None in BTreeMap");
1717         } else {
1718             intrinsics::unreachable();
1719         }
1720     })
1721 }
1722
1723 impl<K, V> BTreeMap<K, V> {
1724     /// Gets an iterator over the entries of the map, sorted by key.
1725     ///
1726     /// # Examples
1727     ///
1728     /// Basic usage:
1729     ///
1730     /// ```
1731     /// use std::collections::BTreeMap;
1732     ///
1733     /// let mut map = BTreeMap::new();
1734     /// map.insert(3, "c");
1735     /// map.insert(2, "b");
1736     /// map.insert(1, "a");
1737     ///
1738     /// for (key, value) in map.iter() {
1739     ///     println!("{}: {}", key, value);
1740     /// }
1741     ///
1742     /// let (first_key, first_value) = map.iter().next().unwrap();
1743     /// assert_eq!((*first_key, *first_value), (1, "a"));
1744     /// ```
1745     #[stable(feature = "rust1", since = "1.0.0")]
1746     pub fn iter(&self) -> Iter<K, V> {
1747         Iter {
1748             range: Range {
1749                 front: first_leaf_edge(self.root.as_ref()),
1750                 back: last_leaf_edge(self.root.as_ref()),
1751             },
1752             length: self.length,
1753         }
1754     }
1755
1756     /// Gets a mutable iterator over the entries of the map, sorted by key.
1757     ///
1758     /// # Examples
1759     ///
1760     /// Basic usage:
1761     ///
1762     /// ```
1763     /// use std::collections::BTreeMap;
1764     ///
1765     /// let mut map = BTreeMap::new();
1766     /// map.insert("a", 1);
1767     /// map.insert("b", 2);
1768     /// map.insert("c", 3);
1769     ///
1770     /// // add 10 to the value if the key isn't "a"
1771     /// for (key, value) in map.iter_mut() {
1772     ///     if key != &"a" {
1773     ///         *value += 10;
1774     ///     }
1775     /// }
1776     /// ```
1777     #[stable(feature = "rust1", since = "1.0.0")]
1778     pub fn iter_mut(&mut self) -> IterMut<K, V> {
1779         let root1 = self.root.as_mut();
1780         let root2 = unsafe { ptr::read(&root1) };
1781         IterMut {
1782             range: RangeMut {
1783                 front: first_leaf_edge(root1),
1784                 back: last_leaf_edge(root2),
1785                 _marker: PhantomData,
1786             },
1787             length: self.length,
1788         }
1789     }
1790
1791     /// Gets an iterator over the keys of the map, in sorted order.
1792     ///
1793     /// # Examples
1794     ///
1795     /// Basic usage:
1796     ///
1797     /// ```
1798     /// use std::collections::BTreeMap;
1799     ///
1800     /// let mut a = BTreeMap::new();
1801     /// a.insert(2, "b");
1802     /// a.insert(1, "a");
1803     ///
1804     /// let keys: Vec<_> = a.keys().cloned().collect();
1805     /// assert_eq!(keys, [1, 2]);
1806     /// ```
1807     #[stable(feature = "rust1", since = "1.0.0")]
1808     pub fn keys<'a>(&'a self) -> Keys<'a, K, V> {
1809         Keys { inner: self.iter() }
1810     }
1811
1812     /// Gets an iterator over the values of the map, in order by key.
1813     ///
1814     /// # Examples
1815     ///
1816     /// Basic usage:
1817     ///
1818     /// ```
1819     /// use std::collections::BTreeMap;
1820     ///
1821     /// let mut a = BTreeMap::new();
1822     /// a.insert(1, "hello");
1823     /// a.insert(2, "goodbye");
1824     ///
1825     /// let values: Vec<&str> = a.values().cloned().collect();
1826     /// assert_eq!(values, ["hello", "goodbye"]);
1827     /// ```
1828     #[stable(feature = "rust1", since = "1.0.0")]
1829     pub fn values<'a>(&'a self) -> Values<'a, K, V> {
1830         Values { inner: self.iter() }
1831     }
1832
1833     /// Gets a mutable iterator over the values of the map, in order by key.
1834     ///
1835     /// # Examples
1836     ///
1837     /// Basic usage:
1838     ///
1839     /// ```
1840     /// use std::collections::BTreeMap;
1841     ///
1842     /// let mut a = BTreeMap::new();
1843     /// a.insert(1, String::from("hello"));
1844     /// a.insert(2, String::from("goodbye"));
1845     ///
1846     /// for value in a.values_mut() {
1847     ///     value.push_str("!");
1848     /// }
1849     ///
1850     /// let values: Vec<String> = a.values().cloned().collect();
1851     /// assert_eq!(values, [String::from("hello!"),
1852     ///                     String::from("goodbye!")]);
1853     /// ```
1854     #[stable(feature = "map_values_mut", since = "1.10.0")]
1855     pub fn values_mut(&mut self) -> ValuesMut<K, V> {
1856         ValuesMut { inner: self.iter_mut() }
1857     }
1858
1859     /// Returns the number of elements in the map.
1860     ///
1861     /// # Examples
1862     ///
1863     /// Basic usage:
1864     ///
1865     /// ```
1866     /// use std::collections::BTreeMap;
1867     ///
1868     /// let mut a = BTreeMap::new();
1869     /// assert_eq!(a.len(), 0);
1870     /// a.insert(1, "a");
1871     /// assert_eq!(a.len(), 1);
1872     /// ```
1873     #[stable(feature = "rust1", since = "1.0.0")]
1874     pub fn len(&self) -> usize {
1875         self.length
1876     }
1877
1878     /// Returns true if the map contains no elements.
1879     ///
1880     /// # Examples
1881     ///
1882     /// Basic usage:
1883     ///
1884     /// ```
1885     /// use std::collections::BTreeMap;
1886     ///
1887     /// let mut a = BTreeMap::new();
1888     /// assert!(a.is_empty());
1889     /// a.insert(1, "a");
1890     /// assert!(!a.is_empty());
1891     /// ```
1892     #[stable(feature = "rust1", since = "1.0.0")]
1893     pub fn is_empty(&self) -> bool {
1894         self.len() == 0
1895     }
1896 }
1897
1898 impl<'a, K: Ord, V> Entry<'a, K, V> {
1899     /// Ensures a value is in the entry by inserting the default if empty, and returns
1900     /// a mutable reference to the value in the entry.
1901     ///
1902     /// # Examples
1903     ///
1904     /// ```
1905     /// use std::collections::BTreeMap;
1906     ///
1907     /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
1908     /// map.entry("poneyland").or_insert(12);
1909     ///
1910     /// assert_eq!(map["poneyland"], 12);
1911     /// ```
1912     #[stable(feature = "rust1", since = "1.0.0")]
1913     pub fn or_insert(self, default: V) -> &'a mut V {
1914         match self {
1915             Occupied(entry) => entry.into_mut(),
1916             Vacant(entry) => entry.insert(default),
1917         }
1918     }
1919
1920     /// Ensures a value is in the entry by inserting the result of the default function if empty,
1921     /// and returns a mutable reference to the value in the entry.
1922     ///
1923     /// # Examples
1924     ///
1925     /// ```
1926     /// use std::collections::BTreeMap;
1927     ///
1928     /// let mut map: BTreeMap<&str, String> = BTreeMap::new();
1929     /// let s = "hoho".to_owned();
1930     ///
1931     /// map.entry("poneyland").or_insert_with(|| s);
1932     ///
1933     /// assert_eq!(map["poneyland"], "hoho".to_owned());
1934     /// ```
1935     #[stable(feature = "rust1", since = "1.0.0")]
1936     pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V {
1937         match self {
1938             Occupied(entry) => entry.into_mut(),
1939             Vacant(entry) => entry.insert(default()),
1940         }
1941     }
1942
1943     /// Returns a reference to this entry's key.
1944     ///
1945     /// # Examples
1946     ///
1947     /// ```
1948     /// use std::collections::BTreeMap;
1949     ///
1950     /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
1951     /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
1952     /// ```
1953     #[stable(feature = "map_entry_keys", since = "1.10.0")]
1954     pub fn key(&self) -> &K {
1955         match *self {
1956             Occupied(ref entry) => entry.key(),
1957             Vacant(ref entry) => entry.key(),
1958         }
1959     }
1960 }
1961
1962 impl<'a, K: Ord, V> VacantEntry<'a, K, V> {
1963     /// Gets a reference to the key that would be used when inserting a value
1964     /// through the VacantEntry.
1965     ///
1966     /// # Examples
1967     ///
1968     /// ```
1969     /// use std::collections::BTreeMap;
1970     ///
1971     /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
1972     /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
1973     /// ```
1974     #[stable(feature = "map_entry_keys", since = "1.10.0")]
1975     pub fn key(&self) -> &K {
1976         &self.key
1977     }
1978
1979     /// Take ownership of the key.
1980     ///
1981     /// # Examples
1982     ///
1983     /// ```
1984     /// #![feature(map_entry_recover_keys)]
1985     ///
1986     /// use std::collections::BTreeMap;
1987     /// use std::collections::btree_map::Entry;
1988     ///
1989     /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
1990     ///
1991     /// if let Entry::Vacant(v) = map.entry("poneyland") {
1992     ///     v.into_key();
1993     /// }
1994     /// ```
1995     #[unstable(feature = "map_entry_recover_keys", issue = "34285")]
1996     pub fn into_key(self) -> K {
1997         self.key
1998     }
1999
2000     /// Sets the value of the entry with the VacantEntry's key,
2001     /// and returns a mutable reference to it.
2002     ///
2003     /// # Examples
2004     ///
2005     /// ```
2006     /// use std::collections::BTreeMap;
2007     ///
2008     /// let mut count: BTreeMap<&str, usize> = BTreeMap::new();
2009     ///
2010     /// // count the number of occurrences of letters in the vec
2011     /// for x in vec!["a","b","a","c","a","b"] {
2012     ///     *count.entry(x).or_insert(0) += 1;
2013     /// }
2014     ///
2015     /// assert_eq!(count["a"], 3);
2016     /// ```
2017     #[stable(feature = "rust1", since = "1.0.0")]
2018     pub fn insert(self, value: V) -> &'a mut V {
2019         *self.length += 1;
2020
2021         let out_ptr;
2022
2023         let mut ins_k;
2024         let mut ins_v;
2025         let mut ins_edge;
2026
2027         let mut cur_parent = match self.handle.insert(self.key, value) {
2028             (Fit(handle), _) => return handle.into_kv_mut().1,
2029             (Split(left, k, v, right), ptr) => {
2030                 ins_k = k;
2031                 ins_v = v;
2032                 ins_edge = right;
2033                 out_ptr = ptr;
2034                 left.ascend().map_err(|n| n.into_root_mut())
2035             }
2036         };
2037
2038         loop {
2039             match cur_parent {
2040                 Ok(parent) => {
2041                     match parent.insert(ins_k, ins_v, ins_edge) {
2042                         Fit(_) => return unsafe { &mut *out_ptr },
2043                         Split(left, k, v, right) => {
2044                             ins_k = k;
2045                             ins_v = v;
2046                             ins_edge = right;
2047                             cur_parent = left.ascend().map_err(|n| n.into_root_mut());
2048                         }
2049                     }
2050                 }
2051                 Err(root) => {
2052                     root.push_level().push(ins_k, ins_v, ins_edge);
2053                     return unsafe { &mut *out_ptr };
2054                 }
2055             }
2056         }
2057     }
2058 }
2059
2060 impl<'a, K: Ord, V> OccupiedEntry<'a, K, V> {
2061     /// Gets a reference to the key in the entry.
2062     ///
2063     /// # Examples
2064     ///
2065     /// ```
2066     /// use std::collections::BTreeMap;
2067     ///
2068     /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2069     /// map.entry("poneyland").or_insert(12);
2070     /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2071     /// ```
2072     #[stable(feature = "map_entry_keys", since = "1.10.0")]
2073     pub fn key(&self) -> &K {
2074         self.handle.reborrow().into_kv().0
2075     }
2076
2077     /// Take ownership of the key and value from the map.
2078     ///
2079     /// # Examples
2080     ///
2081     /// ```
2082     /// #![feature(map_entry_recover_keys)]
2083     ///
2084     /// use std::collections::BTreeMap;
2085     /// use std::collections::btree_map::Entry;
2086     ///
2087     /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2088     /// map.entry("poneyland").or_insert(12);
2089     ///
2090     /// if let Entry::Occupied(o) = map.entry("poneyland") {
2091     ///     // We delete the entry from the map.
2092     ///     o.remove_pair();
2093     /// }
2094     ///
2095     /// // If now try to get the value, it will panic:
2096     /// // println!("{}", map["poneyland"]);
2097     /// ```
2098     #[unstable(feature = "map_entry_recover_keys", issue = "34285")]
2099     pub fn remove_pair(self) -> (K, V) {
2100         self.remove_kv()
2101     }
2102
2103     /// Gets a reference to the value in the entry.
2104     ///
2105     /// # Examples
2106     ///
2107     /// ```
2108     /// use std::collections::BTreeMap;
2109     /// use std::collections::btree_map::Entry;
2110     ///
2111     /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2112     /// map.entry("poneyland").or_insert(12);
2113     ///
2114     /// if let Entry::Occupied(o) = map.entry("poneyland") {
2115     ///     assert_eq!(o.get(), &12);
2116     /// }
2117     /// ```
2118     #[stable(feature = "rust1", since = "1.0.0")]
2119     pub fn get(&self) -> &V {
2120         self.handle.reborrow().into_kv().1
2121     }
2122
2123     /// Gets a mutable reference to the value in the entry.
2124     ///
2125     /// # Examples
2126     ///
2127     /// ```
2128     /// use std::collections::BTreeMap;
2129     /// use std::collections::btree_map::Entry;
2130     ///
2131     /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2132     /// map.entry("poneyland").or_insert(12);
2133     ///
2134     /// assert_eq!(map["poneyland"], 12);
2135     /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
2136     ///      *o.get_mut() += 10;
2137     /// }
2138     /// assert_eq!(map["poneyland"], 22);
2139     /// ```
2140     #[stable(feature = "rust1", since = "1.0.0")]
2141     pub fn get_mut(&mut self) -> &mut V {
2142         self.handle.kv_mut().1
2143     }
2144
2145     /// Converts the entry into a mutable reference to its value.
2146     ///
2147     /// # Examples
2148     ///
2149     /// ```
2150     /// use std::collections::BTreeMap;
2151     /// use std::collections::btree_map::Entry;
2152     ///
2153     /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2154     /// map.entry("poneyland").or_insert(12);
2155     ///
2156     /// assert_eq!(map["poneyland"], 12);
2157     /// if let Entry::Occupied(o) = map.entry("poneyland") {
2158     ///     *o.into_mut() += 10;
2159     /// }
2160     /// assert_eq!(map["poneyland"], 22);
2161     /// ```
2162     #[stable(feature = "rust1", since = "1.0.0")]
2163     pub fn into_mut(self) -> &'a mut V {
2164         self.handle.into_kv_mut().1
2165     }
2166
2167     /// Sets the value of the entry with the OccupiedEntry's key,
2168     /// and returns the entry's old value.
2169     ///
2170     /// # Examples
2171     ///
2172     /// ```
2173     /// use std::collections::BTreeMap;
2174     /// use std::collections::btree_map::Entry;
2175     ///
2176     /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2177     /// map.entry("poneyland").or_insert(12);
2178     ///
2179     /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
2180     ///     assert_eq!(o.insert(15), 12);
2181     /// }
2182     /// assert_eq!(map["poneyland"], 15);
2183     /// ```
2184     #[stable(feature = "rust1", since = "1.0.0")]
2185     pub fn insert(&mut self, value: V) -> V {
2186         mem::replace(self.get_mut(), value)
2187     }
2188
2189     /// Takes the value of the entry out of the map, and returns it.
2190     ///
2191     /// # Examples
2192     ///
2193     /// ```
2194     /// use std::collections::BTreeMap;
2195     /// use std::collections::btree_map::Entry;
2196     ///
2197     /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2198     /// map.entry("poneyland").or_insert(12);
2199     ///
2200     /// if let Entry::Occupied(o) = map.entry("poneyland") {
2201     ///     assert_eq!(o.remove(), 12);
2202     /// }
2203     /// // If we try to get "poneyland"'s value, it'll panic:
2204     /// // println!("{}", map["poneyland"]);
2205     /// ```
2206     #[stable(feature = "rust1", since = "1.0.0")]
2207     pub fn remove(self) -> V {
2208         self.remove_kv().1
2209     }
2210
2211     fn remove_kv(self) -> (K, V) {
2212         *self.length -= 1;
2213
2214         let (small_leaf, old_key, old_val) = match self.handle.force() {
2215             Leaf(leaf) => {
2216                 let (hole, old_key, old_val) = leaf.remove();
2217                 (hole.into_node(), old_key, old_val)
2218             }
2219             Internal(mut internal) => {
2220                 let key_loc = internal.kv_mut().0 as *mut K;
2221                 let val_loc = internal.kv_mut().1 as *mut V;
2222
2223                 let to_remove = first_leaf_edge(internal.right_edge().descend()).right_kv().ok();
2224                 let to_remove = unsafe { unwrap_unchecked(to_remove) };
2225
2226                 let (hole, key, val) = to_remove.remove();
2227
2228                 let old_key = unsafe { mem::replace(&mut *key_loc, key) };
2229                 let old_val = unsafe { mem::replace(&mut *val_loc, val) };
2230
2231                 (hole.into_node(), old_key, old_val)
2232             }
2233         };
2234
2235         // Handle underflow
2236         let mut cur_node = small_leaf.forget_type();
2237         while cur_node.len() < node::CAPACITY / 2 {
2238             match handle_underfull_node(cur_node) {
2239                 AtRoot => break,
2240                 EmptyParent(_) => unreachable!(),
2241                 Merged(parent) => {
2242                     if parent.len() == 0 {
2243                         // We must be at the root
2244                         parent.into_root_mut().pop_level();
2245                         break;
2246                     } else {
2247                         cur_node = parent.forget_type();
2248                     }
2249                 }
2250                 Stole(_) => break,
2251             }
2252         }
2253
2254         (old_key, old_val)
2255     }
2256 }
2257
2258 enum UnderflowResult<'a, K, V> {
2259     AtRoot,
2260     EmptyParent(NodeRef<marker::Mut<'a>, K, V, marker::Internal>),
2261     Merged(NodeRef<marker::Mut<'a>, K, V, marker::Internal>),
2262     Stole(NodeRef<marker::Mut<'a>, K, V, marker::Internal>),
2263 }
2264
2265 fn handle_underfull_node<'a, K, V>(node: NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal>)
2266                                    -> UnderflowResult<'a, K, V> {
2267     let parent = if let Ok(parent) = node.ascend() {
2268         parent
2269     } else {
2270         return AtRoot;
2271     };
2272
2273     let (is_left, mut handle) = match parent.left_kv() {
2274         Ok(left) => (true, left),
2275         Err(parent) => {
2276             match parent.right_kv() {
2277                 Ok(right) => (false, right),
2278                 Err(parent) => {
2279                     return EmptyParent(parent.into_node());
2280                 }
2281             }
2282         }
2283     };
2284
2285     if handle.can_merge() {
2286         Merged(handle.merge().into_node())
2287     } else {
2288         if is_left {
2289             handle.steal_left();
2290         } else {
2291             handle.steal_right();
2292         }
2293         Stole(handle.into_node())
2294     }
2295 }
2296
2297 impl<K: Ord, V, I: Iterator<Item = (K, V)>> Iterator for MergeIter<K, V, I> {
2298     type Item = (K, V);
2299
2300     fn next(&mut self) -> Option<(K, V)> {
2301         let res = match (self.left.peek(), self.right.peek()) {
2302             (Some(&(ref left_key, _)), Some(&(ref right_key, _))) => left_key.cmp(right_key),
2303             (Some(_), None) => Ordering::Less,
2304             (None, Some(_)) => Ordering::Greater,
2305             (None, None) => return None,
2306         };
2307
2308         // Check which elements comes first and only advance the corresponding iterator.
2309         // If two keys are equal, take the value from `right`.
2310         match res {
2311             Ordering::Less => self.left.next(),
2312             Ordering::Greater => self.right.next(),
2313             Ordering::Equal => {
2314                 self.left.next();
2315                 self.right.next()
2316             }
2317         }
2318     }
2319 }