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