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