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