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