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