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