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