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