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