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