]> git.lizzy.rs Git - rust.git/blob - library/alloc/src/collections/btree/map.rs
BTreeMap: lightly refactor the split_off implementation
[rust.git] / library / alloc / src / collections / btree / map.rs
1 use core::borrow::Borrow;
2 use core::cmp::Ordering;
3 use core::fmt::{self, Debug};
4 use core::hash::{Hash, Hasher};
5 use core::iter::{FromIterator, FusedIterator};
6 use core::marker::PhantomData;
7 use core::mem::{self, ManuallyDrop};
8 use core::ops::{Index, RangeBounds};
9 use core::ptr;
10
11 use super::borrow::DormantMutRef;
12 use super::node::{self, marker, ForceResult::*, Handle, NodeRef, Root};
13 use super::search::SearchResult::*;
14 use super::unwrap_unchecked;
15
16 mod entry;
17 pub use entry::{Entry, OccupiedEntry, VacantEntry};
18 use Entry::*;
19
20 /// Minimum number of elements in nodes that are not a root.
21 /// We might temporarily have fewer elements during methods.
22 pub(super) const MIN_LEN: usize = node::MIN_LEN_AFTER_SPLIT;
23
24 // A tree in a `BTreeMap` is a tree in the `node` module with addtional invariants:
25 // - Keys must appear in ascending order (according to the key's type).
26 // - If the root node is internal, it must contain at least 1 element.
27 // - Every non-root node contains at least MIN_LEN elements.
28 //
29 // An empty map may be represented both by the absense of a root node or by a
30 // root node that is an empty leaf.
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(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 /// The behavior resulting from such a logic error is not specified, but will not result in
63 /// undefined behavior. This could include panics, incorrect results, aborts, memory leaks, and
64 /// non-termination.
65 ///
66 /// [`Cell`]: core::cell::Cell
67 /// [`RefCell`]: core::cell::RefCell
68 ///
69 /// # Examples
70 ///
71 /// ```
72 /// use std::collections::BTreeMap;
73 ///
74 /// // type inference lets us omit an explicit type signature (which
75 /// // would be `BTreeMap<&str, &str>` in this example).
76 /// let mut movie_reviews = BTreeMap::new();
77 ///
78 /// // review some movies.
79 /// movie_reviews.insert("Office Space",       "Deals with real issues in the workplace.");
80 /// movie_reviews.insert("Pulp Fiction",       "Masterpiece.");
81 /// movie_reviews.insert("The Godfather",      "Very enjoyable.");
82 /// movie_reviews.insert("The Blues Brothers", "Eye lyked it a lot.");
83 ///
84 /// // check for a specific one.
85 /// if !movie_reviews.contains_key("Les Misérables") {
86 ///     println!("We've got {} reviews, but Les Misérables ain't one.",
87 ///              movie_reviews.len());
88 /// }
89 ///
90 /// // oops, this review has a lot of spelling mistakes, let's delete it.
91 /// movie_reviews.remove("The Blues Brothers");
92 ///
93 /// // look up the values associated with some keys.
94 /// let to_find = ["Up!", "Office Space"];
95 /// for movie in &to_find {
96 ///     match movie_reviews.get(movie) {
97 ///        Some(review) => println!("{}: {}", movie, review),
98 ///        None => println!("{} is unreviewed.", movie)
99 ///     }
100 /// }
101 ///
102 /// // Look up the value for a key (will panic if the key is not found).
103 /// println!("Movie review: {}", movie_reviews["Office Space"]);
104 ///
105 /// // iterate over everything.
106 /// for (movie, review) in &movie_reviews {
107 ///     println!("{}: \"{}\"", movie, review);
108 /// }
109 /// ```
110 ///
111 /// `BTreeMap` also implements an [`Entry API`], which allows for more complex
112 /// methods of getting, setting, updating and removing keys and their values:
113 ///
114 /// [`Entry API`]: BTreeMap::entry
115 ///
116 /// ```
117 /// use std::collections::BTreeMap;
118 ///
119 /// // type inference lets us omit an explicit type signature (which
120 /// // would be `BTreeMap<&str, u8>` in this example).
121 /// let mut player_stats = BTreeMap::new();
122 ///
123 /// fn random_stat_buff() -> u8 {
124 ///     // could actually return some random value here - let's just return
125 ///     // some fixed value for now
126 ///     42
127 /// }
128 ///
129 /// // insert a key only if it doesn't already exist
130 /// player_stats.entry("health").or_insert(100);
131 ///
132 /// // insert a key using a function that provides a new value only if it
133 /// // doesn't already exist
134 /// player_stats.entry("defence").or_insert_with(random_stat_buff);
135 ///
136 /// // update a key, guarding against the key possibly not being set
137 /// let stat = player_stats.entry("attack").or_insert(100);
138 /// *stat += random_stat_buff();
139 /// ```
140 #[stable(feature = "rust1", since = "1.0.0")]
141 pub struct BTreeMap<K, V> {
142     root: Option<Root<K, V>>,
143     length: usize,
144 }
145
146 #[stable(feature = "btree_drop", since = "1.7.0")]
147 unsafe impl<#[may_dangle] K, #[may_dangle] V> Drop for BTreeMap<K, V> {
148     fn drop(&mut self) {
149         unsafe {
150             drop(ptr::read(self).into_iter());
151         }
152     }
153 }
154
155 #[stable(feature = "rust1", since = "1.0.0")]
156 impl<K: Clone, V: Clone> Clone for BTreeMap<K, V> {
157     fn clone(&self) -> BTreeMap<K, V> {
158         fn clone_subtree<'a, K: Clone, V: Clone>(
159             node: NodeRef<marker::Immut<'a>, K, V, marker::LeafOrInternal>,
160         ) -> BTreeMap<K, V>
161         where
162             K: 'a,
163             V: 'a,
164         {
165             match node.force() {
166                 Leaf(leaf) => {
167                     let mut out_tree = BTreeMap { root: Some(Root::new()), length: 0 };
168
169                     {
170                         let root = out_tree.root.as_mut().unwrap(); // unwrap succeeds because we just wrapped
171                         let mut out_node = match root.borrow_mut().force() {
172                             Leaf(leaf) => leaf,
173                             Internal(_) => unreachable!(),
174                         };
175
176                         let mut in_edge = leaf.first_edge();
177                         while let Ok(kv) = in_edge.right_kv() {
178                             let (k, v) = kv.into_kv();
179                             in_edge = kv.right_edge();
180
181                             out_node.push(k.clone(), v.clone());
182                             out_tree.length += 1;
183                         }
184                     }
185
186                     out_tree
187                 }
188                 Internal(internal) => {
189                     let mut out_tree = clone_subtree(internal.first_edge().descend());
190
191                     {
192                         let out_root = BTreeMap::ensure_is_owned(&mut out_tree.root);
193                         let mut out_node = out_root.push_internal_level();
194                         let mut in_edge = internal.first_edge();
195                         while let Ok(kv) = in_edge.right_kv() {
196                             let (k, v) = kv.into_kv();
197                             in_edge = kv.right_edge();
198
199                             let k = (*k).clone();
200                             let v = (*v).clone();
201                             let subtree = clone_subtree(in_edge.descend());
202
203                             // We can't destructure subtree directly
204                             // because BTreeMap implements Drop
205                             let (subroot, sublength) = unsafe {
206                                 let subtree = ManuallyDrop::new(subtree);
207                                 let root = ptr::read(&subtree.root);
208                                 let length = subtree.length;
209                                 (root, length)
210                             };
211
212                             out_node.push(k, v, subroot.unwrap_or_else(Root::new));
213                             out_tree.length += 1 + sublength;
214                         }
215                     }
216
217                     out_tree
218                 }
219             }
220         }
221
222         if self.is_empty() {
223             // Ideally we'd call `BTreeMap::new` here, but that has the `K:
224             // Ord` constraint, which this method lacks.
225             BTreeMap { root: None, length: 0 }
226         } else {
227             clone_subtree(self.root.as_ref().unwrap().reborrow()) // unwrap succeeds because not empty
228         }
229     }
230 }
231
232 impl<K, Q: ?Sized> super::Recover<Q> for BTreeMap<K, ()>
233 where
234     K: Borrow<Q> + Ord,
235     Q: Ord,
236 {
237     type Key = K;
238
239     fn get(&self, key: &Q) -> Option<&K> {
240         let root_node = self.root.as_ref()?.reborrow();
241         match root_node.search_tree(key) {
242             Found(handle) => Some(handle.into_kv().0),
243             GoDown(_) => None,
244         }
245     }
246
247     fn take(&mut self, key: &Q) -> Option<K> {
248         let (map, dormant_map) = DormantMutRef::new(self);
249         let root_node = map.root.as_mut()?.borrow_mut();
250         match root_node.search_tree(key) {
251             Found(handle) => {
252                 Some(OccupiedEntry { handle, dormant_map, _marker: PhantomData }.remove_kv().0)
253             }
254             GoDown(_) => None,
255         }
256     }
257
258     fn replace(&mut self, key: K) -> Option<K> {
259         let (map, dormant_map) = DormantMutRef::new(self);
260         let root_node = Self::ensure_is_owned(&mut map.root).borrow_mut();
261         match root_node.search_tree::<K>(&key) {
262             Found(mut kv) => Some(mem::replace(kv.key_mut(), key)),
263             GoDown(handle) => {
264                 VacantEntry { key, handle, dormant_map, _marker: PhantomData }.insert(());
265                 None
266             }
267         }
268     }
269 }
270
271 /// An iterator over the entries of a `BTreeMap`.
272 ///
273 /// This `struct` is created by the [`iter`] method on [`BTreeMap`]. See its
274 /// documentation for more.
275 ///
276 /// [`iter`]: BTreeMap::iter
277 #[stable(feature = "rust1", since = "1.0.0")]
278 pub struct Iter<'a, K: 'a, V: 'a> {
279     range: Range<'a, K, V>,
280     length: usize,
281 }
282
283 #[stable(feature = "collection_debug", since = "1.17.0")]
284 impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for Iter<'_, K, V> {
285     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
286         f.debug_list().entries(self.clone()).finish()
287     }
288 }
289
290 /// A mutable iterator over the entries of a `BTreeMap`.
291 ///
292 /// This `struct` is created by the [`iter_mut`] method on [`BTreeMap`]. See its
293 /// documentation for more.
294 ///
295 /// [`iter_mut`]: BTreeMap::iter_mut
296 #[stable(feature = "rust1", since = "1.0.0")]
297 #[derive(Debug)]
298 pub struct IterMut<'a, K: 'a, V: 'a> {
299     range: RangeMut<'a, K, V>,
300     length: usize,
301 }
302
303 /// An owning iterator over the entries of a `BTreeMap`.
304 ///
305 /// This `struct` is created by the [`into_iter`] method on [`BTreeMap`]
306 /// (provided by the `IntoIterator` trait). See its documentation for more.
307 ///
308 /// [`into_iter`]: IntoIterator::into_iter
309 #[stable(feature = "rust1", since = "1.0.0")]
310 pub struct IntoIter<K, V> {
311     front: Option<Handle<NodeRef<marker::Owned, K, V, marker::Leaf>, marker::Edge>>,
312     back: Option<Handle<NodeRef<marker::Owned, K, V, marker::Leaf>, marker::Edge>>,
313     length: usize,
314 }
315
316 impl<K, V> IntoIter<K, V> {
317     /// Returns an iterator of references over the remaining items.
318     #[inline]
319     pub(super) fn iter(&self) -> Iter<'_, K, V> {
320         let range = Range {
321             front: self.front.as_ref().map(|f| f.reborrow()),
322             back: self.back.as_ref().map(|b| b.reborrow()),
323         };
324
325         Iter { range: range, length: self.length }
326     }
327 }
328
329 #[stable(feature = "collection_debug", since = "1.17.0")]
330 impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for IntoIter<K, V> {
331     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
332         f.debug_list().entries(self.iter()).finish()
333     }
334 }
335
336 /// An iterator over the keys of a `BTreeMap`.
337 ///
338 /// This `struct` is created by the [`keys`] method on [`BTreeMap`]. See its
339 /// documentation for more.
340 ///
341 /// [`keys`]: BTreeMap::keys
342 #[stable(feature = "rust1", since = "1.0.0")]
343 pub struct Keys<'a, K: 'a, V: 'a> {
344     inner: Iter<'a, K, V>,
345 }
346
347 #[stable(feature = "collection_debug", since = "1.17.0")]
348 impl<K: fmt::Debug, V> fmt::Debug for Keys<'_, K, V> {
349     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
350         f.debug_list().entries(self.clone()).finish()
351     }
352 }
353
354 /// An iterator over the values of a `BTreeMap`.
355 ///
356 /// This `struct` is created by the [`values`] method on [`BTreeMap`]. See its
357 /// documentation for more.
358 ///
359 /// [`values`]: BTreeMap::values
360 #[stable(feature = "rust1", since = "1.0.0")]
361 pub struct Values<'a, K: 'a, V: 'a> {
362     inner: Iter<'a, K, V>,
363 }
364
365 #[stable(feature = "collection_debug", since = "1.17.0")]
366 impl<K, V: fmt::Debug> fmt::Debug for Values<'_, K, V> {
367     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
368         f.debug_list().entries(self.clone()).finish()
369     }
370 }
371
372 /// A mutable iterator over the values of a `BTreeMap`.
373 ///
374 /// This `struct` is created by the [`values_mut`] method on [`BTreeMap`]. See its
375 /// documentation for more.
376 ///
377 /// [`values_mut`]: BTreeMap::values_mut
378 #[stable(feature = "map_values_mut", since = "1.10.0")]
379 pub struct ValuesMut<'a, K: 'a, V: 'a> {
380     inner: IterMut<'a, K, V>,
381 }
382
383 #[stable(feature = "map_values_mut", since = "1.10.0")]
384 impl<K, V: fmt::Debug> fmt::Debug for ValuesMut<'_, K, V> {
385     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
386         f.debug_list().entries(self.inner.iter().map(|(_, val)| val)).finish()
387     }
388 }
389
390 /// An owning iterator over the keys of a `BTreeMap`.
391 ///
392 /// This `struct` is created by the [`into_keys`] method on [`BTreeMap`].
393 /// See its documentation for more.
394 ///
395 /// [`into_keys`]: BTreeMap::into_keys
396 #[unstable(feature = "map_into_keys_values", issue = "75294")]
397 pub struct IntoKeys<K, V> {
398     inner: IntoIter<K, V>,
399 }
400
401 #[unstable(feature = "map_into_keys_values", issue = "75294")]
402 impl<K: fmt::Debug, V> fmt::Debug for IntoKeys<K, V> {
403     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
404         f.debug_list().entries(self.inner.iter().map(|(key, _)| key)).finish()
405     }
406 }
407
408 /// An owning iterator over the values of a `BTreeMap`.
409 ///
410 /// This `struct` is created by the [`into_values`] method on [`BTreeMap`].
411 /// See its documentation for more.
412 ///
413 /// [`into_values`]: BTreeMap::into_values
414 #[unstable(feature = "map_into_keys_values", issue = "75294")]
415 pub struct IntoValues<K, V> {
416     inner: IntoIter<K, V>,
417 }
418
419 #[unstable(feature = "map_into_keys_values", issue = "75294")]
420 impl<K, V: fmt::Debug> fmt::Debug for IntoValues<K, V> {
421     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
422         f.debug_list().entries(self.inner.iter().map(|(_, val)| val)).finish()
423     }
424 }
425
426 /// An iterator over a sub-range of entries in a `BTreeMap`.
427 ///
428 /// This `struct` is created by the [`range`] method on [`BTreeMap`]. See its
429 /// documentation for more.
430 ///
431 /// [`range`]: BTreeMap::range
432 #[stable(feature = "btree_range", since = "1.17.0")]
433 pub struct Range<'a, K: 'a, V: 'a> {
434     front: Option<Handle<NodeRef<marker::Immut<'a>, K, V, marker::Leaf>, marker::Edge>>,
435     back: Option<Handle<NodeRef<marker::Immut<'a>, K, V, marker::Leaf>, marker::Edge>>,
436 }
437
438 #[stable(feature = "collection_debug", since = "1.17.0")]
439 impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for Range<'_, K, V> {
440     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
441         f.debug_list().entries(self.clone()).finish()
442     }
443 }
444
445 /// A mutable iterator over a sub-range of entries in a `BTreeMap`.
446 ///
447 /// This `struct` is created by the [`range_mut`] method on [`BTreeMap`]. See its
448 /// documentation for more.
449 ///
450 /// [`range_mut`]: BTreeMap::range_mut
451 #[stable(feature = "btree_range", since = "1.17.0")]
452 pub struct RangeMut<'a, K: 'a, V: 'a> {
453     front: Option<Handle<NodeRef<marker::ValMut<'a>, K, V, marker::Leaf>, marker::Edge>>,
454     back: Option<Handle<NodeRef<marker::ValMut<'a>, K, V, marker::Leaf>, marker::Edge>>,
455
456     // Be invariant in `K` and `V`
457     _marker: PhantomData<&'a mut (K, V)>,
458 }
459
460 #[stable(feature = "collection_debug", since = "1.17.0")]
461 impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for RangeMut<'_, K, V> {
462     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
463         let range = Range {
464             front: self.front.as_ref().map(|f| f.reborrow()),
465             back: self.back.as_ref().map(|b| b.reborrow()),
466         };
467         f.debug_list().entries(range).finish()
468     }
469 }
470
471 impl<K: Ord, V> BTreeMap<K, V> {
472     /// Makes a new, empty `BTreeMap`.
473     ///
474     /// Does not allocate anything on its own.
475     ///
476     /// # Examples
477     ///
478     /// Basic usage:
479     ///
480     /// ```
481     /// use std::collections::BTreeMap;
482     ///
483     /// let mut map = BTreeMap::new();
484     ///
485     /// // entries can now be inserted into the empty map
486     /// map.insert(1, "a");
487     /// ```
488     #[stable(feature = "rust1", since = "1.0.0")]
489     #[rustc_const_unstable(feature = "const_btree_new", issue = "71835")]
490     pub const fn new() -> BTreeMap<K, V> {
491         BTreeMap { root: None, length: 0 }
492     }
493
494     /// Clears the map, removing all elements.
495     ///
496     /// # Examples
497     ///
498     /// Basic usage:
499     ///
500     /// ```
501     /// use std::collections::BTreeMap;
502     ///
503     /// let mut a = BTreeMap::new();
504     /// a.insert(1, "a");
505     /// a.clear();
506     /// assert!(a.is_empty());
507     /// ```
508     #[stable(feature = "rust1", since = "1.0.0")]
509     pub fn clear(&mut self) {
510         *self = BTreeMap::new();
511     }
512
513     /// Returns a reference to the value corresponding to the key.
514     ///
515     /// The key may be any borrowed form of the map's key type, but the ordering
516     /// on the borrowed form *must* match the ordering on the key type.
517     ///
518     /// # Examples
519     ///
520     /// Basic usage:
521     ///
522     /// ```
523     /// use std::collections::BTreeMap;
524     ///
525     /// let mut map = BTreeMap::new();
526     /// map.insert(1, "a");
527     /// assert_eq!(map.get(&1), Some(&"a"));
528     /// assert_eq!(map.get(&2), None);
529     /// ```
530     #[stable(feature = "rust1", since = "1.0.0")]
531     pub fn get<Q: ?Sized>(&self, key: &Q) -> Option<&V>
532     where
533         K: Borrow<Q>,
534         Q: Ord,
535     {
536         let root_node = self.root.as_ref()?.reborrow();
537         match root_node.search_tree(key) {
538             Found(handle) => Some(handle.into_kv().1),
539             GoDown(_) => None,
540         }
541     }
542
543     /// Returns the key-value pair corresponding to the supplied key.
544     ///
545     /// The supplied key may be any borrowed form of the map's key type, but the ordering
546     /// on the borrowed form *must* match the ordering on the key type.
547     ///
548     /// # Examples
549     ///
550     /// ```
551     /// use std::collections::BTreeMap;
552     ///
553     /// let mut map = BTreeMap::new();
554     /// map.insert(1, "a");
555     /// assert_eq!(map.get_key_value(&1), Some((&1, &"a")));
556     /// assert_eq!(map.get_key_value(&2), None);
557     /// ```
558     #[stable(feature = "map_get_key_value", since = "1.40.0")]
559     pub fn get_key_value<Q: ?Sized>(&self, k: &Q) -> Option<(&K, &V)>
560     where
561         K: Borrow<Q>,
562         Q: Ord,
563     {
564         let root_node = self.root.as_ref()?.reborrow();
565         match root_node.search_tree(k) {
566             Found(handle) => Some(handle.into_kv()),
567             GoDown(_) => None,
568         }
569     }
570
571     /// Returns the first key-value pair in the map.
572     /// The key in this pair is the minimum key in the map.
573     ///
574     /// # Examples
575     ///
576     /// Basic usage:
577     ///
578     /// ```
579     /// #![feature(map_first_last)]
580     /// use std::collections::BTreeMap;
581     ///
582     /// let mut map = BTreeMap::new();
583     /// assert_eq!(map.first_key_value(), None);
584     /// map.insert(1, "b");
585     /// map.insert(2, "a");
586     /// assert_eq!(map.first_key_value(), Some((&1, &"b")));
587     /// ```
588     #[unstable(feature = "map_first_last", issue = "62924")]
589     pub fn first_key_value(&self) -> Option<(&K, &V)> {
590         let root_node = self.root.as_ref()?.reborrow();
591         root_node.first_leaf_edge().right_kv().ok().map(Handle::into_kv)
592     }
593
594     /// Returns the first entry in the map for in-place manipulation.
595     /// The key of this entry is the minimum key in the map.
596     ///
597     /// # Examples
598     ///
599     /// ```
600     /// #![feature(map_first_last)]
601     /// use std::collections::BTreeMap;
602     ///
603     /// let mut map = BTreeMap::new();
604     /// map.insert(1, "a");
605     /// map.insert(2, "b");
606     /// if let Some(mut entry) = map.first_entry() {
607     ///     if *entry.key() > 0 {
608     ///         entry.insert("first");
609     ///     }
610     /// }
611     /// assert_eq!(*map.get(&1).unwrap(), "first");
612     /// assert_eq!(*map.get(&2).unwrap(), "b");
613     /// ```
614     #[unstable(feature = "map_first_last", issue = "62924")]
615     pub fn first_entry(&mut self) -> Option<OccupiedEntry<'_, K, V>> {
616         let (map, dormant_map) = DormantMutRef::new(self);
617         let root_node = map.root.as_mut()?.borrow_mut();
618         let kv = root_node.first_leaf_edge().right_kv().ok()?;
619         Some(OccupiedEntry { handle: kv.forget_node_type(), dormant_map, _marker: PhantomData })
620     }
621
622     /// Removes and returns the first element in the map.
623     /// The key of this element is the minimum key that was in the map.
624     ///
625     /// # Examples
626     ///
627     /// Draining elements in ascending order, while keeping a usable map each iteration.
628     ///
629     /// ```
630     /// #![feature(map_first_last)]
631     /// use std::collections::BTreeMap;
632     ///
633     /// let mut map = BTreeMap::new();
634     /// map.insert(1, "a");
635     /// map.insert(2, "b");
636     /// while let Some((key, _val)) = map.pop_first() {
637     ///     assert!(map.iter().all(|(k, _v)| *k > key));
638     /// }
639     /// assert!(map.is_empty());
640     /// ```
641     #[unstable(feature = "map_first_last", issue = "62924")]
642     pub fn pop_first(&mut self) -> Option<(K, V)> {
643         self.first_entry().map(|entry| entry.remove_entry())
644     }
645
646     /// Returns the last key-value pair in the map.
647     /// The key in this pair is the maximum key in the map.
648     ///
649     /// # Examples
650     ///
651     /// Basic usage:
652     ///
653     /// ```
654     /// #![feature(map_first_last)]
655     /// use std::collections::BTreeMap;
656     ///
657     /// let mut map = BTreeMap::new();
658     /// map.insert(1, "b");
659     /// map.insert(2, "a");
660     /// assert_eq!(map.last_key_value(), Some((&2, &"a")));
661     /// ```
662     #[unstable(feature = "map_first_last", issue = "62924")]
663     pub fn last_key_value(&self) -> Option<(&K, &V)> {
664         let root_node = self.root.as_ref()?.reborrow();
665         root_node.last_leaf_edge().left_kv().ok().map(Handle::into_kv)
666     }
667
668     /// Returns the last entry in the map for in-place manipulation.
669     /// The key of this entry is the maximum key in the map.
670     ///
671     /// # Examples
672     ///
673     /// ```
674     /// #![feature(map_first_last)]
675     /// use std::collections::BTreeMap;
676     ///
677     /// let mut map = BTreeMap::new();
678     /// map.insert(1, "a");
679     /// map.insert(2, "b");
680     /// if let Some(mut entry) = map.last_entry() {
681     ///     if *entry.key() > 0 {
682     ///         entry.insert("last");
683     ///     }
684     /// }
685     /// assert_eq!(*map.get(&1).unwrap(), "a");
686     /// assert_eq!(*map.get(&2).unwrap(), "last");
687     /// ```
688     #[unstable(feature = "map_first_last", issue = "62924")]
689     pub fn last_entry(&mut self) -> Option<OccupiedEntry<'_, K, V>> {
690         let (map, dormant_map) = DormantMutRef::new(self);
691         let root_node = map.root.as_mut()?.borrow_mut();
692         let kv = root_node.last_leaf_edge().left_kv().ok()?;
693         Some(OccupiedEntry { handle: kv.forget_node_type(), dormant_map, _marker: PhantomData })
694     }
695
696     /// Removes and returns the last element in the map.
697     /// The key of this element is the maximum key that was in the map.
698     ///
699     /// # Examples
700     ///
701     /// Draining elements in descending order, while keeping a usable map each iteration.
702     ///
703     /// ```
704     /// #![feature(map_first_last)]
705     /// use std::collections::BTreeMap;
706     ///
707     /// let mut map = BTreeMap::new();
708     /// map.insert(1, "a");
709     /// map.insert(2, "b");
710     /// while let Some((key, _val)) = map.pop_last() {
711     ///     assert!(map.iter().all(|(k, _v)| *k < key));
712     /// }
713     /// assert!(map.is_empty());
714     /// ```
715     #[unstable(feature = "map_first_last", issue = "62924")]
716     pub fn pop_last(&mut self) -> Option<(K, V)> {
717         self.last_entry().map(|entry| entry.remove_entry())
718     }
719
720     /// Returns `true` if the map contains a value for the specified key.
721     ///
722     /// The key may be any borrowed form of the map's key type, but the ordering
723     /// on the borrowed form *must* match the ordering on the key type.
724     ///
725     /// # Examples
726     ///
727     /// Basic usage:
728     ///
729     /// ```
730     /// use std::collections::BTreeMap;
731     ///
732     /// let mut map = BTreeMap::new();
733     /// map.insert(1, "a");
734     /// assert_eq!(map.contains_key(&1), true);
735     /// assert_eq!(map.contains_key(&2), false);
736     /// ```
737     #[stable(feature = "rust1", since = "1.0.0")]
738     pub fn contains_key<Q: ?Sized>(&self, key: &Q) -> bool
739     where
740         K: Borrow<Q>,
741         Q: Ord,
742     {
743         self.get(key).is_some()
744     }
745
746     /// Returns a mutable reference to the value corresponding to the key.
747     ///
748     /// The key may be any borrowed form of the map's key type, but the ordering
749     /// on the borrowed form *must* match the ordering on the key type.
750     ///
751     /// # Examples
752     ///
753     /// Basic usage:
754     ///
755     /// ```
756     /// use std::collections::BTreeMap;
757     ///
758     /// let mut map = BTreeMap::new();
759     /// map.insert(1, "a");
760     /// if let Some(x) = map.get_mut(&1) {
761     ///     *x = "b";
762     /// }
763     /// assert_eq!(map[&1], "b");
764     /// ```
765     // See `get` for implementation notes, this is basically a copy-paste with mut's added
766     #[stable(feature = "rust1", since = "1.0.0")]
767     pub fn get_mut<Q: ?Sized>(&mut self, key: &Q) -> Option<&mut V>
768     where
769         K: Borrow<Q>,
770         Q: Ord,
771     {
772         let root_node = self.root.as_mut()?.borrow_mut();
773         match root_node.search_tree(key) {
774             Found(handle) => Some(handle.into_val_mut()),
775             GoDown(_) => None,
776         }
777     }
778
779     /// Inserts a key-value pair into the map.
780     ///
781     /// If the map did not have this key present, `None` is returned.
782     ///
783     /// If the map did have this key present, the value is updated, and the old
784     /// value is returned. The key is not updated, though; this matters for
785     /// types that can be `==` without being identical. See the [module-level
786     /// documentation] for more.
787     ///
788     /// [module-level documentation]: index.html#insert-and-complex-keys
789     ///
790     /// # Examples
791     ///
792     /// Basic usage:
793     ///
794     /// ```
795     /// use std::collections::BTreeMap;
796     ///
797     /// let mut map = BTreeMap::new();
798     /// assert_eq!(map.insert(37, "a"), None);
799     /// assert_eq!(map.is_empty(), false);
800     ///
801     /// map.insert(37, "b");
802     /// assert_eq!(map.insert(37, "c"), Some("b"));
803     /// assert_eq!(map[&37], "c");
804     /// ```
805     #[stable(feature = "rust1", since = "1.0.0")]
806     pub fn insert(&mut self, key: K, value: V) -> Option<V> {
807         match self.entry(key) {
808             Occupied(mut entry) => Some(entry.insert(value)),
809             Vacant(entry) => {
810                 entry.insert(value);
811                 None
812             }
813         }
814     }
815
816     /// Removes a key from the map, returning the value at the key if the key
817     /// was previously in the map.
818     ///
819     /// The key may be any borrowed form of the map's key type, but the ordering
820     /// on the borrowed form *must* match the ordering on the key type.
821     ///
822     /// # Examples
823     ///
824     /// Basic usage:
825     ///
826     /// ```
827     /// use std::collections::BTreeMap;
828     ///
829     /// let mut map = BTreeMap::new();
830     /// map.insert(1, "a");
831     /// assert_eq!(map.remove(&1), Some("a"));
832     /// assert_eq!(map.remove(&1), None);
833     /// ```
834     #[stable(feature = "rust1", since = "1.0.0")]
835     pub fn remove<Q: ?Sized>(&mut self, key: &Q) -> Option<V>
836     where
837         K: Borrow<Q>,
838         Q: Ord,
839     {
840         self.remove_entry(key).map(|(_, v)| v)
841     }
842
843     /// Removes a key from the map, returning the stored key and value if the key
844     /// was previously in the map.
845     ///
846     /// The key may be any borrowed form of the map's key type, but the ordering
847     /// on the borrowed form *must* match the ordering on the key type.
848     ///
849     /// # Examples
850     ///
851     /// Basic usage:
852     ///
853     /// ```
854     /// use std::collections::BTreeMap;
855     ///
856     /// let mut map = BTreeMap::new();
857     /// map.insert(1, "a");
858     /// assert_eq!(map.remove_entry(&1), Some((1, "a")));
859     /// assert_eq!(map.remove_entry(&1), None);
860     /// ```
861     #[stable(feature = "btreemap_remove_entry", since = "1.45.0")]
862     pub fn remove_entry<Q: ?Sized>(&mut self, key: &Q) -> Option<(K, V)>
863     where
864         K: Borrow<Q>,
865         Q: Ord,
866     {
867         let (map, dormant_map) = DormantMutRef::new(self);
868         let root_node = map.root.as_mut()?.borrow_mut();
869         match root_node.search_tree(key) {
870             Found(handle) => {
871                 Some(OccupiedEntry { handle, dormant_map, _marker: PhantomData }.remove_entry())
872             }
873             GoDown(_) => None,
874         }
875     }
876
877     /// Retains only the elements specified by the predicate.
878     ///
879     /// In other words, remove all pairs `(k, v)` such that `f(&k, &mut v)` returns `false`.
880     ///
881     /// # Examples
882     ///
883     /// ```
884     /// #![feature(btree_retain)]
885     /// use std::collections::BTreeMap;
886     ///
887     /// let mut map: BTreeMap<i32, i32> = (0..8).map(|x| (x, x*10)).collect();
888     /// // Keep only the elements with even-numbered keys.
889     /// map.retain(|&k, _| k % 2 == 0);
890     /// assert!(map.into_iter().eq(vec![(0, 0), (2, 20), (4, 40), (6, 60)]));
891     /// ```
892     #[inline]
893     #[unstable(feature = "btree_retain", issue = "79025")]
894     pub fn retain<F>(&mut self, mut f: F)
895     where
896         F: FnMut(&K, &mut V) -> bool,
897     {
898         self.drain_filter(|k, v| !f(k, v));
899     }
900
901     /// Moves all elements from `other` into `Self`, leaving `other` empty.
902     ///
903     /// # Examples
904     ///
905     /// ```
906     /// use std::collections::BTreeMap;
907     ///
908     /// let mut a = BTreeMap::new();
909     /// a.insert(1, "a");
910     /// a.insert(2, "b");
911     /// a.insert(3, "c");
912     ///
913     /// let mut b = BTreeMap::new();
914     /// b.insert(3, "d");
915     /// b.insert(4, "e");
916     /// b.insert(5, "f");
917     ///
918     /// a.append(&mut b);
919     ///
920     /// assert_eq!(a.len(), 5);
921     /// assert_eq!(b.len(), 0);
922     ///
923     /// assert_eq!(a[&1], "a");
924     /// assert_eq!(a[&2], "b");
925     /// assert_eq!(a[&3], "d");
926     /// assert_eq!(a[&4], "e");
927     /// assert_eq!(a[&5], "f");
928     /// ```
929     #[stable(feature = "btree_append", since = "1.11.0")]
930     pub fn append(&mut self, other: &mut Self) {
931         // Do we have to append anything at all?
932         if other.is_empty() {
933             return;
934         }
935
936         // We can just swap `self` and `other` if `self` is empty.
937         if self.is_empty() {
938             mem::swap(self, other);
939             return;
940         }
941
942         let self_iter = mem::take(self).into_iter();
943         let other_iter = mem::take(other).into_iter();
944         let root = BTreeMap::ensure_is_owned(&mut self.root);
945         root.append_from_sorted_iters(self_iter, other_iter, &mut self.length)
946     }
947
948     /// Constructs a double-ended iterator over a sub-range of elements in the map.
949     /// The simplest way is to use the range syntax `min..max`, thus `range(min..max)` will
950     /// yield elements from min (inclusive) to max (exclusive).
951     /// The range may also be entered as `(Bound<T>, Bound<T>)`, so for example
952     /// `range((Excluded(4), Included(10)))` will yield a left-exclusive, right-inclusive
953     /// range from 4 to 10.
954     ///
955     /// # Panics
956     ///
957     /// Panics if range `start > end`.
958     /// Panics if range `start == end` and both bounds are `Excluded`.
959     ///
960     /// # Examples
961     ///
962     /// Basic usage:
963     ///
964     /// ```
965     /// use std::collections::BTreeMap;
966     /// use std::ops::Bound::Included;
967     ///
968     /// let mut map = BTreeMap::new();
969     /// map.insert(3, "a");
970     /// map.insert(5, "b");
971     /// map.insert(8, "c");
972     /// for (&key, &value) in map.range((Included(&4), Included(&8))) {
973     ///     println!("{}: {}", key, value);
974     /// }
975     /// assert_eq!(Some((&5, &"b")), map.range(4..).next());
976     /// ```
977     #[stable(feature = "btree_range", since = "1.17.0")]
978     pub fn range<T: ?Sized, R>(&self, range: R) -> Range<'_, K, V>
979     where
980         T: Ord,
981         K: Borrow<T>,
982         R: RangeBounds<T>,
983     {
984         if let Some(root) = &self.root {
985             let (f, b) = root.reborrow().range_search(range);
986
987             Range { front: Some(f), back: Some(b) }
988         } else {
989             Range { front: None, back: None }
990         }
991     }
992
993     /// Constructs a mutable double-ended iterator over a sub-range of elements in the map.
994     /// The simplest way is to use the range syntax `min..max`, thus `range(min..max)` will
995     /// yield elements from min (inclusive) to max (exclusive).
996     /// The range may also be entered as `(Bound<T>, Bound<T>)`, so for example
997     /// `range((Excluded(4), Included(10)))` will yield a left-exclusive, right-inclusive
998     /// range from 4 to 10.
999     ///
1000     /// # Panics
1001     ///
1002     /// Panics if range `start > end`.
1003     /// Panics if range `start == end` and both bounds are `Excluded`.
1004     ///
1005     /// # Examples
1006     ///
1007     /// Basic usage:
1008     ///
1009     /// ```
1010     /// use std::collections::BTreeMap;
1011     ///
1012     /// let mut map: BTreeMap<&str, i32> = ["Alice", "Bob", "Carol", "Cheryl"]
1013     ///     .iter()
1014     ///     .map(|&s| (s, 0))
1015     ///     .collect();
1016     /// for (_, balance) in map.range_mut("B".."Cheryl") {
1017     ///     *balance += 100;
1018     /// }
1019     /// for (name, balance) in &map {
1020     ///     println!("{} => {}", name, balance);
1021     /// }
1022     /// ```
1023     #[stable(feature = "btree_range", since = "1.17.0")]
1024     pub fn range_mut<T: ?Sized, R>(&mut self, range: R) -> RangeMut<'_, K, V>
1025     where
1026         T: Ord,
1027         K: Borrow<T>,
1028         R: RangeBounds<T>,
1029     {
1030         if let Some(root) = &mut self.root {
1031             let (f, b) = root.borrow_valmut().range_search(range);
1032
1033             RangeMut { front: Some(f), back: Some(b), _marker: PhantomData }
1034         } else {
1035             RangeMut { front: None, back: None, _marker: PhantomData }
1036         }
1037     }
1038
1039     /// Gets the given key's corresponding entry in the map for in-place manipulation.
1040     ///
1041     /// # Examples
1042     ///
1043     /// Basic usage:
1044     ///
1045     /// ```
1046     /// use std::collections::BTreeMap;
1047     ///
1048     /// let mut count: BTreeMap<&str, usize> = BTreeMap::new();
1049     ///
1050     /// // count the number of occurrences of letters in the vec
1051     /// for x in vec!["a", "b", "a", "c", "a", "b"] {
1052     ///     *count.entry(x).or_insert(0) += 1;
1053     /// }
1054     ///
1055     /// assert_eq!(count["a"], 3);
1056     /// ```
1057     #[stable(feature = "rust1", since = "1.0.0")]
1058     pub fn entry(&mut self, key: K) -> Entry<'_, K, V> {
1059         // FIXME(@porglezomp) Avoid allocating if we don't insert
1060         let (map, dormant_map) = DormantMutRef::new(self);
1061         let root_node = Self::ensure_is_owned(&mut map.root).borrow_mut();
1062         match root_node.search_tree(&key) {
1063             Found(handle) => Occupied(OccupiedEntry { handle, dormant_map, _marker: PhantomData }),
1064             GoDown(handle) => {
1065                 Vacant(VacantEntry { key, handle, dormant_map, _marker: PhantomData })
1066             }
1067         }
1068     }
1069
1070     /// Splits the collection into two at the given key. Returns everything after the given key,
1071     /// including the key.
1072     ///
1073     /// # Examples
1074     ///
1075     /// Basic usage:
1076     ///
1077     /// ```
1078     /// use std::collections::BTreeMap;
1079     ///
1080     /// let mut a = BTreeMap::new();
1081     /// a.insert(1, "a");
1082     /// a.insert(2, "b");
1083     /// a.insert(3, "c");
1084     /// a.insert(17, "d");
1085     /// a.insert(41, "e");
1086     ///
1087     /// let b = a.split_off(&3);
1088     ///
1089     /// assert_eq!(a.len(), 2);
1090     /// assert_eq!(b.len(), 3);
1091     ///
1092     /// assert_eq!(a[&1], "a");
1093     /// assert_eq!(a[&2], "b");
1094     ///
1095     /// assert_eq!(b[&3], "c");
1096     /// assert_eq!(b[&17], "d");
1097     /// assert_eq!(b[&41], "e");
1098     /// ```
1099     #[stable(feature = "btree_split_off", since = "1.11.0")]
1100     pub fn split_off<Q: ?Sized + Ord>(&mut self, key: &Q) -> Self
1101     where
1102         K: Borrow<Q>,
1103     {
1104         if self.is_empty() {
1105             return Self::new();
1106         }
1107
1108         let total_num = self.len();
1109         let left_root = self.root.as_mut().unwrap(); // unwrap succeeds because not empty
1110
1111         let right_root = left_root.split_off(key);
1112
1113         let (new_left_len, right_len) = Root::calc_split_length(total_num, &left_root, &right_root);
1114         self.length = new_left_len;
1115
1116         BTreeMap { root: Some(right_root), length: right_len }
1117     }
1118
1119     /// Creates an iterator which uses a closure to determine if an element should be removed.
1120     ///
1121     /// If the closure returns true, the element is removed from the map and yielded.
1122     /// If the closure returns false, or panics, the element remains in the map and will not be
1123     /// yielded.
1124     ///
1125     /// Note that `drain_filter` lets you mutate every value in the filter closure, regardless of
1126     /// whether you choose to keep or remove it.
1127     ///
1128     /// If the iterator is only partially consumed or not consumed at all, each of the remaining
1129     /// elements will still be subjected to the closure and removed and dropped if it returns true.
1130     ///
1131     /// It is unspecified how many more elements will be subjected to the closure
1132     /// if a panic occurs in the closure, or a panic occurs while dropping an element,
1133     /// or if the `DrainFilter` value is leaked.
1134     ///
1135     /// # Examples
1136     ///
1137     /// Splitting a map into even and odd keys, reusing the original map:
1138     ///
1139     /// ```
1140     /// #![feature(btree_drain_filter)]
1141     /// use std::collections::BTreeMap;
1142     ///
1143     /// let mut map: BTreeMap<i32, i32> = (0..8).map(|x| (x, x)).collect();
1144     /// let evens: BTreeMap<_, _> = map.drain_filter(|k, _v| k % 2 == 0).collect();
1145     /// let odds = map;
1146     /// assert_eq!(evens.keys().copied().collect::<Vec<_>>(), vec![0, 2, 4, 6]);
1147     /// assert_eq!(odds.keys().copied().collect::<Vec<_>>(), vec![1, 3, 5, 7]);
1148     /// ```
1149     #[unstable(feature = "btree_drain_filter", issue = "70530")]
1150     pub fn drain_filter<F>(&mut self, pred: F) -> DrainFilter<'_, K, V, F>
1151     where
1152         F: FnMut(&K, &mut V) -> bool,
1153     {
1154         DrainFilter { pred, inner: self.drain_filter_inner() }
1155     }
1156
1157     pub(super) fn drain_filter_inner(&mut self) -> DrainFilterInner<'_, K, V> {
1158         if let Some(root) = self.root.as_mut() {
1159             let (root, dormant_root) = DormantMutRef::new(root);
1160             let front = root.borrow_mut().first_leaf_edge();
1161             DrainFilterInner {
1162                 length: &mut self.length,
1163                 dormant_root: Some(dormant_root),
1164                 cur_leaf_edge: Some(front),
1165             }
1166         } else {
1167             DrainFilterInner { length: &mut self.length, dormant_root: None, cur_leaf_edge: None }
1168         }
1169     }
1170
1171     /// Creates a consuming iterator visiting all the keys, in sorted order.
1172     /// The map cannot be used after calling this.
1173     /// The iterator element type is `K`.
1174     ///
1175     /// # Examples
1176     ///
1177     /// ```
1178     /// #![feature(map_into_keys_values)]
1179     /// use std::collections::BTreeMap;
1180     ///
1181     /// let mut a = BTreeMap::new();
1182     /// a.insert(2, "b");
1183     /// a.insert(1, "a");
1184     ///
1185     /// let keys: Vec<i32> = a.into_keys().collect();
1186     /// assert_eq!(keys, [1, 2]);
1187     /// ```
1188     #[inline]
1189     #[unstable(feature = "map_into_keys_values", issue = "75294")]
1190     pub fn into_keys(self) -> IntoKeys<K, V> {
1191         IntoKeys { inner: self.into_iter() }
1192     }
1193
1194     /// Creates a consuming iterator visiting all the values, in order by key.
1195     /// The map cannot be used after calling this.
1196     /// The iterator element type is `V`.
1197     ///
1198     /// # Examples
1199     ///
1200     /// ```
1201     /// #![feature(map_into_keys_values)]
1202     /// use std::collections::BTreeMap;
1203     ///
1204     /// let mut a = BTreeMap::new();
1205     /// a.insert(1, "hello");
1206     /// a.insert(2, "goodbye");
1207     ///
1208     /// let values: Vec<&str> = a.into_values().collect();
1209     /// assert_eq!(values, ["hello", "goodbye"]);
1210     /// ```
1211     #[inline]
1212     #[unstable(feature = "map_into_keys_values", issue = "75294")]
1213     pub fn into_values(self) -> IntoValues<K, V> {
1214         IntoValues { inner: self.into_iter() }
1215     }
1216 }
1217
1218 #[stable(feature = "rust1", since = "1.0.0")]
1219 impl<'a, K, V> IntoIterator for &'a BTreeMap<K, V> {
1220     type Item = (&'a K, &'a V);
1221     type IntoIter = Iter<'a, K, V>;
1222
1223     fn into_iter(self) -> Iter<'a, K, V> {
1224         self.iter()
1225     }
1226 }
1227
1228 #[stable(feature = "rust1", since = "1.0.0")]
1229 impl<'a, K: 'a, V: 'a> Iterator for Iter<'a, K, V> {
1230     type Item = (&'a K, &'a V);
1231
1232     fn next(&mut self) -> Option<(&'a K, &'a V)> {
1233         if self.length == 0 {
1234             None
1235         } else {
1236             self.length -= 1;
1237             unsafe { Some(self.range.next_unchecked()) }
1238         }
1239     }
1240
1241     fn size_hint(&self) -> (usize, Option<usize>) {
1242         (self.length, Some(self.length))
1243     }
1244
1245     fn last(mut self) -> Option<(&'a K, &'a V)> {
1246         self.next_back()
1247     }
1248
1249     fn min(mut self) -> Option<(&'a K, &'a V)> {
1250         self.next()
1251     }
1252
1253     fn max(mut self) -> Option<(&'a K, &'a V)> {
1254         self.next_back()
1255     }
1256 }
1257
1258 #[stable(feature = "fused", since = "1.26.0")]
1259 impl<K, V> FusedIterator for Iter<'_, K, V> {}
1260
1261 #[stable(feature = "rust1", since = "1.0.0")]
1262 impl<'a, K: 'a, V: 'a> DoubleEndedIterator for Iter<'a, K, V> {
1263     fn next_back(&mut self) -> Option<(&'a K, &'a V)> {
1264         if self.length == 0 {
1265             None
1266         } else {
1267             self.length -= 1;
1268             unsafe { Some(self.range.next_back_unchecked()) }
1269         }
1270     }
1271 }
1272
1273 #[stable(feature = "rust1", since = "1.0.0")]
1274 impl<K, V> ExactSizeIterator for Iter<'_, K, V> {
1275     fn len(&self) -> usize {
1276         self.length
1277     }
1278 }
1279
1280 #[stable(feature = "rust1", since = "1.0.0")]
1281 impl<K, V> Clone for Iter<'_, K, V> {
1282     fn clone(&self) -> Self {
1283         Iter { range: self.range.clone(), length: self.length }
1284     }
1285 }
1286
1287 #[stable(feature = "rust1", since = "1.0.0")]
1288 impl<'a, K, V> IntoIterator for &'a mut BTreeMap<K, V> {
1289     type Item = (&'a K, &'a mut V);
1290     type IntoIter = IterMut<'a, K, V>;
1291
1292     fn into_iter(self) -> IterMut<'a, K, V> {
1293         self.iter_mut()
1294     }
1295 }
1296
1297 #[stable(feature = "rust1", since = "1.0.0")]
1298 impl<'a, K: 'a, V: 'a> Iterator for IterMut<'a, K, V> {
1299     type Item = (&'a K, &'a mut V);
1300
1301     fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
1302         if self.length == 0 {
1303             None
1304         } else {
1305             self.length -= 1;
1306             let (k, v) = unsafe { self.range.next_unchecked() };
1307             Some((k, v)) // coerce k from `&mut K` to `&K`
1308         }
1309     }
1310
1311     fn size_hint(&self) -> (usize, Option<usize>) {
1312         (self.length, Some(self.length))
1313     }
1314
1315     fn last(mut self) -> Option<(&'a K, &'a mut V)> {
1316         self.next_back()
1317     }
1318
1319     fn min(mut self) -> Option<(&'a K, &'a mut V)> {
1320         self.next()
1321     }
1322
1323     fn max(mut self) -> Option<(&'a K, &'a mut V)> {
1324         self.next_back()
1325     }
1326 }
1327
1328 #[stable(feature = "rust1", since = "1.0.0")]
1329 impl<'a, K: 'a, V: 'a> DoubleEndedIterator for IterMut<'a, K, V> {
1330     fn next_back(&mut self) -> Option<(&'a K, &'a mut V)> {
1331         if self.length == 0 {
1332             None
1333         } else {
1334             self.length -= 1;
1335             let (k, v) = unsafe { self.range.next_back_unchecked() };
1336             Some((k, v)) // coerce k from `&mut K` to `&K`
1337         }
1338     }
1339 }
1340
1341 #[stable(feature = "rust1", since = "1.0.0")]
1342 impl<K, V> ExactSizeIterator for IterMut<'_, K, V> {
1343     fn len(&self) -> usize {
1344         self.length
1345     }
1346 }
1347
1348 #[stable(feature = "fused", since = "1.26.0")]
1349 impl<K, V> FusedIterator for IterMut<'_, K, V> {}
1350
1351 impl<'a, K, V> IterMut<'a, K, V> {
1352     /// Returns an iterator of references over the remaining items.
1353     #[inline]
1354     pub(super) fn iter(&self) -> Iter<'_, K, V> {
1355         Iter { range: self.range.iter(), length: self.length }
1356     }
1357 }
1358
1359 #[stable(feature = "rust1", since = "1.0.0")]
1360 impl<K, V> IntoIterator for BTreeMap<K, V> {
1361     type Item = (K, V);
1362     type IntoIter = IntoIter<K, V>;
1363
1364     fn into_iter(self) -> IntoIter<K, V> {
1365         let mut me = ManuallyDrop::new(self);
1366         if let Some(root) = me.root.take() {
1367             let (f, b) = root.full_range();
1368
1369             IntoIter { front: Some(f), back: Some(b), length: me.length }
1370         } else {
1371             IntoIter { front: None, back: None, length: 0 }
1372         }
1373     }
1374 }
1375
1376 #[stable(feature = "btree_drop", since = "1.7.0")]
1377 impl<K, V> Drop for IntoIter<K, V> {
1378     fn drop(&mut self) {
1379         struct DropGuard<'a, K, V>(&'a mut IntoIter<K, V>);
1380
1381         impl<'a, K, V> Drop for DropGuard<'a, K, V> {
1382             fn drop(&mut self) {
1383                 // Continue the same loop we perform below. This only runs when unwinding, so we
1384                 // don't have to care about panics this time (they'll abort).
1385                 while let Some(_) = self.0.next() {}
1386
1387                 unsafe {
1388                     let mut node =
1389                         unwrap_unchecked(ptr::read(&self.0.front)).into_node().forget_type();
1390                     while let Some(parent) = node.deallocate_and_ascend() {
1391                         node = parent.into_node().forget_type();
1392                     }
1393                 }
1394             }
1395         }
1396
1397         while let Some(pair) = self.next() {
1398             let guard = DropGuard(self);
1399             drop(pair);
1400             mem::forget(guard);
1401         }
1402
1403         unsafe {
1404             if let Some(front) = ptr::read(&self.front) {
1405                 let mut node = front.into_node().forget_type();
1406                 // Most of the nodes have been deallocated while traversing
1407                 // but one pile from a leaf up to the root is left standing.
1408                 while let Some(parent) = node.deallocate_and_ascend() {
1409                     node = parent.into_node().forget_type();
1410                 }
1411             }
1412         }
1413     }
1414 }
1415
1416 #[stable(feature = "rust1", since = "1.0.0")]
1417 impl<K, V> Iterator for IntoIter<K, V> {
1418     type Item = (K, V);
1419
1420     fn next(&mut self) -> Option<(K, V)> {
1421         if self.length == 0 {
1422             None
1423         } else {
1424             self.length -= 1;
1425             Some(unsafe { self.front.as_mut().unwrap().next_unchecked() })
1426         }
1427     }
1428
1429     fn size_hint(&self) -> (usize, Option<usize>) {
1430         (self.length, Some(self.length))
1431     }
1432 }
1433
1434 #[stable(feature = "rust1", since = "1.0.0")]
1435 impl<K, V> DoubleEndedIterator for IntoIter<K, V> {
1436     fn next_back(&mut self) -> Option<(K, V)> {
1437         if self.length == 0 {
1438             None
1439         } else {
1440             self.length -= 1;
1441             Some(unsafe { self.back.as_mut().unwrap().next_back_unchecked() })
1442         }
1443     }
1444 }
1445
1446 #[stable(feature = "rust1", since = "1.0.0")]
1447 impl<K, V> ExactSizeIterator for IntoIter<K, V> {
1448     fn len(&self) -> usize {
1449         self.length
1450     }
1451 }
1452
1453 #[stable(feature = "fused", since = "1.26.0")]
1454 impl<K, V> FusedIterator for IntoIter<K, V> {}
1455
1456 #[stable(feature = "rust1", since = "1.0.0")]
1457 impl<'a, K, V> Iterator for Keys<'a, K, V> {
1458     type Item = &'a K;
1459
1460     fn next(&mut self) -> Option<&'a K> {
1461         self.inner.next().map(|(k, _)| k)
1462     }
1463
1464     fn size_hint(&self) -> (usize, Option<usize>) {
1465         self.inner.size_hint()
1466     }
1467
1468     fn last(mut self) -> Option<&'a K> {
1469         self.next_back()
1470     }
1471
1472     fn min(mut self) -> Option<&'a K> {
1473         self.next()
1474     }
1475
1476     fn max(mut self) -> Option<&'a K> {
1477         self.next_back()
1478     }
1479 }
1480
1481 #[stable(feature = "rust1", since = "1.0.0")]
1482 impl<'a, K, V> DoubleEndedIterator for Keys<'a, K, V> {
1483     fn next_back(&mut self) -> Option<&'a K> {
1484         self.inner.next_back().map(|(k, _)| k)
1485     }
1486 }
1487
1488 #[stable(feature = "rust1", since = "1.0.0")]
1489 impl<K, V> ExactSizeIterator for Keys<'_, K, V> {
1490     fn len(&self) -> usize {
1491         self.inner.len()
1492     }
1493 }
1494
1495 #[stable(feature = "fused", since = "1.26.0")]
1496 impl<K, V> FusedIterator for Keys<'_, K, V> {}
1497
1498 #[stable(feature = "rust1", since = "1.0.0")]
1499 impl<K, V> Clone for Keys<'_, K, V> {
1500     fn clone(&self) -> Self {
1501         Keys { inner: self.inner.clone() }
1502     }
1503 }
1504
1505 #[stable(feature = "rust1", since = "1.0.0")]
1506 impl<'a, K, V> Iterator for Values<'a, K, V> {
1507     type Item = &'a V;
1508
1509     fn next(&mut self) -> Option<&'a V> {
1510         self.inner.next().map(|(_, v)| v)
1511     }
1512
1513     fn size_hint(&self) -> (usize, Option<usize>) {
1514         self.inner.size_hint()
1515     }
1516
1517     fn last(mut self) -> Option<&'a V> {
1518         self.next_back()
1519     }
1520 }
1521
1522 #[stable(feature = "rust1", since = "1.0.0")]
1523 impl<'a, K, V> DoubleEndedIterator for Values<'a, K, V> {
1524     fn next_back(&mut self) -> Option<&'a V> {
1525         self.inner.next_back().map(|(_, v)| v)
1526     }
1527 }
1528
1529 #[stable(feature = "rust1", since = "1.0.0")]
1530 impl<K, V> ExactSizeIterator for Values<'_, K, V> {
1531     fn len(&self) -> usize {
1532         self.inner.len()
1533     }
1534 }
1535
1536 #[stable(feature = "fused", since = "1.26.0")]
1537 impl<K, V> FusedIterator for Values<'_, K, V> {}
1538
1539 #[stable(feature = "rust1", since = "1.0.0")]
1540 impl<K, V> Clone for Values<'_, K, V> {
1541     fn clone(&self) -> Self {
1542         Values { inner: self.inner.clone() }
1543     }
1544 }
1545
1546 /// An iterator produced by calling `drain_filter` on BTreeMap.
1547 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1548 pub struct DrainFilter<'a, K, V, F>
1549 where
1550     K: 'a,
1551     V: 'a,
1552     F: 'a + FnMut(&K, &mut V) -> bool,
1553 {
1554     pred: F,
1555     inner: DrainFilterInner<'a, K, V>,
1556 }
1557 /// Most of the implementation of DrainFilter are generic over the type
1558 /// of the predicate, thus also serving for BTreeSet::DrainFilter.
1559 pub(super) struct DrainFilterInner<'a, K: 'a, V: 'a> {
1560     /// Reference to the length field in the borrowed map, updated live.
1561     length: &'a mut usize,
1562     /// Buried reference to the root field in the borrowed map.
1563     /// Wrapped in `Option` to allow drop handler to `take` it.
1564     dormant_root: Option<DormantMutRef<'a, Root<K, V>>>,
1565     /// Contains a leaf edge preceding the next element to be returned, or the last leaf edge.
1566     /// Empty if the map has no root, if iteration went beyond the last leaf edge,
1567     /// or if a panic occurred in the predicate.
1568     cur_leaf_edge: Option<Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge>>,
1569 }
1570
1571 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1572 impl<K, V, F> Drop for DrainFilter<'_, K, V, F>
1573 where
1574     F: FnMut(&K, &mut V) -> bool,
1575 {
1576     fn drop(&mut self) {
1577         self.for_each(drop);
1578     }
1579 }
1580
1581 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1582 impl<K, V, F> fmt::Debug for DrainFilter<'_, K, V, F>
1583 where
1584     K: fmt::Debug,
1585     V: fmt::Debug,
1586     F: FnMut(&K, &mut V) -> bool,
1587 {
1588     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1589         f.debug_tuple("DrainFilter").field(&self.inner.peek()).finish()
1590     }
1591 }
1592
1593 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1594 impl<K, V, F> Iterator for DrainFilter<'_, K, V, F>
1595 where
1596     F: FnMut(&K, &mut V) -> bool,
1597 {
1598     type Item = (K, V);
1599
1600     fn next(&mut self) -> Option<(K, V)> {
1601         self.inner.next(&mut self.pred)
1602     }
1603
1604     fn size_hint(&self) -> (usize, Option<usize>) {
1605         self.inner.size_hint()
1606     }
1607 }
1608
1609 impl<'a, K: 'a, V: 'a> DrainFilterInner<'a, K, V> {
1610     /// Allow Debug implementations to predict the next element.
1611     pub(super) fn peek(&self) -> Option<(&K, &V)> {
1612         let edge = self.cur_leaf_edge.as_ref()?;
1613         edge.reborrow().next_kv().ok().map(Handle::into_kv)
1614     }
1615
1616     /// Implementation of a typical `DrainFilter::next` method, given the predicate.
1617     pub(super) fn next<F>(&mut self, pred: &mut F) -> Option<(K, V)>
1618     where
1619         F: FnMut(&K, &mut V) -> bool,
1620     {
1621         while let Ok(mut kv) = self.cur_leaf_edge.take()?.next_kv() {
1622             let (k, v) = kv.kv_mut();
1623             if pred(k, v) {
1624                 *self.length -= 1;
1625                 let (kv, pos) = kv.remove_kv_tracking(|| {
1626                     // SAFETY: we will touch the root in a way that will not
1627                     // invalidate the position returned.
1628                     let root = unsafe { self.dormant_root.take().unwrap().awaken() };
1629                     root.pop_internal_level();
1630                     self.dormant_root = Some(DormantMutRef::new(root).1);
1631                 });
1632                 self.cur_leaf_edge = Some(pos);
1633                 return Some(kv);
1634             }
1635             self.cur_leaf_edge = Some(kv.next_leaf_edge());
1636         }
1637         None
1638     }
1639
1640     /// Implementation of a typical `DrainFilter::size_hint` method.
1641     pub(super) fn size_hint(&self) -> (usize, Option<usize>) {
1642         // In most of the btree iterators, `self.length` is the number of elements
1643         // yet to be visited. Here, it includes elements that were visited and that
1644         // the predicate decided not to drain. Making this upper bound more accurate
1645         // requires maintaining an extra field and is not worth while.
1646         (0, Some(*self.length))
1647     }
1648 }
1649
1650 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1651 impl<K, V, F> FusedIterator for DrainFilter<'_, K, V, F> where F: FnMut(&K, &mut V) -> bool {}
1652
1653 #[stable(feature = "btree_range", since = "1.17.0")]
1654 impl<'a, K, V> Iterator for Range<'a, K, V> {
1655     type Item = (&'a K, &'a V);
1656
1657     fn next(&mut self) -> Option<(&'a K, &'a V)> {
1658         if self.is_empty() { None } else { unsafe { Some(self.next_unchecked()) } }
1659     }
1660
1661     fn last(mut self) -> Option<(&'a K, &'a V)> {
1662         self.next_back()
1663     }
1664
1665     fn min(mut self) -> Option<(&'a K, &'a V)> {
1666         self.next()
1667     }
1668
1669     fn max(mut self) -> Option<(&'a K, &'a V)> {
1670         self.next_back()
1671     }
1672 }
1673
1674 #[stable(feature = "map_values_mut", since = "1.10.0")]
1675 impl<'a, K, V> Iterator for ValuesMut<'a, K, V> {
1676     type Item = &'a mut V;
1677
1678     fn next(&mut self) -> Option<&'a mut V> {
1679         self.inner.next().map(|(_, v)| v)
1680     }
1681
1682     fn size_hint(&self) -> (usize, Option<usize>) {
1683         self.inner.size_hint()
1684     }
1685
1686     fn last(mut self) -> Option<&'a mut V> {
1687         self.next_back()
1688     }
1689 }
1690
1691 #[stable(feature = "map_values_mut", since = "1.10.0")]
1692 impl<'a, K, V> DoubleEndedIterator for ValuesMut<'a, K, V> {
1693     fn next_back(&mut self) -> Option<&'a mut V> {
1694         self.inner.next_back().map(|(_, v)| v)
1695     }
1696 }
1697
1698 #[stable(feature = "map_values_mut", since = "1.10.0")]
1699 impl<K, V> ExactSizeIterator for ValuesMut<'_, K, V> {
1700     fn len(&self) -> usize {
1701         self.inner.len()
1702     }
1703 }
1704
1705 #[stable(feature = "fused", since = "1.26.0")]
1706 impl<K, V> FusedIterator for ValuesMut<'_, K, V> {}
1707
1708 impl<'a, K, V> Range<'a, K, V> {
1709     fn is_empty(&self) -> bool {
1710         self.front == self.back
1711     }
1712
1713     unsafe fn next_unchecked(&mut self) -> (&'a K, &'a V) {
1714         unsafe { unwrap_unchecked(self.front.as_mut()).next_unchecked() }
1715     }
1716 }
1717
1718 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1719 impl<K, V> Iterator for IntoKeys<K, V> {
1720     type Item = K;
1721
1722     fn next(&mut self) -> Option<K> {
1723         self.inner.next().map(|(k, _)| k)
1724     }
1725
1726     fn size_hint(&self) -> (usize, Option<usize>) {
1727         self.inner.size_hint()
1728     }
1729
1730     fn last(mut self) -> Option<K> {
1731         self.next_back()
1732     }
1733
1734     fn min(mut self) -> Option<K> {
1735         self.next()
1736     }
1737
1738     fn max(mut self) -> Option<K> {
1739         self.next_back()
1740     }
1741 }
1742
1743 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1744 impl<K, V> DoubleEndedIterator for IntoKeys<K, V> {
1745     fn next_back(&mut self) -> Option<K> {
1746         self.inner.next_back().map(|(k, _)| k)
1747     }
1748 }
1749
1750 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1751 impl<K, V> ExactSizeIterator for IntoKeys<K, V> {
1752     fn len(&self) -> usize {
1753         self.inner.len()
1754     }
1755 }
1756
1757 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1758 impl<K, V> FusedIterator for IntoKeys<K, V> {}
1759
1760 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1761 impl<K, V> Iterator for IntoValues<K, V> {
1762     type Item = V;
1763
1764     fn next(&mut self) -> Option<V> {
1765         self.inner.next().map(|(_, v)| v)
1766     }
1767
1768     fn size_hint(&self) -> (usize, Option<usize>) {
1769         self.inner.size_hint()
1770     }
1771
1772     fn last(mut self) -> Option<V> {
1773         self.next_back()
1774     }
1775 }
1776
1777 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1778 impl<K, V> DoubleEndedIterator for IntoValues<K, V> {
1779     fn next_back(&mut self) -> Option<V> {
1780         self.inner.next_back().map(|(_, v)| v)
1781     }
1782 }
1783
1784 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1785 impl<K, V> ExactSizeIterator for IntoValues<K, V> {
1786     fn len(&self) -> usize {
1787         self.inner.len()
1788     }
1789 }
1790
1791 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1792 impl<K, V> FusedIterator for IntoValues<K, V> {}
1793
1794 #[stable(feature = "btree_range", since = "1.17.0")]
1795 impl<'a, K, V> DoubleEndedIterator for Range<'a, K, V> {
1796     fn next_back(&mut self) -> Option<(&'a K, &'a V)> {
1797         if self.is_empty() { None } else { Some(unsafe { self.next_back_unchecked() }) }
1798     }
1799 }
1800
1801 impl<'a, K, V> Range<'a, K, V> {
1802     unsafe fn next_back_unchecked(&mut self) -> (&'a K, &'a V) {
1803         unsafe { unwrap_unchecked(self.back.as_mut()).next_back_unchecked() }
1804     }
1805 }
1806
1807 #[stable(feature = "fused", since = "1.26.0")]
1808 impl<K, V> FusedIterator for Range<'_, K, V> {}
1809
1810 #[stable(feature = "btree_range", since = "1.17.0")]
1811 impl<K, V> Clone for Range<'_, K, V> {
1812     fn clone(&self) -> Self {
1813         Range { front: self.front, back: self.back }
1814     }
1815 }
1816
1817 #[stable(feature = "btree_range", since = "1.17.0")]
1818 impl<'a, K, V> Iterator for RangeMut<'a, K, V> {
1819     type Item = (&'a K, &'a mut V);
1820
1821     fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
1822         if self.is_empty() {
1823             None
1824         } else {
1825             let (k, v) = unsafe { self.next_unchecked() };
1826             Some((k, v)) // coerce k from `&mut K` to `&K`
1827         }
1828     }
1829
1830     fn last(mut self) -> Option<(&'a K, &'a mut V)> {
1831         self.next_back()
1832     }
1833
1834     fn min(mut self) -> Option<(&'a K, &'a mut V)> {
1835         self.next()
1836     }
1837
1838     fn max(mut self) -> Option<(&'a K, &'a mut V)> {
1839         self.next_back()
1840     }
1841 }
1842
1843 impl<'a, K, V> RangeMut<'a, K, V> {
1844     fn is_empty(&self) -> bool {
1845         self.front == self.back
1846     }
1847
1848     unsafe fn next_unchecked(&mut self) -> (&'a K, &'a mut V) {
1849         unsafe { unwrap_unchecked(self.front.as_mut()).next_unchecked() }
1850     }
1851
1852     /// Returns an iterator of references over the remaining items.
1853     #[inline]
1854     pub(super) fn iter(&self) -> Range<'_, K, V> {
1855         Range {
1856             front: self.front.as_ref().map(|f| f.reborrow()),
1857             back: self.back.as_ref().map(|b| b.reborrow()),
1858         }
1859     }
1860 }
1861
1862 #[stable(feature = "btree_range", since = "1.17.0")]
1863 impl<'a, K, V> DoubleEndedIterator for RangeMut<'a, K, V> {
1864     fn next_back(&mut self) -> Option<(&'a K, &'a mut V)> {
1865         if self.is_empty() {
1866             None
1867         } else {
1868             let (k, v) = unsafe { self.next_back_unchecked() };
1869             Some((k, v)) // coerce k from `&mut K` to `&K`
1870         }
1871     }
1872 }
1873
1874 #[stable(feature = "fused", since = "1.26.0")]
1875 impl<K, V> FusedIterator for RangeMut<'_, K, V> {}
1876
1877 impl<'a, K, V> RangeMut<'a, K, V> {
1878     unsafe fn next_back_unchecked(&mut self) -> (&'a K, &'a mut V) {
1879         unsafe { unwrap_unchecked(self.back.as_mut()).next_back_unchecked() }
1880     }
1881 }
1882
1883 #[stable(feature = "rust1", since = "1.0.0")]
1884 impl<K: Ord, V> FromIterator<(K, V)> for BTreeMap<K, V> {
1885     fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> BTreeMap<K, V> {
1886         let mut map = BTreeMap::new();
1887         map.extend(iter);
1888         map
1889     }
1890 }
1891
1892 #[stable(feature = "rust1", since = "1.0.0")]
1893 impl<K: Ord, V> Extend<(K, V)> for BTreeMap<K, V> {
1894     #[inline]
1895     fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) {
1896         iter.into_iter().for_each(move |(k, v)| {
1897             self.insert(k, v);
1898         });
1899     }
1900
1901     #[inline]
1902     fn extend_one(&mut self, (k, v): (K, V)) {
1903         self.insert(k, v);
1904     }
1905 }
1906
1907 #[stable(feature = "extend_ref", since = "1.2.0")]
1908 impl<'a, K: Ord + Copy, V: Copy> Extend<(&'a K, &'a V)> for BTreeMap<K, V> {
1909     fn extend<I: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: I) {
1910         self.extend(iter.into_iter().map(|(&key, &value)| (key, value)));
1911     }
1912
1913     #[inline]
1914     fn extend_one(&mut self, (&k, &v): (&'a K, &'a V)) {
1915         self.insert(k, v);
1916     }
1917 }
1918
1919 #[stable(feature = "rust1", since = "1.0.0")]
1920 impl<K: Hash, V: Hash> Hash for BTreeMap<K, V> {
1921     fn hash<H: Hasher>(&self, state: &mut H) {
1922         for elt in self {
1923             elt.hash(state);
1924         }
1925     }
1926 }
1927
1928 #[stable(feature = "rust1", since = "1.0.0")]
1929 impl<K: Ord, V> Default for BTreeMap<K, V> {
1930     /// Creates an empty `BTreeMap`.
1931     fn default() -> BTreeMap<K, V> {
1932         BTreeMap::new()
1933     }
1934 }
1935
1936 #[stable(feature = "rust1", since = "1.0.0")]
1937 impl<K: PartialEq, V: PartialEq> PartialEq for BTreeMap<K, V> {
1938     fn eq(&self, other: &BTreeMap<K, V>) -> bool {
1939         self.len() == other.len() && self.iter().zip(other).all(|(a, b)| a == b)
1940     }
1941 }
1942
1943 #[stable(feature = "rust1", since = "1.0.0")]
1944 impl<K: Eq, V: Eq> Eq for BTreeMap<K, V> {}
1945
1946 #[stable(feature = "rust1", since = "1.0.0")]
1947 impl<K: PartialOrd, V: PartialOrd> PartialOrd for BTreeMap<K, V> {
1948     #[inline]
1949     fn partial_cmp(&self, other: &BTreeMap<K, V>) -> Option<Ordering> {
1950         self.iter().partial_cmp(other.iter())
1951     }
1952 }
1953
1954 #[stable(feature = "rust1", since = "1.0.0")]
1955 impl<K: Ord, V: Ord> Ord for BTreeMap<K, V> {
1956     #[inline]
1957     fn cmp(&self, other: &BTreeMap<K, V>) -> Ordering {
1958         self.iter().cmp(other.iter())
1959     }
1960 }
1961
1962 #[stable(feature = "rust1", since = "1.0.0")]
1963 impl<K: Debug, V: Debug> Debug for BTreeMap<K, V> {
1964     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1965         f.debug_map().entries(self.iter()).finish()
1966     }
1967 }
1968
1969 #[stable(feature = "rust1", since = "1.0.0")]
1970 impl<K: Ord, Q: ?Sized, V> Index<&Q> for BTreeMap<K, V>
1971 where
1972     K: Borrow<Q>,
1973     Q: Ord,
1974 {
1975     type Output = V;
1976
1977     /// Returns a reference to the value corresponding to the supplied key.
1978     ///
1979     /// # Panics
1980     ///
1981     /// Panics if the key is not present in the `BTreeMap`.
1982     #[inline]
1983     fn index(&self, key: &Q) -> &V {
1984         self.get(key).expect("no entry found for key")
1985     }
1986 }
1987
1988 impl<K, V> BTreeMap<K, V> {
1989     /// Gets an iterator over the entries of the map, sorted by key.
1990     ///
1991     /// # Examples
1992     ///
1993     /// Basic usage:
1994     ///
1995     /// ```
1996     /// use std::collections::BTreeMap;
1997     ///
1998     /// let mut map = BTreeMap::new();
1999     /// map.insert(3, "c");
2000     /// map.insert(2, "b");
2001     /// map.insert(1, "a");
2002     ///
2003     /// for (key, value) in map.iter() {
2004     ///     println!("{}: {}", key, value);
2005     /// }
2006     ///
2007     /// let (first_key, first_value) = map.iter().next().unwrap();
2008     /// assert_eq!((*first_key, *first_value), (1, "a"));
2009     /// ```
2010     #[stable(feature = "rust1", since = "1.0.0")]
2011     pub fn iter(&self) -> Iter<'_, K, V> {
2012         if let Some(root) = &self.root {
2013             let (f, b) = root.reborrow().full_range();
2014
2015             Iter { range: Range { front: Some(f), back: Some(b) }, length: self.length }
2016         } else {
2017             Iter { range: Range { front: None, back: None }, length: 0 }
2018         }
2019     }
2020
2021     /// Gets a mutable iterator over the entries of the map, sorted by key.
2022     ///
2023     /// # Examples
2024     ///
2025     /// Basic usage:
2026     ///
2027     /// ```
2028     /// use std::collections::BTreeMap;
2029     ///
2030     /// let mut map = BTreeMap::new();
2031     /// map.insert("a", 1);
2032     /// map.insert("b", 2);
2033     /// map.insert("c", 3);
2034     ///
2035     /// // add 10 to the value if the key isn't "a"
2036     /// for (key, value) in map.iter_mut() {
2037     ///     if key != &"a" {
2038     ///         *value += 10;
2039     ///     }
2040     /// }
2041     /// ```
2042     #[stable(feature = "rust1", since = "1.0.0")]
2043     pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {
2044         if let Some(root) = &mut self.root {
2045             let (f, b) = root.borrow_valmut().full_range();
2046
2047             IterMut {
2048                 range: RangeMut { front: Some(f), back: Some(b), _marker: PhantomData },
2049                 length: self.length,
2050             }
2051         } else {
2052             IterMut { range: RangeMut { front: None, back: None, _marker: PhantomData }, length: 0 }
2053         }
2054     }
2055
2056     /// Gets an iterator over the keys of the map, in sorted order.
2057     ///
2058     /// # Examples
2059     ///
2060     /// Basic usage:
2061     ///
2062     /// ```
2063     /// use std::collections::BTreeMap;
2064     ///
2065     /// let mut a = BTreeMap::new();
2066     /// a.insert(2, "b");
2067     /// a.insert(1, "a");
2068     ///
2069     /// let keys: Vec<_> = a.keys().cloned().collect();
2070     /// assert_eq!(keys, [1, 2]);
2071     /// ```
2072     #[stable(feature = "rust1", since = "1.0.0")]
2073     pub fn keys(&self) -> Keys<'_, K, V> {
2074         Keys { inner: self.iter() }
2075     }
2076
2077     /// Gets an iterator over the values of the map, in order by key.
2078     ///
2079     /// # Examples
2080     ///
2081     /// Basic usage:
2082     ///
2083     /// ```
2084     /// use std::collections::BTreeMap;
2085     ///
2086     /// let mut a = BTreeMap::new();
2087     /// a.insert(1, "hello");
2088     /// a.insert(2, "goodbye");
2089     ///
2090     /// let values: Vec<&str> = a.values().cloned().collect();
2091     /// assert_eq!(values, ["hello", "goodbye"]);
2092     /// ```
2093     #[stable(feature = "rust1", since = "1.0.0")]
2094     pub fn values(&self) -> Values<'_, K, V> {
2095         Values { inner: self.iter() }
2096     }
2097
2098     /// Gets a mutable iterator over the values of the map, in order by key.
2099     ///
2100     /// # Examples
2101     ///
2102     /// Basic usage:
2103     ///
2104     /// ```
2105     /// use std::collections::BTreeMap;
2106     ///
2107     /// let mut a = BTreeMap::new();
2108     /// a.insert(1, String::from("hello"));
2109     /// a.insert(2, String::from("goodbye"));
2110     ///
2111     /// for value in a.values_mut() {
2112     ///     value.push_str("!");
2113     /// }
2114     ///
2115     /// let values: Vec<String> = a.values().cloned().collect();
2116     /// assert_eq!(values, [String::from("hello!"),
2117     ///                     String::from("goodbye!")]);
2118     /// ```
2119     #[stable(feature = "map_values_mut", since = "1.10.0")]
2120     pub fn values_mut(&mut self) -> ValuesMut<'_, K, V> {
2121         ValuesMut { inner: self.iter_mut() }
2122     }
2123
2124     /// Returns the number of elements in the map.
2125     ///
2126     /// # Examples
2127     ///
2128     /// Basic usage:
2129     ///
2130     /// ```
2131     /// use std::collections::BTreeMap;
2132     ///
2133     /// let mut a = BTreeMap::new();
2134     /// assert_eq!(a.len(), 0);
2135     /// a.insert(1, "a");
2136     /// assert_eq!(a.len(), 1);
2137     /// ```
2138     #[doc(alias = "length")]
2139     #[stable(feature = "rust1", since = "1.0.0")]
2140     #[rustc_const_unstable(feature = "const_btree_new", issue = "71835")]
2141     pub const fn len(&self) -> usize {
2142         self.length
2143     }
2144
2145     /// Returns `true` if the map contains no elements.
2146     ///
2147     /// # Examples
2148     ///
2149     /// Basic usage:
2150     ///
2151     /// ```
2152     /// use std::collections::BTreeMap;
2153     ///
2154     /// let mut a = BTreeMap::new();
2155     /// assert!(a.is_empty());
2156     /// a.insert(1, "a");
2157     /// assert!(!a.is_empty());
2158     /// ```
2159     #[stable(feature = "rust1", since = "1.0.0")]
2160     #[rustc_const_unstable(feature = "const_btree_new", issue = "71835")]
2161     pub const fn is_empty(&self) -> bool {
2162         self.len() == 0
2163     }
2164
2165     /// If the root node is the empty (non-allocated) root node, allocate our
2166     /// own node. Is an associated function to avoid borrowing the entire BTreeMap.
2167     fn ensure_is_owned(root: &mut Option<Root<K, V>>) -> &mut Root<K, V> {
2168         root.get_or_insert_with(Root::new)
2169     }
2170 }
2171
2172 #[cfg(test)]
2173 mod tests;