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