alloc/collections/btree/map.rs
1use core::borrow::Borrow;
2use core::cmp::Ordering;
3use core::error::Error;
4use core::fmt::{self, Debug};
5use core::hash::{Hash, Hasher};
6use core::iter::{FusedIterator, TrustedLen};
7use core::marker::PhantomData;
8use core::mem::{self, ManuallyDrop};
9use core::ops::{Bound, Index, RangeBounds};
10use core::ptr;
11
12use super::borrow::DormantMutRef;
13use super::dedup_sorted_iter::DedupSortedIter;
14use super::navigate::{LazyLeafRange, LeafRange};
15use super::node::ForceResult::*;
16use super::node::{self, Handle, NodeRef, Root, marker};
17use super::search::SearchBound;
18use super::search::SearchResult::*;
19use super::set_val::SetValZST;
20use crate::alloc::{Allocator, Global};
21use crate::vec::Vec;
22
23mod entry;
24
25use Entry::*;
26#[stable(feature = "rust1", since = "1.0.0")]
27pub use entry::{Entry, OccupiedEntry, OccupiedError, VacantEntry};
28
29/// Minimum number of elements in a node that is not a root.
30/// We might temporarily have fewer elements during methods.
31pub(super) const MIN_LEN: usize = node::MIN_LEN_AFTER_SPLIT;
32
33// A tree in a `BTreeMap` is a tree in the `node` module with additional invariants:
34// - Keys must appear in ascending order (according to the key's type).
35// - Every non-leaf node contains at least 1 element (has at least 2 children).
36// - Every non-root node contains at least MIN_LEN elements.
37//
38// An empty map is represented either by the absence of a root node or by a
39// root node that is an empty leaf.
40
41/// An ordered map based on a [B-Tree].
42///
43/// Given a key type with a [total order], an ordered map stores its entries in key order.
44/// That means that keys must be of a type that implements the [`Ord`] trait,
45/// such that two keys can always be compared to determine their [`Ordering`].
46/// Examples of keys with a total order are strings with lexicographical order,
47/// and numbers with their natural order.
48///
49/// Iterators obtained from functions such as [`BTreeMap::iter`], [`BTreeMap::into_iter`], [`BTreeMap::values`], or
50/// [`BTreeMap::keys`] produce their items in key order, and take worst-case logarithmic and
51/// amortized constant time per item returned.
52///
53/// It is a logic error for a key to be modified in such a way that the key's ordering relative to
54/// any other key, as determined by the [`Ord`] trait, changes while it is in the map. This is
55/// normally only possible through [`Cell`], [`RefCell`], global state, I/O, or unsafe code.
56/// The behavior resulting from such a logic error is not specified, but will be encapsulated to the
57/// `BTreeMap` that observed the logic error and not result in undefined behavior. This could
58/// include panics, incorrect results, aborts, memory leaks, and non-termination.
59///
60/// # Examples
61///
62/// ```
63/// use std::collections::BTreeMap;
64///
65/// // type inference lets us omit an explicit type signature (which
66/// // would be `BTreeMap<&str, &str>` in this example).
67/// let mut movie_reviews = BTreeMap::new();
68///
69/// // review some movies.
70/// movie_reviews.insert("Office Space", "Deals with real issues in the workplace.");
71/// movie_reviews.insert("Pulp Fiction", "Masterpiece.");
72/// movie_reviews.insert("The Godfather", "Very enjoyable.");
73/// movie_reviews.insert("The Blues Brothers", "Eye lyked it a lot.");
74///
75/// // check for a specific one.
76/// if !movie_reviews.contains_key("Les Misérables") {
77/// println!("We've got {} reviews, but Les Misérables ain't one.",
78/// movie_reviews.len());
79/// }
80///
81/// // oops, this review has a lot of spelling mistakes, let's delete it.
82/// movie_reviews.remove("The Blues Brothers");
83///
84/// // look up the values associated with some keys.
85/// let to_find = ["Up!", "Office Space"];
86/// for movie in &to_find {
87/// match movie_reviews.get(movie) {
88/// Some(review) => println!("{movie}: {review}"),
89/// None => println!("{movie} is unreviewed.")
90/// }
91/// }
92///
93/// // Look up the value for a key (will panic if the key is not found).
94/// println!("Movie review: {}", movie_reviews["Office Space"]);
95///
96/// // iterate over everything.
97/// for (movie, review) in &movie_reviews {
98/// println!("{movie}: \"{review}\"");
99/// }
100/// ```
101///
102/// A `BTreeMap` with a known list of items can be initialized from an array:
103///
104/// ```
105/// use std::collections::BTreeMap;
106///
107/// let solar_distance = BTreeMap::from([
108/// ("Mercury", 0.4),
109/// ("Venus", 0.7),
110/// ("Earth", 1.0),
111/// ("Mars", 1.5),
112/// ]);
113/// ```
114///
115/// ## `Entry` API
116///
117/// `BTreeMap` implements an [`Entry API`], which allows for complex
118/// methods of getting, setting, updating and removing keys and their values:
119///
120/// [`Entry API`]: BTreeMap::entry
121///
122/// ```
123/// use std::collections::BTreeMap;
124///
125/// // type inference lets us omit an explicit type signature (which
126/// // would be `BTreeMap<&str, u8>` in this example).
127/// let mut player_stats = BTreeMap::new();
128///
129/// fn random_stat_buff() -> u8 {
130/// // could actually return some random value here - let's just return
131/// // some fixed value for now
132/// 42
133/// }
134///
135/// // insert a key only if it doesn't already exist
136/// player_stats.entry("health").or_insert(100);
137///
138/// // insert a key using a function that provides a new value only if it
139/// // doesn't already exist
140/// player_stats.entry("defence").or_insert_with(random_stat_buff);
141///
142/// // update a key, guarding against the key possibly not being set
143/// let stat = player_stats.entry("attack").or_insert(100);
144/// *stat += random_stat_buff();
145///
146/// // modify an entry before an insert with in-place mutation
147/// player_stats.entry("mana").and_modify(|mana| *mana += 200).or_insert(100);
148/// ```
149///
150/// # Background
151///
152/// A B-tree is (like) a [binary search tree], but adapted to the natural granularity that modern
153/// machines like to consume data at. This means that each node contains an entire array of elements,
154/// instead of just a single element.
155///
156/// B-Trees represent a fundamental compromise between cache-efficiency and actually minimizing
157/// the amount of work performed in a search. In theory, a binary search tree (BST) is the optimal
158/// choice for a sorted map, as a perfectly balanced BST performs the theoretical minimum number of
159/// comparisons necessary to find an element (log<sub>2</sub>n). However, in practice the way this
160/// is done is *very* inefficient for modern computer architectures. In particular, every element
161/// is stored in its own individually heap-allocated node. This means that every single insertion
162/// triggers a heap-allocation, and every comparison is a potential cache-miss due to the indirection.
163/// Since both heap-allocations and cache-misses are notably expensive in practice, we are forced to,
164/// at the very least, reconsider the BST strategy.
165///
166/// A B-Tree instead makes each node contain B-1 to 2B-1 elements in a contiguous array. By doing
167/// this, we reduce the number of allocations by a factor of B, and improve cache efficiency in
168/// searches. However, this does mean that searches will have to do *more* comparisons on average.
169/// The precise number of comparisons depends on the node search strategy used. For optimal cache
170/// efficiency, one could search the nodes linearly. For optimal comparisons, one could search
171/// the node using binary search. As a compromise, one could also perform a linear search
172/// that initially only checks every i<sup>th</sup> element for some choice of i.
173///
174/// Currently, our implementation simply performs naive linear search. This provides excellent
175/// performance on *small* nodes of elements which are cheap to compare. However in the future we
176/// would like to further explore choosing the optimal search strategy based on the choice of B,
177/// and possibly other factors. Using linear search, searching for a random element is expected
178/// to take B * log(n) comparisons, which is generally worse than a BST. In practice,
179/// however, performance is excellent.
180///
181/// [B-Tree]: https://en.wikipedia.org/wiki/B-tree
182/// [binary search tree]: https://en.wikipedia.org/wiki/Binary_search_tree
183/// [total order]: https://en.wikipedia.org/wiki/Total_order
184/// [`Cell`]: core::cell::Cell
185/// [`RefCell`]: core::cell::RefCell
186#[stable(feature = "rust1", since = "1.0.0")]
187#[cfg_attr(not(test), rustc_diagnostic_item = "BTreeMap")]
188#[rustc_insignificant_dtor]
189pub struct BTreeMap<
190 K,
191 V,
192 #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator + Clone = Global,
193> {
194 root: Option<Root<K, V>>,
195 length: usize,
196 /// `ManuallyDrop` to control drop order (needs to be dropped after all the nodes).
197 // Although some of the accessory types store a copy of the allocator, the nodes do not.
198 // Because allocations will remain live as long as any copy (like this one) of the allocator
199 // is live, it's unnecessary to store the allocator in each node.
200 pub(super) alloc: ManuallyDrop<A>,
201 // For dropck; the `Box` avoids making the `Unpin` impl more strict than before
202 _marker: PhantomData<crate::boxed::Box<(K, V), A>>,
203}
204
205#[stable(feature = "btree_drop", since = "1.7.0")]
206unsafe impl<#[may_dangle] K, #[may_dangle] V, A: Allocator + Clone> Drop for BTreeMap<K, V, A> {
207 fn drop(&mut self) {
208 drop(unsafe { ptr::read(self) }.into_iter())
209 }
210}
211
212// FIXME: This implementation is "wrong", but changing it would be a breaking change.
213// (The bounds of the automatic `UnwindSafe` implementation have been like this since Rust 1.50.)
214// Maybe we can fix it nonetheless with a crater run, or if the `UnwindSafe`
215// traits are deprecated, or disarmed (no longer causing hard errors) in the future.
216#[stable(feature = "btree_unwindsafe", since = "1.64.0")]
217impl<K, V, A: Allocator + Clone> core::panic::UnwindSafe for BTreeMap<K, V, A>
218where
219 A: core::panic::UnwindSafe,
220 K: core::panic::RefUnwindSafe,
221 V: core::panic::RefUnwindSafe,
222{
223}
224
225#[stable(feature = "rust1", since = "1.0.0")]
226impl<K: Clone, V: Clone, A: Allocator + Clone> Clone for BTreeMap<K, V, A> {
227 fn clone(&self) -> BTreeMap<K, V, A> {
228 fn clone_subtree<'a, K: Clone, V: Clone, A: Allocator + Clone>(
229 node: NodeRef<marker::Immut<'a>, K, V, marker::LeafOrInternal>,
230 alloc: A,
231 ) -> BTreeMap<K, V, A>
232 where
233 K: 'a,
234 V: 'a,
235 {
236 match node.force() {
237 Leaf(leaf) => {
238 let mut out_tree = BTreeMap {
239 root: Some(Root::new(alloc.clone())),
240 length: 0,
241 alloc: ManuallyDrop::new(alloc),
242 _marker: PhantomData,
243 };
244
245 {
246 let root = out_tree.root.as_mut().unwrap(); // unwrap succeeds because we just wrapped
247 let mut out_node = match root.borrow_mut().force() {
248 Leaf(leaf) => leaf,
249 Internal(_) => unreachable!(),
250 };
251
252 let mut in_edge = leaf.first_edge();
253 while let Ok(kv) = in_edge.right_kv() {
254 let (k, v) = kv.into_kv();
255 in_edge = kv.right_edge();
256
257 out_node.push(k.clone(), v.clone());
258 out_tree.length += 1;
259 }
260 }
261
262 out_tree
263 }
264 Internal(internal) => {
265 let mut out_tree =
266 clone_subtree(internal.first_edge().descend(), alloc.clone());
267
268 {
269 let out_root = out_tree.root.as_mut().unwrap();
270 let mut out_node = out_root.push_internal_level(alloc.clone());
271 let mut in_edge = internal.first_edge();
272 while let Ok(kv) = in_edge.right_kv() {
273 let (k, v) = kv.into_kv();
274 in_edge = kv.right_edge();
275
276 let k = (*k).clone();
277 let v = (*v).clone();
278 let subtree = clone_subtree(in_edge.descend(), alloc.clone());
279
280 // We can't destructure subtree directly
281 // because BTreeMap implements Drop
282 let (subroot, sublength) = unsafe {
283 let subtree = ManuallyDrop::new(subtree);
284 let root = ptr::read(&subtree.root);
285 let length = subtree.length;
286 (root, length)
287 };
288
289 out_node.push(
290 k,
291 v,
292 subroot.unwrap_or_else(|| Root::new(alloc.clone())),
293 );
294 out_tree.length += 1 + sublength;
295 }
296 }
297
298 out_tree
299 }
300 }
301 }
302
303 if self.is_empty() {
304 BTreeMap::new_in((*self.alloc).clone())
305 } else {
306 clone_subtree(self.root.as_ref().unwrap().reborrow(), (*self.alloc).clone()) // unwrap succeeds because not empty
307 }
308 }
309}
310
311// Internal functionality for `BTreeSet`.
312impl<K, A: Allocator + Clone> BTreeMap<K, SetValZST, A> {
313 pub(super) fn replace(&mut self, key: K) -> Option<K>
314 where
315 K: Ord,
316 {
317 let (map, dormant_map) = DormantMutRef::new(self);
318 let root_node =
319 map.root.get_or_insert_with(|| Root::new((*map.alloc).clone())).borrow_mut();
320 match root_node.search_tree::<K>(&key) {
321 Found(mut kv) => Some(mem::replace(kv.key_mut(), key)),
322 GoDown(handle) => {
323 VacantEntry {
324 key,
325 handle: Some(handle),
326 dormant_map,
327 alloc: (*map.alloc).clone(),
328 _marker: PhantomData,
329 }
330 .insert(SetValZST);
331 None
332 }
333 }
334 }
335
336 pub(super) fn get_or_insert_with<Q: ?Sized, F>(&mut self, q: &Q, f: F) -> &K
337 where
338 K: Borrow<Q> + Ord,
339 Q: Ord,
340 F: FnOnce(&Q) -> K,
341 {
342 let (map, dormant_map) = DormantMutRef::new(self);
343 let root_node =
344 map.root.get_or_insert_with(|| Root::new((*map.alloc).clone())).borrow_mut();
345 match root_node.search_tree(q) {
346 Found(handle) => handle.into_kv_mut().0,
347 GoDown(handle) => {
348 let key = f(q);
349 assert!(*key.borrow() == *q, "new value is not equal");
350 VacantEntry {
351 key,
352 handle: Some(handle),
353 dormant_map,
354 alloc: (*map.alloc).clone(),
355 _marker: PhantomData,
356 }
357 .insert_entry(SetValZST)
358 .into_key()
359 }
360 }
361 }
362}
363
364/// An iterator over the entries of a `BTreeMap`.
365///
366/// This `struct` is created by the [`iter`] method on [`BTreeMap`]. See its
367/// documentation for more.
368///
369/// [`iter`]: BTreeMap::iter
370#[must_use = "iterators are lazy and do nothing unless consumed"]
371#[stable(feature = "rust1", since = "1.0.0")]
372pub struct Iter<'a, K: 'a, V: 'a> {
373 range: LazyLeafRange<marker::Immut<'a>, K, V>,
374 length: usize,
375}
376
377#[stable(feature = "collection_debug", since = "1.17.0")]
378impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for Iter<'_, K, V> {
379 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
380 f.debug_list().entries(self.clone()).finish()
381 }
382}
383
384#[stable(feature = "default_iters", since = "1.70.0")]
385impl<'a, K: 'a, V: 'a> Default for Iter<'a, K, V> {
386 /// Creates an empty `btree_map::Iter`.
387 ///
388 /// ```
389 /// # use std::collections::btree_map;
390 /// let iter: btree_map::Iter<'_, u8, u8> = Default::default();
391 /// assert_eq!(iter.len(), 0);
392 /// ```
393 fn default() -> Self {
394 Iter { range: Default::default(), length: 0 }
395 }
396}
397
398/// A mutable iterator over the entries of a `BTreeMap`.
399///
400/// This `struct` is created by the [`iter_mut`] method on [`BTreeMap`]. See its
401/// documentation for more.
402///
403/// [`iter_mut`]: BTreeMap::iter_mut
404#[must_use = "iterators are lazy and do nothing unless consumed"]
405#[stable(feature = "rust1", since = "1.0.0")]
406pub struct IterMut<'a, K: 'a, V: 'a> {
407 range: LazyLeafRange<marker::ValMut<'a>, K, V>,
408 length: usize,
409
410 // Be invariant in `K` and `V`
411 _marker: PhantomData<&'a mut (K, V)>,
412}
413
414#[stable(feature = "collection_debug", since = "1.17.0")]
415impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for IterMut<'_, K, V> {
416 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
417 let range = Iter { range: self.range.reborrow(), length: self.length };
418 f.debug_list().entries(range).finish()
419 }
420}
421
422#[stable(feature = "default_iters", since = "1.70.0")]
423impl<'a, K: 'a, V: 'a> Default for IterMut<'a, K, V> {
424 /// Creates an empty `btree_map::IterMut`.
425 ///
426 /// ```
427 /// # use std::collections::btree_map;
428 /// let iter: btree_map::IterMut<'_, u8, u8> = Default::default();
429 /// assert_eq!(iter.len(), 0);
430 /// ```
431 fn default() -> Self {
432 IterMut { range: Default::default(), length: 0, _marker: PhantomData {} }
433 }
434}
435
436/// An owning iterator over the entries of a `BTreeMap`, sorted by key.
437///
438/// This `struct` is created by the [`into_iter`] method on [`BTreeMap`]
439/// (provided by the [`IntoIterator`] trait). See its documentation for more.
440///
441/// [`into_iter`]: IntoIterator::into_iter
442#[stable(feature = "rust1", since = "1.0.0")]
443#[rustc_insignificant_dtor]
444pub struct IntoIter<
445 K,
446 V,
447 #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator + Clone = Global,
448> {
449 range: LazyLeafRange<marker::Dying, K, V>,
450 length: usize,
451 /// The BTreeMap will outlive this IntoIter so we don't care about drop order for `alloc`.
452 alloc: A,
453}
454
455impl<K, V, A: Allocator + Clone> IntoIter<K, V, A> {
456 /// Returns an iterator of references over the remaining items.
457 #[inline]
458 pub(super) fn iter(&self) -> Iter<'_, K, V> {
459 Iter { range: self.range.reborrow(), length: self.length }
460 }
461}
462
463#[stable(feature = "collection_debug", since = "1.17.0")]
464impl<K: Debug, V: Debug, A: Allocator + Clone> Debug for IntoIter<K, V, A> {
465 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
466 f.debug_list().entries(self.iter()).finish()
467 }
468}
469
470#[stable(feature = "default_iters", since = "1.70.0")]
471impl<K, V, A> Default for IntoIter<K, V, A>
472where
473 A: Allocator + Default + Clone,
474{
475 /// Creates an empty `btree_map::IntoIter`.
476 ///
477 /// ```
478 /// # use std::collections::btree_map;
479 /// let iter: btree_map::IntoIter<u8, u8> = Default::default();
480 /// assert_eq!(iter.len(), 0);
481 /// ```
482 fn default() -> Self {
483 IntoIter { range: Default::default(), length: 0, alloc: Default::default() }
484 }
485}
486
487/// An iterator over the keys of a `BTreeMap`.
488///
489/// This `struct` is created by the [`keys`] method on [`BTreeMap`]. See its
490/// documentation for more.
491///
492/// [`keys`]: BTreeMap::keys
493#[must_use = "iterators are lazy and do nothing unless consumed"]
494#[stable(feature = "rust1", since = "1.0.0")]
495pub struct Keys<'a, K, V> {
496 inner: Iter<'a, K, V>,
497}
498
499#[stable(feature = "collection_debug", since = "1.17.0")]
500impl<K: fmt::Debug, V> fmt::Debug for Keys<'_, K, V> {
501 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
502 f.debug_list().entries(self.clone()).finish()
503 }
504}
505
506/// An iterator over the values of a `BTreeMap`.
507///
508/// This `struct` is created by the [`values`] method on [`BTreeMap`]. See its
509/// documentation for more.
510///
511/// [`values`]: BTreeMap::values
512#[must_use = "iterators are lazy and do nothing unless consumed"]
513#[stable(feature = "rust1", since = "1.0.0")]
514pub struct Values<'a, K, V> {
515 inner: Iter<'a, K, V>,
516}
517
518#[stable(feature = "collection_debug", since = "1.17.0")]
519impl<K, V: fmt::Debug> fmt::Debug for Values<'_, K, V> {
520 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
521 f.debug_list().entries(self.clone()).finish()
522 }
523}
524
525/// A mutable iterator over the values of a `BTreeMap`.
526///
527/// This `struct` is created by the [`values_mut`] method on [`BTreeMap`]. See its
528/// documentation for more.
529///
530/// [`values_mut`]: BTreeMap::values_mut
531#[must_use = "iterators are lazy and do nothing unless consumed"]
532#[stable(feature = "map_values_mut", since = "1.10.0")]
533pub struct ValuesMut<'a, K, V> {
534 inner: IterMut<'a, K, V>,
535}
536
537#[stable(feature = "map_values_mut", since = "1.10.0")]
538impl<K, V: fmt::Debug> fmt::Debug for ValuesMut<'_, K, V> {
539 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
540 f.debug_list().entries(self.inner.iter().map(|(_, val)| val)).finish()
541 }
542}
543
544/// An owning iterator over the keys of a `BTreeMap`.
545///
546/// This `struct` is created by the [`into_keys`] method on [`BTreeMap`].
547/// See its documentation for more.
548///
549/// [`into_keys`]: BTreeMap::into_keys
550#[must_use = "iterators are lazy and do nothing unless consumed"]
551#[stable(feature = "map_into_keys_values", since = "1.54.0")]
552pub struct IntoKeys<
553 K,
554 V,
555 #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator + Clone = Global,
556> {
557 inner: IntoIter<K, V, A>,
558}
559
560#[stable(feature = "map_into_keys_values", since = "1.54.0")]
561impl<K: fmt::Debug, V, A: Allocator + Clone> fmt::Debug for IntoKeys<K, V, A> {
562 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
563 f.debug_list().entries(self.inner.iter().map(|(key, _)| key)).finish()
564 }
565}
566
567/// An owning iterator over the values of a `BTreeMap`.
568///
569/// This `struct` is created by the [`into_values`] method on [`BTreeMap`].
570/// See its documentation for more.
571///
572/// [`into_values`]: BTreeMap::into_values
573#[must_use = "iterators are lazy and do nothing unless consumed"]
574#[stable(feature = "map_into_keys_values", since = "1.54.0")]
575pub struct IntoValues<
576 K,
577 V,
578 #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator + Clone = Global,
579> {
580 inner: IntoIter<K, V, A>,
581}
582
583#[stable(feature = "map_into_keys_values", since = "1.54.0")]
584impl<K, V: fmt::Debug, A: Allocator + Clone> fmt::Debug for IntoValues<K, V, A> {
585 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
586 f.debug_list().entries(self.inner.iter().map(|(_, val)| val)).finish()
587 }
588}
589
590/// An iterator over a sub-range of entries in a `BTreeMap`.
591///
592/// This `struct` is created by the [`range`] method on [`BTreeMap`]. See its
593/// documentation for more.
594///
595/// [`range`]: BTreeMap::range
596#[must_use = "iterators are lazy and do nothing unless consumed"]
597#[stable(feature = "btree_range", since = "1.17.0")]
598pub struct Range<'a, K: 'a, V: 'a> {
599 inner: LeafRange<marker::Immut<'a>, K, V>,
600}
601
602#[stable(feature = "collection_debug", since = "1.17.0")]
603impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for Range<'_, K, V> {
604 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
605 f.debug_list().entries(self.clone()).finish()
606 }
607}
608
609/// A mutable iterator over a sub-range of entries in a `BTreeMap`.
610///
611/// This `struct` is created by the [`range_mut`] method on [`BTreeMap`]. See its
612/// documentation for more.
613///
614/// [`range_mut`]: BTreeMap::range_mut
615#[must_use = "iterators are lazy and do nothing unless consumed"]
616#[stable(feature = "btree_range", since = "1.17.0")]
617pub struct RangeMut<'a, K: 'a, V: 'a> {
618 inner: LeafRange<marker::ValMut<'a>, K, V>,
619
620 // Be invariant in `K` and `V`
621 _marker: PhantomData<&'a mut (K, V)>,
622}
623
624#[stable(feature = "collection_debug", since = "1.17.0")]
625impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for RangeMut<'_, K, V> {
626 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
627 let range = Range { inner: self.inner.reborrow() };
628 f.debug_list().entries(range).finish()
629 }
630}
631
632impl<K, V> BTreeMap<K, V> {
633 /// Makes a new, empty `BTreeMap`.
634 ///
635 /// Does not allocate anything on its own.
636 ///
637 /// # Examples
638 ///
639 /// ```
640 /// use std::collections::BTreeMap;
641 ///
642 /// let mut map = BTreeMap::new();
643 ///
644 /// // entries can now be inserted into the empty map
645 /// map.insert(1, "a");
646 /// ```
647 #[stable(feature = "rust1", since = "1.0.0")]
648 #[rustc_const_stable(feature = "const_btree_new", since = "1.66.0")]
649 #[inline]
650 #[must_use]
651 pub const fn new() -> BTreeMap<K, V> {
652 BTreeMap { root: None, length: 0, alloc: ManuallyDrop::new(Global), _marker: PhantomData }
653 }
654}
655
656impl<K, V, A: Allocator + Clone> BTreeMap<K, V, A> {
657 /// Clears the map, removing all elements.
658 ///
659 /// # Examples
660 ///
661 /// ```
662 /// use std::collections::BTreeMap;
663 ///
664 /// let mut a = BTreeMap::new();
665 /// a.insert(1, "a");
666 /// a.clear();
667 /// assert!(a.is_empty());
668 /// ```
669 #[stable(feature = "rust1", since = "1.0.0")]
670 pub fn clear(&mut self) {
671 // avoid moving the allocator
672 drop(BTreeMap {
673 root: mem::replace(&mut self.root, None),
674 length: mem::replace(&mut self.length, 0),
675 alloc: self.alloc.clone(),
676 _marker: PhantomData,
677 });
678 }
679
680 /// Makes a new empty BTreeMap with a reasonable choice for B.
681 ///
682 /// # Examples
683 ///
684 /// ```
685 /// # #![feature(allocator_api)]
686 /// # #![feature(btreemap_alloc)]
687 /// use std::collections::BTreeMap;
688 /// use std::alloc::Global;
689 ///
690 /// let mut map = BTreeMap::new_in(Global);
691 ///
692 /// // entries can now be inserted into the empty map
693 /// map.insert(1, "a");
694 /// ```
695 #[unstable(feature = "btreemap_alloc", issue = "32838")]
696 pub const fn new_in(alloc: A) -> BTreeMap<K, V, A> {
697 BTreeMap { root: None, length: 0, alloc: ManuallyDrop::new(alloc), _marker: PhantomData }
698 }
699}
700
701impl<K, V, A: Allocator + Clone> BTreeMap<K, V, A> {
702 /// Returns a reference to the value corresponding to the key.
703 ///
704 /// The key may be any borrowed form of the map's key type, but the ordering
705 /// on the borrowed form *must* match the ordering on the key type.
706 ///
707 /// # Examples
708 ///
709 /// ```
710 /// use std::collections::BTreeMap;
711 ///
712 /// let mut map = BTreeMap::new();
713 /// map.insert(1, "a");
714 /// assert_eq!(map.get(&1), Some(&"a"));
715 /// assert_eq!(map.get(&2), None);
716 /// ```
717 #[stable(feature = "rust1", since = "1.0.0")]
718 pub fn get<Q: ?Sized>(&self, key: &Q) -> Option<&V>
719 where
720 K: Borrow<Q> + Ord,
721 Q: Ord,
722 {
723 let root_node = self.root.as_ref()?.reborrow();
724 match root_node.search_tree(key) {
725 Found(handle) => Some(handle.into_kv().1),
726 GoDown(_) => None,
727 }
728 }
729
730 /// Returns the key-value pair corresponding to the supplied key. This is
731 /// potentially useful:
732 /// - for key types where non-identical keys can be considered equal;
733 /// - for getting the `&K` stored key value from a borrowed `&Q` lookup key; or
734 /// - for getting a reference to a key with the same lifetime as the collection.
735 ///
736 /// The supplied key may be any borrowed form of the map's key type, but the ordering
737 /// on the borrowed form *must* match the ordering on the key type.
738 ///
739 /// # Examples
740 ///
741 /// ```
742 /// use std::cmp::Ordering;
743 /// use std::collections::BTreeMap;
744 ///
745 /// #[derive(Clone, Copy, Debug)]
746 /// struct S {
747 /// id: u32,
748 /// # #[allow(unused)] // prevents a "field `name` is never read" error
749 /// name: &'static str, // ignored by equality and ordering operations
750 /// }
751 ///
752 /// impl PartialEq for S {
753 /// fn eq(&self, other: &S) -> bool {
754 /// self.id == other.id
755 /// }
756 /// }
757 ///
758 /// impl Eq for S {}
759 ///
760 /// impl PartialOrd for S {
761 /// fn partial_cmp(&self, other: &S) -> Option<Ordering> {
762 /// self.id.partial_cmp(&other.id)
763 /// }
764 /// }
765 ///
766 /// impl Ord for S {
767 /// fn cmp(&self, other: &S) -> Ordering {
768 /// self.id.cmp(&other.id)
769 /// }
770 /// }
771 ///
772 /// let j_a = S { id: 1, name: "Jessica" };
773 /// let j_b = S { id: 1, name: "Jess" };
774 /// let p = S { id: 2, name: "Paul" };
775 /// assert_eq!(j_a, j_b);
776 ///
777 /// let mut map = BTreeMap::new();
778 /// map.insert(j_a, "Paris");
779 /// assert_eq!(map.get_key_value(&j_a), Some((&j_a, &"Paris")));
780 /// assert_eq!(map.get_key_value(&j_b), Some((&j_a, &"Paris"))); // the notable case
781 /// assert_eq!(map.get_key_value(&p), None);
782 /// ```
783 #[stable(feature = "map_get_key_value", since = "1.40.0")]
784 pub fn get_key_value<Q: ?Sized>(&self, k: &Q) -> Option<(&K, &V)>
785 where
786 K: Borrow<Q> + Ord,
787 Q: Ord,
788 {
789 let root_node = self.root.as_ref()?.reborrow();
790 match root_node.search_tree(k) {
791 Found(handle) => Some(handle.into_kv()),
792 GoDown(_) => None,
793 }
794 }
795
796 /// Returns the first key-value pair in the map.
797 /// The key in this pair is the minimum key in the map.
798 ///
799 /// # Examples
800 ///
801 /// ```
802 /// use std::collections::BTreeMap;
803 ///
804 /// let mut map = BTreeMap::new();
805 /// assert_eq!(map.first_key_value(), None);
806 /// map.insert(1, "b");
807 /// map.insert(2, "a");
808 /// assert_eq!(map.first_key_value(), Some((&1, &"b")));
809 /// ```
810 #[stable(feature = "map_first_last", since = "1.66.0")]
811 pub fn first_key_value(&self) -> Option<(&K, &V)>
812 where
813 K: Ord,
814 {
815 let root_node = self.root.as_ref()?.reborrow();
816 root_node.first_leaf_edge().right_kv().ok().map(Handle::into_kv)
817 }
818
819 /// Returns the first entry in the map for in-place manipulation.
820 /// The key of this entry is the minimum key in the map.
821 ///
822 /// # Examples
823 ///
824 /// ```
825 /// use std::collections::BTreeMap;
826 ///
827 /// let mut map = BTreeMap::new();
828 /// map.insert(1, "a");
829 /// map.insert(2, "b");
830 /// if let Some(mut entry) = map.first_entry() {
831 /// if *entry.key() > 0 {
832 /// entry.insert("first");
833 /// }
834 /// }
835 /// assert_eq!(*map.get(&1).unwrap(), "first");
836 /// assert_eq!(*map.get(&2).unwrap(), "b");
837 /// ```
838 #[stable(feature = "map_first_last", since = "1.66.0")]
839 pub fn first_entry(&mut self) -> Option<OccupiedEntry<'_, K, V, A>>
840 where
841 K: Ord,
842 {
843 let (map, dormant_map) = DormantMutRef::new(self);
844 let root_node = map.root.as_mut()?.borrow_mut();
845 let kv = root_node.first_leaf_edge().right_kv().ok()?;
846 Some(OccupiedEntry {
847 handle: kv.forget_node_type(),
848 dormant_map,
849 alloc: (*map.alloc).clone(),
850 _marker: PhantomData,
851 })
852 }
853
854 /// Removes and returns the first element in the map.
855 /// The key of this element is the minimum key that was in the map.
856 ///
857 /// # Examples
858 ///
859 /// Draining elements in ascending order, while keeping a usable map each iteration.
860 ///
861 /// ```
862 /// use std::collections::BTreeMap;
863 ///
864 /// let mut map = BTreeMap::new();
865 /// map.insert(1, "a");
866 /// map.insert(2, "b");
867 /// while let Some((key, _val)) = map.pop_first() {
868 /// assert!(map.iter().all(|(k, _v)| *k > key));
869 /// }
870 /// assert!(map.is_empty());
871 /// ```
872 #[stable(feature = "map_first_last", since = "1.66.0")]
873 pub fn pop_first(&mut self) -> Option<(K, V)>
874 where
875 K: Ord,
876 {
877 self.first_entry().map(|entry| entry.remove_entry())
878 }
879
880 /// Returns the last key-value pair in the map.
881 /// The key in this pair is the maximum key in the map.
882 ///
883 /// # Examples
884 ///
885 /// ```
886 /// use std::collections::BTreeMap;
887 ///
888 /// let mut map = BTreeMap::new();
889 /// map.insert(1, "b");
890 /// map.insert(2, "a");
891 /// assert_eq!(map.last_key_value(), Some((&2, &"a")));
892 /// ```
893 #[stable(feature = "map_first_last", since = "1.66.0")]
894 pub fn last_key_value(&self) -> Option<(&K, &V)>
895 where
896 K: Ord,
897 {
898 let root_node = self.root.as_ref()?.reborrow();
899 root_node.last_leaf_edge().left_kv().ok().map(Handle::into_kv)
900 }
901
902 /// Returns the last entry in the map for in-place manipulation.
903 /// The key of this entry is the maximum key in the map.
904 ///
905 /// # Examples
906 ///
907 /// ```
908 /// use std::collections::BTreeMap;
909 ///
910 /// let mut map = BTreeMap::new();
911 /// map.insert(1, "a");
912 /// map.insert(2, "b");
913 /// if let Some(mut entry) = map.last_entry() {
914 /// if *entry.key() > 0 {
915 /// entry.insert("last");
916 /// }
917 /// }
918 /// assert_eq!(*map.get(&1).unwrap(), "a");
919 /// assert_eq!(*map.get(&2).unwrap(), "last");
920 /// ```
921 #[stable(feature = "map_first_last", since = "1.66.0")]
922 pub fn last_entry(&mut self) -> Option<OccupiedEntry<'_, K, V, A>>
923 where
924 K: Ord,
925 {
926 let (map, dormant_map) = DormantMutRef::new(self);
927 let root_node = map.root.as_mut()?.borrow_mut();
928 let kv = root_node.last_leaf_edge().left_kv().ok()?;
929 Some(OccupiedEntry {
930 handle: kv.forget_node_type(),
931 dormant_map,
932 alloc: (*map.alloc).clone(),
933 _marker: PhantomData,
934 })
935 }
936
937 /// Removes and returns the last element in the map.
938 /// The key of this element is the maximum key that was in the map.
939 ///
940 /// # Examples
941 ///
942 /// Draining elements in descending order, while keeping a usable map each iteration.
943 ///
944 /// ```
945 /// use std::collections::BTreeMap;
946 ///
947 /// let mut map = BTreeMap::new();
948 /// map.insert(1, "a");
949 /// map.insert(2, "b");
950 /// while let Some((key, _val)) = map.pop_last() {
951 /// assert!(map.iter().all(|(k, _v)| *k < key));
952 /// }
953 /// assert!(map.is_empty());
954 /// ```
955 #[stable(feature = "map_first_last", since = "1.66.0")]
956 pub fn pop_last(&mut self) -> Option<(K, V)>
957 where
958 K: Ord,
959 {
960 self.last_entry().map(|entry| entry.remove_entry())
961 }
962
963 /// Returns `true` if the map contains a value for the specified key.
964 ///
965 /// The key may be any borrowed form of the map's key type, but the ordering
966 /// on the borrowed form *must* match the ordering on the key type.
967 ///
968 /// # Examples
969 ///
970 /// ```
971 /// use std::collections::BTreeMap;
972 ///
973 /// let mut map = BTreeMap::new();
974 /// map.insert(1, "a");
975 /// assert_eq!(map.contains_key(&1), true);
976 /// assert_eq!(map.contains_key(&2), false);
977 /// ```
978 #[stable(feature = "rust1", since = "1.0.0")]
979 #[cfg_attr(not(test), rustc_diagnostic_item = "btreemap_contains_key")]
980 pub fn contains_key<Q: ?Sized>(&self, key: &Q) -> bool
981 where
982 K: Borrow<Q> + Ord,
983 Q: Ord,
984 {
985 self.get(key).is_some()
986 }
987
988 /// Returns a mutable reference to the value corresponding to the key.
989 ///
990 /// The key may be any borrowed form of the map's key type, but the ordering
991 /// on the borrowed form *must* match the ordering on the key type.
992 ///
993 /// # Examples
994 ///
995 /// ```
996 /// use std::collections::BTreeMap;
997 ///
998 /// let mut map = BTreeMap::new();
999 /// map.insert(1, "a");
1000 /// if let Some(x) = map.get_mut(&1) {
1001 /// *x = "b";
1002 /// }
1003 /// assert_eq!(map[&1], "b");
1004 /// ```
1005 // See `get` for implementation notes, this is basically a copy-paste with mut's added
1006 #[stable(feature = "rust1", since = "1.0.0")]
1007 pub fn get_mut<Q: ?Sized>(&mut self, key: &Q) -> Option<&mut V>
1008 where
1009 K: Borrow<Q> + Ord,
1010 Q: Ord,
1011 {
1012 let root_node = self.root.as_mut()?.borrow_mut();
1013 match root_node.search_tree(key) {
1014 Found(handle) => Some(handle.into_val_mut()),
1015 GoDown(_) => None,
1016 }
1017 }
1018
1019 /// Inserts a key-value pair into the map.
1020 ///
1021 /// If the map did not have this key present, `None` is returned.
1022 ///
1023 /// If the map did have this key present, the value is updated, and the old
1024 /// value is returned. The key is not updated, though; this matters for
1025 /// types that can be `==` without being identical. See the [module-level
1026 /// documentation] for more.
1027 ///
1028 /// [module-level documentation]: index.html#insert-and-complex-keys
1029 ///
1030 /// # Examples
1031 ///
1032 /// ```
1033 /// use std::collections::BTreeMap;
1034 ///
1035 /// let mut map = BTreeMap::new();
1036 /// assert_eq!(map.insert(37, "a"), None);
1037 /// assert_eq!(map.is_empty(), false);
1038 ///
1039 /// map.insert(37, "b");
1040 /// assert_eq!(map.insert(37, "c"), Some("b"));
1041 /// assert_eq!(map[&37], "c");
1042 /// ```
1043 #[stable(feature = "rust1", since = "1.0.0")]
1044 #[rustc_confusables("push", "put", "set")]
1045 #[cfg_attr(not(test), rustc_diagnostic_item = "btreemap_insert")]
1046 pub fn insert(&mut self, key: K, value: V) -> Option<V>
1047 where
1048 K: Ord,
1049 {
1050 match self.entry(key) {
1051 Occupied(mut entry) => Some(entry.insert(value)),
1052 Vacant(entry) => {
1053 entry.insert(value);
1054 None
1055 }
1056 }
1057 }
1058
1059 /// Tries to insert a key-value pair into the map, and returns
1060 /// a mutable reference to the value in the entry.
1061 ///
1062 /// If the map already had this key present, nothing is updated, and
1063 /// an error containing the occupied entry and the value is returned.
1064 ///
1065 /// # Examples
1066 ///
1067 /// ```
1068 /// #![feature(map_try_insert)]
1069 ///
1070 /// use std::collections::BTreeMap;
1071 ///
1072 /// let mut map = BTreeMap::new();
1073 /// assert_eq!(map.try_insert(37, "a").unwrap(), &"a");
1074 ///
1075 /// let err = map.try_insert(37, "b").unwrap_err();
1076 /// assert_eq!(err.entry.key(), &37);
1077 /// assert_eq!(err.entry.get(), &"a");
1078 /// assert_eq!(err.value, "b");
1079 /// ```
1080 #[unstable(feature = "map_try_insert", issue = "82766")]
1081 pub fn try_insert(&mut self, key: K, value: V) -> Result<&mut V, OccupiedError<'_, K, V, A>>
1082 where
1083 K: Ord,
1084 {
1085 match self.entry(key) {
1086 Occupied(entry) => Err(OccupiedError { entry, value }),
1087 Vacant(entry) => Ok(entry.insert(value)),
1088 }
1089 }
1090
1091 /// Removes a key from the map, returning the value at the key if the key
1092 /// was previously in the map.
1093 ///
1094 /// The key may be any borrowed form of the map's key type, but the ordering
1095 /// on the borrowed form *must* match the ordering on the key type.
1096 ///
1097 /// # Examples
1098 ///
1099 /// ```
1100 /// use std::collections::BTreeMap;
1101 ///
1102 /// let mut map = BTreeMap::new();
1103 /// map.insert(1, "a");
1104 /// assert_eq!(map.remove(&1), Some("a"));
1105 /// assert_eq!(map.remove(&1), None);
1106 /// ```
1107 #[stable(feature = "rust1", since = "1.0.0")]
1108 #[rustc_confusables("delete", "take")]
1109 pub fn remove<Q: ?Sized>(&mut self, key: &Q) -> Option<V>
1110 where
1111 K: Borrow<Q> + Ord,
1112 Q: Ord,
1113 {
1114 self.remove_entry(key).map(|(_, v)| v)
1115 }
1116
1117 /// Removes a key from the map, returning the stored key and value if the key
1118 /// was previously in the map.
1119 ///
1120 /// The key may be any borrowed form of the map's key type, but the ordering
1121 /// on the borrowed form *must* match the ordering on the key type.
1122 ///
1123 /// # Examples
1124 ///
1125 /// ```
1126 /// use std::collections::BTreeMap;
1127 ///
1128 /// let mut map = BTreeMap::new();
1129 /// map.insert(1, "a");
1130 /// assert_eq!(map.remove_entry(&1), Some((1, "a")));
1131 /// assert_eq!(map.remove_entry(&1), None);
1132 /// ```
1133 #[stable(feature = "btreemap_remove_entry", since = "1.45.0")]
1134 pub fn remove_entry<Q: ?Sized>(&mut self, key: &Q) -> Option<(K, V)>
1135 where
1136 K: Borrow<Q> + Ord,
1137 Q: Ord,
1138 {
1139 let (map, dormant_map) = DormantMutRef::new(self);
1140 let root_node = map.root.as_mut()?.borrow_mut();
1141 match root_node.search_tree(key) {
1142 Found(handle) => Some(
1143 OccupiedEntry {
1144 handle,
1145 dormant_map,
1146 alloc: (*map.alloc).clone(),
1147 _marker: PhantomData,
1148 }
1149 .remove_entry(),
1150 ),
1151 GoDown(_) => None,
1152 }
1153 }
1154
1155 /// Retains only the elements specified by the predicate.
1156 ///
1157 /// In other words, remove all pairs `(k, v)` for which `f(&k, &mut v)` returns `false`.
1158 /// The elements are visited in ascending key order.
1159 ///
1160 /// # Examples
1161 ///
1162 /// ```
1163 /// use std::collections::BTreeMap;
1164 ///
1165 /// let mut map: BTreeMap<i32, i32> = (0..8).map(|x| (x, x*10)).collect();
1166 /// // Keep only the elements with even-numbered keys.
1167 /// map.retain(|&k, _| k % 2 == 0);
1168 /// assert!(map.into_iter().eq(vec![(0, 0), (2, 20), (4, 40), (6, 60)]));
1169 /// ```
1170 #[inline]
1171 #[stable(feature = "btree_retain", since = "1.53.0")]
1172 pub fn retain<F>(&mut self, mut f: F)
1173 where
1174 K: Ord,
1175 F: FnMut(&K, &mut V) -> bool,
1176 {
1177 self.extract_if(.., |k, v| !f(k, v)).for_each(drop);
1178 }
1179
1180 /// Moves all elements from `other` into `self`, leaving `other` empty.
1181 ///
1182 /// If a key from `other` is already present in `self`, the respective
1183 /// value from `self` will be overwritten with the respective value from `other`.
1184 /// Similar to [`insert`], though, the key is not overwritten,
1185 /// which matters for types that can be `==` without being identical.
1186 ///
1187 /// [`insert`]: BTreeMap::insert
1188 ///
1189 /// # Examples
1190 ///
1191 /// ```
1192 /// use std::collections::BTreeMap;
1193 ///
1194 /// let mut a = BTreeMap::new();
1195 /// a.insert(1, "a");
1196 /// a.insert(2, "b");
1197 /// a.insert(3, "c"); // Note: Key (3) also present in b.
1198 ///
1199 /// let mut b = BTreeMap::new();
1200 /// b.insert(3, "d"); // Note: Key (3) also present in a.
1201 /// b.insert(4, "e");
1202 /// b.insert(5, "f");
1203 ///
1204 /// a.append(&mut b);
1205 ///
1206 /// assert_eq!(a.len(), 5);
1207 /// assert_eq!(b.len(), 0);
1208 ///
1209 /// assert_eq!(a[&1], "a");
1210 /// assert_eq!(a[&2], "b");
1211 /// assert_eq!(a[&3], "d"); // Note: "c" has been overwritten.
1212 /// assert_eq!(a[&4], "e");
1213 /// assert_eq!(a[&5], "f");
1214 /// ```
1215 #[stable(feature = "btree_append", since = "1.11.0")]
1216 pub fn append(&mut self, other: &mut Self)
1217 where
1218 K: Ord,
1219 A: Clone,
1220 {
1221 // Do we have to append anything at all?
1222 if other.is_empty() {
1223 return;
1224 }
1225
1226 // We can just swap `self` and `other` if `self` is empty.
1227 if self.is_empty() {
1228 mem::swap(self, other);
1229 return;
1230 }
1231
1232 let self_iter = mem::replace(self, Self::new_in((*self.alloc).clone())).into_iter();
1233 let other_iter = mem::replace(other, Self::new_in((*self.alloc).clone())).into_iter();
1234 let root = self.root.get_or_insert_with(|| Root::new((*self.alloc).clone()));
1235 root.append_from_sorted_iters(
1236 self_iter,
1237 other_iter,
1238 &mut self.length,
1239 (*self.alloc).clone(),
1240 )
1241 }
1242
1243 /// Moves all elements from `other` into `self`, leaving `other` empty.
1244 ///
1245 /// If a key from `other` is already present in `self`, then the `conflict`
1246 /// closure is used to return a value to `self`. The `conflict`
1247 /// closure takes in a borrow of `self`'s key, `self`'s value, and `other`'s value
1248 /// in that order.
1249 ///
1250 /// An example of why one might use this method over [`append`]
1251 /// is to combine `self`'s value with `other`'s value when their keys conflict.
1252 ///
1253 /// Similar to [`insert`], though, the key is not overwritten,
1254 /// which matters for types that can be `==` without being identical.
1255 ///
1256 /// [`insert`]: BTreeMap::insert
1257 /// [`append`]: BTreeMap::append
1258 ///
1259 /// # Examples
1260 ///
1261 /// ```
1262 /// #![feature(btree_merge)]
1263 /// use std::collections::BTreeMap;
1264 ///
1265 /// let mut a = BTreeMap::new();
1266 /// a.insert(1, String::from("a"));
1267 /// a.insert(2, String::from("b"));
1268 /// a.insert(3, String::from("c")); // Note: Key (3) also present in b.
1269 ///
1270 /// let mut b = BTreeMap::new();
1271 /// b.insert(3, String::from("d")); // Note: Key (3) also present in a.
1272 /// b.insert(4, String::from("e"));
1273 /// b.insert(5, String::from("f"));
1274 ///
1275 /// // concatenate a's value and b's value
1276 /// a.merge(b, |_, a_val, b_val| {
1277 /// format!("{a_val}{b_val}")
1278 /// });
1279 ///
1280 /// assert_eq!(a.len(), 5); // all of b's keys in a
1281 ///
1282 /// assert_eq!(a[&1], "a");
1283 /// assert_eq!(a[&2], "b");
1284 /// assert_eq!(a[&3], "cd"); // Note: "c" has been combined with "d".
1285 /// assert_eq!(a[&4], "e");
1286 /// assert_eq!(a[&5], "f");
1287 /// ```
1288 #[unstable(feature = "btree_merge", issue = "152152")]
1289 pub fn merge(&mut self, mut other: Self, mut conflict: impl FnMut(&K, V, V) -> V)
1290 where
1291 K: Ord,
1292 A: Clone,
1293 {
1294 // Do we have to append anything at all?
1295 if other.is_empty() {
1296 return;
1297 }
1298
1299 // We can just swap `self` and `other` if `self` is empty.
1300 if self.is_empty() {
1301 mem::swap(self, &mut other);
1302 return;
1303 }
1304
1305 let mut other_iter = other.into_iter();
1306 let (first_other_key, first_other_val) = other_iter.next().unwrap();
1307
1308 // find the first gap that has the smallest key greater than or equal to
1309 // the first key from other
1310 let mut self_cursor = self.lower_bound_mut(Bound::Included(&first_other_key));
1311
1312 if let Some((self_key, _)) = self_cursor.peek_next() {
1313 match K::cmp(self_key, &first_other_key) {
1314 Ordering::Equal => {
1315 // if `f` unwinds, the next entry is already removed leaving
1316 // the tree in valid state.
1317 // FIXME: Once `MaybeDangling` is implemented, we can optimize
1318 // this through using a drop handler and transmutating CursorMutKey<K, V>
1319 // to CursorMutKey<ManuallyDrop<K>, ManuallyDrop<V>> (see PR #152418)
1320 if let Some((k, v)) = self_cursor.remove_next() {
1321 // SAFETY: we remove the K, V out of the next entry,
1322 // apply 'f' to get a new (K, V), and insert it back
1323 // into the next entry that the cursor is pointing at
1324 let v = conflict(&k, v, first_other_val);
1325 unsafe { self_cursor.insert_after_unchecked(k, v) };
1326 }
1327 }
1328 Ordering::Greater =>
1329 // SAFETY: we know our other_key's ordering is less than self_key,
1330 // so inserting before will guarantee sorted order
1331 unsafe {
1332 self_cursor.insert_before_unchecked(first_other_key, first_other_val);
1333 },
1334 Ordering::Less => {
1335 unreachable!("Cursor's peek_next should return None.");
1336 }
1337 }
1338 } else {
1339 // SAFETY: reaching here means our cursor is at the end
1340 // self BTreeMap so we just insert other_key here
1341 unsafe {
1342 self_cursor.insert_before_unchecked(first_other_key, first_other_val);
1343 }
1344 }
1345
1346 for (other_key, other_val) in other_iter {
1347 loop {
1348 if let Some((self_key, _)) = self_cursor.peek_next() {
1349 match K::cmp(self_key, &other_key) {
1350 Ordering::Equal => {
1351 // if `f` unwinds, the next entry is already removed leaving
1352 // the tree in valid state.
1353 // FIXME: Once `MaybeDangling` is implemented, we can optimize
1354 // this through using a drop handler and transmutating CursorMutKey<K, V>
1355 // to CursorMutKey<ManuallyDrop<K>, ManuallyDrop<V>> (see PR #152418)
1356 if let Some((k, v)) = self_cursor.remove_next() {
1357 // SAFETY: we remove the K, V out of the next entry,
1358 // apply 'f' to get a new (K, V), and insert it back
1359 // into the next entry that the cursor is pointing at
1360 let v = conflict(&k, v, other_val);
1361 unsafe { self_cursor.insert_after_unchecked(k, v) };
1362 }
1363 break;
1364 }
1365 Ordering::Greater => {
1366 // SAFETY: we know our self_key's ordering is greater than other_key,
1367 // so inserting before will guarantee sorted order
1368 unsafe {
1369 self_cursor.insert_before_unchecked(other_key, other_val);
1370 }
1371 break;
1372 }
1373 Ordering::Less => {
1374 // FIXME: instead of doing a linear search here,
1375 // this can be optimized to search the tree by starting
1376 // from self_cursor and going towards the root and then
1377 // back down to the proper node -- that should probably
1378 // be a new method on Cursor*.
1379 self_cursor.next();
1380 }
1381 }
1382 } else {
1383 // FIXME: If we get here, that means all of other's keys are greater than
1384 // self's keys. For performance, this should really do a bulk insertion of items
1385 // from other_iter into the end of self `BTreeMap`. Maybe this should be
1386 // a method for Cursor*?
1387
1388 // SAFETY: reaching here means our cursor is at the end
1389 // self BTreeMap so we just insert other_key here
1390 unsafe {
1391 self_cursor.insert_before_unchecked(other_key, other_val);
1392 }
1393 break;
1394 }
1395 }
1396 }
1397 }
1398
1399 /// Constructs a double-ended iterator over a sub-range of elements in the map.
1400 /// The simplest way is to use the range syntax `min..max`, thus `range(min..max)` will
1401 /// yield elements from min (inclusive) to max (exclusive).
1402 /// The range may also be entered as `(Bound<T>, Bound<T>)`, so for example
1403 /// `range((Excluded(4), Included(10)))` will yield a left-exclusive, right-inclusive
1404 /// range from 4 to 10.
1405 ///
1406 /// # Panics
1407 ///
1408 /// Panics if range `start > end`.
1409 /// Panics if range `start == end` and both bounds are `Excluded`.
1410 ///
1411 /// # Examples
1412 ///
1413 /// ```
1414 /// use std::collections::BTreeMap;
1415 /// use std::ops::Bound::Included;
1416 ///
1417 /// let mut map = BTreeMap::new();
1418 /// map.insert(3, "a");
1419 /// map.insert(5, "b");
1420 /// map.insert(8, "c");
1421 /// for (&key, &value) in map.range((Included(&4), Included(&8))) {
1422 /// println!("{key}: {value}");
1423 /// }
1424 /// assert_eq!(Some((&5, &"b")), map.range(4..).next());
1425 /// ```
1426 #[stable(feature = "btree_range", since = "1.17.0")]
1427 pub fn range<T: ?Sized, R>(&self, range: R) -> Range<'_, K, V>
1428 where
1429 T: Ord,
1430 K: Borrow<T> + Ord,
1431 R: RangeBounds<T>,
1432 {
1433 if let Some(root) = &self.root {
1434 Range { inner: root.reborrow().range_search(range) }
1435 } else {
1436 Range { inner: LeafRange::none() }
1437 }
1438 }
1439
1440 /// Constructs a mutable double-ended iterator over a sub-range of elements in the map.
1441 /// The simplest way is to use the range syntax `min..max`, thus `range(min..max)` will
1442 /// yield elements from min (inclusive) to max (exclusive).
1443 /// The range may also be entered as `(Bound<T>, Bound<T>)`, so for example
1444 /// `range((Excluded(4), Included(10)))` will yield a left-exclusive, right-inclusive
1445 /// range from 4 to 10.
1446 ///
1447 /// # Panics
1448 ///
1449 /// Panics if range `start > end`.
1450 /// Panics if range `start == end` and both bounds are `Excluded`.
1451 ///
1452 /// # Examples
1453 ///
1454 /// ```
1455 /// use std::collections::BTreeMap;
1456 ///
1457 /// let mut map: BTreeMap<&str, i32> =
1458 /// [("Alice", 0), ("Bob", 0), ("Carol", 0), ("Cheryl", 0)].into();
1459 /// for (_, balance) in map.range_mut("B".."Cheryl") {
1460 /// *balance += 100;
1461 /// }
1462 /// for (name, balance) in &map {
1463 /// println!("{name} => {balance}");
1464 /// }
1465 /// ```
1466 #[stable(feature = "btree_range", since = "1.17.0")]
1467 pub fn range_mut<T: ?Sized, R>(&mut self, range: R) -> RangeMut<'_, K, V>
1468 where
1469 T: Ord,
1470 K: Borrow<T> + Ord,
1471 R: RangeBounds<T>,
1472 {
1473 if let Some(root) = &mut self.root {
1474 RangeMut { inner: root.borrow_valmut().range_search(range), _marker: PhantomData }
1475 } else {
1476 RangeMut { inner: LeafRange::none(), _marker: PhantomData }
1477 }
1478 }
1479
1480 /// Gets the given key's corresponding entry in the map for in-place manipulation.
1481 ///
1482 /// # Examples
1483 ///
1484 /// ```
1485 /// use std::collections::BTreeMap;
1486 ///
1487 /// let mut count: BTreeMap<&str, usize> = BTreeMap::new();
1488 ///
1489 /// // count the number of occurrences of letters in the vec
1490 /// for x in ["a", "b", "a", "c", "a", "b"] {
1491 /// count.entry(x).and_modify(|curr| *curr += 1).or_insert(1);
1492 /// }
1493 ///
1494 /// assert_eq!(count["a"], 3);
1495 /// assert_eq!(count["b"], 2);
1496 /// assert_eq!(count["c"], 1);
1497 /// ```
1498 #[stable(feature = "rust1", since = "1.0.0")]
1499 pub fn entry(&mut self, key: K) -> Entry<'_, K, V, A>
1500 where
1501 K: Ord,
1502 {
1503 let (map, dormant_map) = DormantMutRef::new(self);
1504 match map.root {
1505 None => Vacant(VacantEntry {
1506 key,
1507 handle: None,
1508 dormant_map,
1509 alloc: (*map.alloc).clone(),
1510 _marker: PhantomData,
1511 }),
1512 Some(ref mut root) => match root.borrow_mut().search_tree(&key) {
1513 Found(handle) => Occupied(OccupiedEntry {
1514 handle,
1515 dormant_map,
1516 alloc: (*map.alloc).clone(),
1517 _marker: PhantomData,
1518 }),
1519 GoDown(handle) => Vacant(VacantEntry {
1520 key,
1521 handle: Some(handle),
1522 dormant_map,
1523 alloc: (*map.alloc).clone(),
1524 _marker: PhantomData,
1525 }),
1526 },
1527 }
1528 }
1529
1530 /// Splits the collection into two at the given key. Returns everything after the given key,
1531 /// including the key. If the key is not present, the split will occur at the nearest
1532 /// greater key, or return an empty map if no such key exists.
1533 ///
1534 /// # Examples
1535 ///
1536 /// ```
1537 /// use std::collections::BTreeMap;
1538 ///
1539 /// let mut a = BTreeMap::new();
1540 /// a.insert(1, "a");
1541 /// a.insert(2, "b");
1542 /// a.insert(3, "c");
1543 /// a.insert(17, "d");
1544 /// a.insert(41, "e");
1545 ///
1546 /// let b = a.split_off(&3);
1547 ///
1548 /// assert_eq!(a.len(), 2);
1549 /// assert_eq!(b.len(), 3);
1550 ///
1551 /// assert_eq!(a[&1], "a");
1552 /// assert_eq!(a[&2], "b");
1553 ///
1554 /// assert_eq!(b[&3], "c");
1555 /// assert_eq!(b[&17], "d");
1556 /// assert_eq!(b[&41], "e");
1557 /// ```
1558 #[stable(feature = "btree_split_off", since = "1.11.0")]
1559 pub fn split_off<Q: ?Sized + Ord>(&mut self, key: &Q) -> Self
1560 where
1561 K: Borrow<Q> + Ord,
1562 A: Clone,
1563 {
1564 if self.is_empty() {
1565 return Self::new_in((*self.alloc).clone());
1566 }
1567
1568 let total_num = self.len();
1569 let left_root = self.root.as_mut().unwrap(); // unwrap succeeds because not empty
1570
1571 let right_root = left_root.split_off(key, (*self.alloc).clone());
1572
1573 let (new_left_len, right_len) = Root::calc_split_length(total_num, &left_root, &right_root);
1574 self.length = new_left_len;
1575
1576 BTreeMap {
1577 root: Some(right_root),
1578 length: right_len,
1579 alloc: self.alloc.clone(),
1580 _marker: PhantomData,
1581 }
1582 }
1583
1584 /// Creates an iterator that visits elements (key-value pairs) in the specified range in
1585 /// ascending key order and uses a closure to determine if an element
1586 /// should be removed.
1587 ///
1588 /// If the closure returns `true`, the element is removed from the map and
1589 /// yielded. If the closure returns `false`, or panics, the element remains
1590 /// in the map and will not be yielded.
1591 ///
1592 /// The iterator also lets you mutate the value of each element in the
1593 /// closure, regardless of whether you choose to keep or remove it.
1594 ///
1595 /// If the returned `ExtractIf` is not exhausted, e.g. because it is dropped without iterating
1596 /// or the iteration short-circuits, then the remaining elements will be retained.
1597 /// Use `extract_if().for_each(drop)` if you do not need the returned iterator,
1598 /// or [`retain`] with a negated predicate if you also do not need to restrict the range.
1599 ///
1600 /// [`retain`]: BTreeMap::retain
1601 ///
1602 /// # Examples
1603 ///
1604 /// ```
1605 /// use std::collections::BTreeMap;
1606 ///
1607 /// // Splitting a map into even and odd keys, reusing the original map:
1608 /// let mut map: BTreeMap<i32, i32> = (0..8).map(|x| (x, x)).collect();
1609 /// let evens: BTreeMap<_, _> = map.extract_if(.., |k, _v| k % 2 == 0).collect();
1610 /// let odds = map;
1611 /// assert_eq!(evens.keys().copied().collect::<Vec<_>>(), [0, 2, 4, 6]);
1612 /// assert_eq!(odds.keys().copied().collect::<Vec<_>>(), [1, 3, 5, 7]);
1613 ///
1614 /// // Splitting a map into low and high halves, reusing the original map:
1615 /// let mut map: BTreeMap<i32, i32> = (0..8).map(|x| (x, x)).collect();
1616 /// let low: BTreeMap<_, _> = map.extract_if(0..4, |_k, _v| true).collect();
1617 /// let high = map;
1618 /// assert_eq!(low.keys().copied().collect::<Vec<_>>(), [0, 1, 2, 3]);
1619 /// assert_eq!(high.keys().copied().collect::<Vec<_>>(), [4, 5, 6, 7]);
1620 /// ```
1621 #[stable(feature = "btree_extract_if", since = "1.91.0")]
1622 pub fn extract_if<F, R>(&mut self, range: R, pred: F) -> ExtractIf<'_, K, V, R, F, A>
1623 where
1624 K: Ord,
1625 R: RangeBounds<K>,
1626 F: FnMut(&K, &mut V) -> bool,
1627 {
1628 let (inner, alloc) = self.extract_if_inner(range);
1629 ExtractIf { pred, inner, alloc }
1630 }
1631
1632 pub(super) fn extract_if_inner<R>(&mut self, range: R) -> (ExtractIfInner<'_, K, V, R>, A)
1633 where
1634 K: Ord,
1635 R: RangeBounds<K>,
1636 {
1637 if let Some(root) = self.root.as_mut() {
1638 let (root, dormant_root) = DormantMutRef::new(root);
1639 let first = root.borrow_mut().lower_bound(SearchBound::from_range(range.start_bound()));
1640 (
1641 ExtractIfInner {
1642 length: &mut self.length,
1643 dormant_root: Some(dormant_root),
1644 cur_leaf_edge: Some(first),
1645 range,
1646 },
1647 (*self.alloc).clone(),
1648 )
1649 } else {
1650 (
1651 ExtractIfInner {
1652 length: &mut self.length,
1653 dormant_root: None,
1654 cur_leaf_edge: None,
1655 range,
1656 },
1657 (*self.alloc).clone(),
1658 )
1659 }
1660 }
1661
1662 /// Creates a consuming iterator visiting all the keys, in sorted order.
1663 /// The map cannot be used after calling this.
1664 /// The iterator element type is `K`.
1665 ///
1666 /// # Examples
1667 ///
1668 /// ```
1669 /// use std::collections::BTreeMap;
1670 ///
1671 /// let mut a = BTreeMap::new();
1672 /// a.insert(2, "b");
1673 /// a.insert(1, "a");
1674 ///
1675 /// let keys: Vec<i32> = a.into_keys().collect();
1676 /// assert_eq!(keys, [1, 2]);
1677 /// ```
1678 #[inline]
1679 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
1680 pub fn into_keys(self) -> IntoKeys<K, V, A> {
1681 IntoKeys { inner: self.into_iter() }
1682 }
1683
1684 /// Creates a consuming iterator visiting all the values, in order by key.
1685 /// The map cannot be used after calling this.
1686 /// The iterator element type is `V`.
1687 ///
1688 /// # Examples
1689 ///
1690 /// ```
1691 /// use std::collections::BTreeMap;
1692 ///
1693 /// let mut a = BTreeMap::new();
1694 /// a.insert(1, "hello");
1695 /// a.insert(2, "goodbye");
1696 ///
1697 /// let values: Vec<&str> = a.into_values().collect();
1698 /// assert_eq!(values, ["hello", "goodbye"]);
1699 /// ```
1700 #[inline]
1701 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
1702 pub fn into_values(self) -> IntoValues<K, V, A> {
1703 IntoValues { inner: self.into_iter() }
1704 }
1705
1706 /// Makes a `BTreeMap` from a sorted iterator.
1707 pub(crate) fn bulk_build_from_sorted_iter<I>(iter: I, alloc: A) -> Self
1708 where
1709 K: Ord,
1710 I: IntoIterator<Item = (K, V)>,
1711 {
1712 let mut root = Root::new(alloc.clone());
1713 let mut length = 0;
1714 root.bulk_push(DedupSortedIter::new(iter.into_iter()), &mut length, alloc.clone());
1715 BTreeMap { root: Some(root), length, alloc: ManuallyDrop::new(alloc), _marker: PhantomData }
1716 }
1717}
1718
1719#[stable(feature = "rust1", since = "1.0.0")]
1720impl<'a, K, V, A: Allocator + Clone> IntoIterator for &'a BTreeMap<K, V, A> {
1721 type Item = (&'a K, &'a V);
1722 type IntoIter = Iter<'a, K, V>;
1723
1724 fn into_iter(self) -> Iter<'a, K, V> {
1725 self.iter()
1726 }
1727}
1728
1729#[stable(feature = "rust1", since = "1.0.0")]
1730impl<'a, K: 'a, V: 'a> Iterator for Iter<'a, K, V> {
1731 type Item = (&'a K, &'a V);
1732
1733 fn next(&mut self) -> Option<(&'a K, &'a V)> {
1734 if self.length == 0 {
1735 None
1736 } else {
1737 self.length -= 1;
1738 Some(unsafe { self.range.next_unchecked() })
1739 }
1740 }
1741
1742 fn size_hint(&self) -> (usize, Option<usize>) {
1743 (self.length, Some(self.length))
1744 }
1745
1746 fn last(mut self) -> Option<(&'a K, &'a V)> {
1747 self.next_back()
1748 }
1749
1750 fn min(mut self) -> Option<(&'a K, &'a V)>
1751 where
1752 (&'a K, &'a V): Ord,
1753 {
1754 self.next()
1755 }
1756
1757 fn max(mut self) -> Option<(&'a K, &'a V)>
1758 where
1759 (&'a K, &'a V): Ord,
1760 {
1761 self.next_back()
1762 }
1763}
1764
1765#[stable(feature = "fused", since = "1.26.0")]
1766impl<K, V> FusedIterator for Iter<'_, K, V> {}
1767
1768#[stable(feature = "rust1", since = "1.0.0")]
1769impl<'a, K: 'a, V: 'a> DoubleEndedIterator for Iter<'a, K, V> {
1770 fn next_back(&mut self) -> Option<(&'a K, &'a V)> {
1771 if self.length == 0 {
1772 None
1773 } else {
1774 self.length -= 1;
1775 Some(unsafe { self.range.next_back_unchecked() })
1776 }
1777 }
1778}
1779
1780#[stable(feature = "rust1", since = "1.0.0")]
1781impl<K, V> ExactSizeIterator for Iter<'_, K, V> {
1782 fn len(&self) -> usize {
1783 self.length
1784 }
1785}
1786
1787#[unstable(feature = "trusted_len", issue = "37572")]
1788unsafe impl<K, V> TrustedLen for Iter<'_, K, V> {}
1789
1790#[stable(feature = "rust1", since = "1.0.0")]
1791impl<K, V> Clone for Iter<'_, K, V> {
1792 fn clone(&self) -> Self {
1793 Iter { range: self.range.clone(), length: self.length }
1794 }
1795}
1796
1797#[stable(feature = "rust1", since = "1.0.0")]
1798impl<'a, K, V, A: Allocator + Clone> IntoIterator for &'a mut BTreeMap<K, V, A> {
1799 type Item = (&'a K, &'a mut V);
1800 type IntoIter = IterMut<'a, K, V>;
1801
1802 fn into_iter(self) -> IterMut<'a, K, V> {
1803 self.iter_mut()
1804 }
1805}
1806
1807#[stable(feature = "rust1", since = "1.0.0")]
1808impl<'a, K, V> Iterator for IterMut<'a, K, V> {
1809 type Item = (&'a K, &'a mut V);
1810
1811 fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
1812 if self.length == 0 {
1813 None
1814 } else {
1815 self.length -= 1;
1816 Some(unsafe { self.range.next_unchecked() })
1817 }
1818 }
1819
1820 fn size_hint(&self) -> (usize, Option<usize>) {
1821 (self.length, Some(self.length))
1822 }
1823
1824 fn last(mut self) -> Option<(&'a K, &'a mut V)> {
1825 self.next_back()
1826 }
1827
1828 fn min(mut self) -> Option<(&'a K, &'a mut V)>
1829 where
1830 (&'a K, &'a mut V): Ord,
1831 {
1832 self.next()
1833 }
1834
1835 fn max(mut self) -> Option<(&'a K, &'a mut V)>
1836 where
1837 (&'a K, &'a mut V): Ord,
1838 {
1839 self.next_back()
1840 }
1841}
1842
1843#[stable(feature = "rust1", since = "1.0.0")]
1844impl<'a, K, V> DoubleEndedIterator for IterMut<'a, K, V> {
1845 fn next_back(&mut self) -> Option<(&'a K, &'a mut V)> {
1846 if self.length == 0 {
1847 None
1848 } else {
1849 self.length -= 1;
1850 Some(unsafe { self.range.next_back_unchecked() })
1851 }
1852 }
1853}
1854
1855#[stable(feature = "rust1", since = "1.0.0")]
1856impl<K, V> ExactSizeIterator for IterMut<'_, K, V> {
1857 fn len(&self) -> usize {
1858 self.length
1859 }
1860}
1861
1862#[unstable(feature = "trusted_len", issue = "37572")]
1863unsafe impl<K, V> TrustedLen for IterMut<'_, K, V> {}
1864
1865#[stable(feature = "fused", since = "1.26.0")]
1866impl<K, V> FusedIterator for IterMut<'_, K, V> {}
1867
1868impl<'a, K, V> IterMut<'a, K, V> {
1869 /// Returns an iterator of references over the remaining items.
1870 #[inline]
1871 pub(super) fn iter(&self) -> Iter<'_, K, V> {
1872 Iter { range: self.range.reborrow(), length: self.length }
1873 }
1874}
1875
1876#[stable(feature = "rust1", since = "1.0.0")]
1877impl<K, V, A: Allocator + Clone> IntoIterator for BTreeMap<K, V, A> {
1878 type Item = (K, V);
1879 type IntoIter = IntoIter<K, V, A>;
1880
1881 /// Gets an owning iterator over the entries of the map, sorted by key.
1882 fn into_iter(self) -> IntoIter<K, V, A> {
1883 let mut me = ManuallyDrop::new(self);
1884 if let Some(root) = me.root.take() {
1885 let full_range = root.into_dying().full_range();
1886
1887 IntoIter {
1888 range: full_range,
1889 length: me.length,
1890 alloc: unsafe { ManuallyDrop::take(&mut me.alloc) },
1891 }
1892 } else {
1893 IntoIter {
1894 range: LazyLeafRange::none(),
1895 length: 0,
1896 alloc: unsafe { ManuallyDrop::take(&mut me.alloc) },
1897 }
1898 }
1899 }
1900}
1901
1902#[stable(feature = "btree_drop", since = "1.7.0")]
1903impl<K, V, A: Allocator + Clone> Drop for IntoIter<K, V, A> {
1904 fn drop(&mut self) {
1905 struct DropGuard<'a, K, V, A: Allocator + Clone>(&'a mut IntoIter<K, V, A>);
1906
1907 impl<'a, K, V, A: Allocator + Clone> Drop for DropGuard<'a, K, V, A> {
1908 fn drop(&mut self) {
1909 // Continue the same loop we perform below. This only runs when unwinding, so we
1910 // don't have to care about panics this time (they'll abort).
1911 while let Some(kv) = self.0.dying_next() {
1912 // SAFETY: we consume the dying handle immediately.
1913 unsafe { kv.drop_key_val() };
1914 }
1915 }
1916 }
1917
1918 while let Some(kv) = self.dying_next() {
1919 let guard = DropGuard(self);
1920 // SAFETY: we don't touch the tree before consuming the dying handle.
1921 unsafe { kv.drop_key_val() };
1922 mem::forget(guard);
1923 }
1924 }
1925}
1926
1927impl<K, V, A: Allocator + Clone> IntoIter<K, V, A> {
1928 /// Core of a `next` method returning a dying KV handle,
1929 /// invalidated by further calls to this function and some others.
1930 fn dying_next(
1931 &mut self,
1932 ) -> Option<Handle<NodeRef<marker::Dying, K, V, marker::LeafOrInternal>, marker::KV>> {
1933 if self.length == 0 {
1934 self.range.deallocating_end(self.alloc.clone());
1935 None
1936 } else {
1937 self.length -= 1;
1938 Some(unsafe { self.range.deallocating_next_unchecked(self.alloc.clone()) })
1939 }
1940 }
1941
1942 /// Core of a `next_back` method returning a dying KV handle,
1943 /// invalidated by further calls to this function and some others.
1944 fn dying_next_back(
1945 &mut self,
1946 ) -> Option<Handle<NodeRef<marker::Dying, K, V, marker::LeafOrInternal>, marker::KV>> {
1947 if self.length == 0 {
1948 self.range.deallocating_end(self.alloc.clone());
1949 None
1950 } else {
1951 self.length -= 1;
1952 Some(unsafe { self.range.deallocating_next_back_unchecked(self.alloc.clone()) })
1953 }
1954 }
1955}
1956
1957#[stable(feature = "rust1", since = "1.0.0")]
1958impl<K, V, A: Allocator + Clone> Iterator for IntoIter<K, V, A> {
1959 type Item = (K, V);
1960
1961 fn next(&mut self) -> Option<(K, V)> {
1962 // SAFETY: we consume the dying handle immediately.
1963 self.dying_next().map(unsafe { |kv| kv.into_key_val() })
1964 }
1965
1966 fn size_hint(&self) -> (usize, Option<usize>) {
1967 (self.length, Some(self.length))
1968 }
1969}
1970
1971#[stable(feature = "rust1", since = "1.0.0")]
1972impl<K, V, A: Allocator + Clone> DoubleEndedIterator for IntoIter<K, V, A> {
1973 fn next_back(&mut self) -> Option<(K, V)> {
1974 // SAFETY: we consume the dying handle immediately.
1975 self.dying_next_back().map(unsafe { |kv| kv.into_key_val() })
1976 }
1977}
1978
1979#[stable(feature = "rust1", since = "1.0.0")]
1980impl<K, V, A: Allocator + Clone> ExactSizeIterator for IntoIter<K, V, A> {
1981 fn len(&self) -> usize {
1982 self.length
1983 }
1984}
1985
1986#[unstable(feature = "trusted_len", issue = "37572")]
1987unsafe impl<K, V, A: Allocator + Clone> TrustedLen for IntoIter<K, V, A> {}
1988
1989#[stable(feature = "fused", since = "1.26.0")]
1990impl<K, V, A: Allocator + Clone> FusedIterator for IntoIter<K, V, A> {}
1991
1992#[stable(feature = "rust1", since = "1.0.0")]
1993impl<'a, K, V> Iterator for Keys<'a, K, V> {
1994 type Item = &'a K;
1995
1996 fn next(&mut self) -> Option<&'a K> {
1997 self.inner.next().map(|(k, _)| k)
1998 }
1999
2000 fn size_hint(&self) -> (usize, Option<usize>) {
2001 self.inner.size_hint()
2002 }
2003
2004 fn last(mut self) -> Option<&'a K> {
2005 self.next_back()
2006 }
2007
2008 fn min(mut self) -> Option<&'a K>
2009 where
2010 &'a K: Ord,
2011 {
2012 self.next()
2013 }
2014
2015 fn max(mut self) -> Option<&'a K>
2016 where
2017 &'a K: Ord,
2018 {
2019 self.next_back()
2020 }
2021}
2022
2023#[stable(feature = "rust1", since = "1.0.0")]
2024impl<'a, K, V> DoubleEndedIterator for Keys<'a, K, V> {
2025 fn next_back(&mut self) -> Option<&'a K> {
2026 self.inner.next_back().map(|(k, _)| k)
2027 }
2028}
2029
2030#[stable(feature = "rust1", since = "1.0.0")]
2031impl<K, V> ExactSizeIterator for Keys<'_, K, V> {
2032 fn len(&self) -> usize {
2033 self.inner.len()
2034 }
2035}
2036
2037#[unstable(feature = "trusted_len", issue = "37572")]
2038unsafe impl<K, V> TrustedLen for Keys<'_, K, V> {}
2039
2040#[stable(feature = "fused", since = "1.26.0")]
2041impl<K, V> FusedIterator for Keys<'_, K, V> {}
2042
2043#[stable(feature = "rust1", since = "1.0.0")]
2044impl<K, V> Clone for Keys<'_, K, V> {
2045 fn clone(&self) -> Self {
2046 Keys { inner: self.inner.clone() }
2047 }
2048}
2049
2050#[stable(feature = "default_iters", since = "1.70.0")]
2051impl<K, V> Default for Keys<'_, K, V> {
2052 /// Creates an empty `btree_map::Keys`.
2053 ///
2054 /// ```
2055 /// # use std::collections::btree_map;
2056 /// let iter: btree_map::Keys<'_, u8, u8> = Default::default();
2057 /// assert_eq!(iter.len(), 0);
2058 /// ```
2059 fn default() -> Self {
2060 Keys { inner: Default::default() }
2061 }
2062}
2063
2064#[stable(feature = "rust1", since = "1.0.0")]
2065impl<'a, K, V> Iterator for Values<'a, K, V> {
2066 type Item = &'a V;
2067
2068 fn next(&mut self) -> Option<&'a V> {
2069 self.inner.next().map(|(_, v)| v)
2070 }
2071
2072 fn size_hint(&self) -> (usize, Option<usize>) {
2073 self.inner.size_hint()
2074 }
2075
2076 fn last(mut self) -> Option<&'a V> {
2077 self.next_back()
2078 }
2079}
2080
2081#[stable(feature = "rust1", since = "1.0.0")]
2082impl<'a, K, V> DoubleEndedIterator for Values<'a, K, V> {
2083 fn next_back(&mut self) -> Option<&'a V> {
2084 self.inner.next_back().map(|(_, v)| v)
2085 }
2086}
2087
2088#[stable(feature = "rust1", since = "1.0.0")]
2089impl<K, V> ExactSizeIterator for Values<'_, K, V> {
2090 fn len(&self) -> usize {
2091 self.inner.len()
2092 }
2093}
2094
2095#[unstable(feature = "trusted_len", issue = "37572")]
2096unsafe impl<K, V> TrustedLen for Values<'_, K, V> {}
2097
2098#[stable(feature = "fused", since = "1.26.0")]
2099impl<K, V> FusedIterator for Values<'_, K, V> {}
2100
2101#[stable(feature = "rust1", since = "1.0.0")]
2102impl<K, V> Clone for Values<'_, K, V> {
2103 fn clone(&self) -> Self {
2104 Values { inner: self.inner.clone() }
2105 }
2106}
2107
2108#[stable(feature = "default_iters", since = "1.70.0")]
2109impl<K, V> Default for Values<'_, K, V> {
2110 /// Creates an empty `btree_map::Values`.
2111 ///
2112 /// ```
2113 /// # use std::collections::btree_map;
2114 /// let iter: btree_map::Values<'_, u8, u8> = Default::default();
2115 /// assert_eq!(iter.len(), 0);
2116 /// ```
2117 fn default() -> Self {
2118 Values { inner: Default::default() }
2119 }
2120}
2121
2122/// An iterator produced by calling `extract_if` on BTreeMap.
2123#[stable(feature = "btree_extract_if", since = "1.91.0")]
2124#[must_use = "iterators are lazy and do nothing unless consumed; \
2125 use `retain` or `extract_if().for_each(drop)` to remove and discard elements"]
2126pub struct ExtractIf<
2127 'a,
2128 K,
2129 V,
2130 R,
2131 F,
2132 #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator + Clone = Global,
2133> {
2134 pred: F,
2135 inner: ExtractIfInner<'a, K, V, R>,
2136 /// The BTreeMap will outlive this IntoIter so we don't care about drop order for `alloc`.
2137 alloc: A,
2138}
2139
2140/// Most of the implementation of ExtractIf are generic over the type
2141/// of the predicate, thus also serving for BTreeSet::ExtractIf.
2142pub(super) struct ExtractIfInner<'a, K, V, R> {
2143 /// Reference to the length field in the borrowed map, updated live.
2144 length: &'a mut usize,
2145 /// Buried reference to the root field in the borrowed map.
2146 /// Wrapped in `Option` to allow drop handler to `take` it.
2147 dormant_root: Option<DormantMutRef<'a, Root<K, V>>>,
2148 /// Contains a leaf edge preceding the next element to be returned, or the last leaf edge.
2149 /// Empty if the map has no root, if iteration went beyond the last leaf edge,
2150 /// or if a panic occurred in the predicate.
2151 cur_leaf_edge: Option<Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge>>,
2152 /// Range over which iteration was requested. We don't need the left side, but we
2153 /// can't extract the right side without requiring K: Clone.
2154 range: R,
2155}
2156
2157#[stable(feature = "btree_extract_if", since = "1.91.0")]
2158impl<K, V, R, F, A> fmt::Debug for ExtractIf<'_, K, V, R, F, A>
2159where
2160 K: fmt::Debug,
2161 V: fmt::Debug,
2162 A: Allocator + Clone,
2163{
2164 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2165 f.debug_struct("ExtractIf").field("peek", &self.inner.peek()).finish_non_exhaustive()
2166 }
2167}
2168
2169#[stable(feature = "btree_extract_if", since = "1.91.0")]
2170impl<K, V, R, F, A: Allocator + Clone> Iterator for ExtractIf<'_, K, V, R, F, A>
2171where
2172 K: PartialOrd,
2173 R: RangeBounds<K>,
2174 F: FnMut(&K, &mut V) -> bool,
2175{
2176 type Item = (K, V);
2177
2178 fn next(&mut self) -> Option<(K, V)> {
2179 self.inner.next(&mut self.pred, self.alloc.clone())
2180 }
2181
2182 fn size_hint(&self) -> (usize, Option<usize>) {
2183 self.inner.size_hint()
2184 }
2185}
2186
2187impl<'a, K, V, R> ExtractIfInner<'a, K, V, R> {
2188 /// Allow Debug implementations to predict the next element.
2189 pub(super) fn peek(&self) -> Option<(&K, &V)> {
2190 let edge = self.cur_leaf_edge.as_ref()?;
2191 edge.reborrow().next_kv().ok().map(Handle::into_kv)
2192 }
2193
2194 /// Implementation of a typical `ExtractIf::next` method, given the predicate.
2195 pub(super) fn next<F, A: Allocator + Clone>(&mut self, pred: &mut F, alloc: A) -> Option<(K, V)>
2196 where
2197 K: PartialOrd,
2198 R: RangeBounds<K>,
2199 F: FnMut(&K, &mut V) -> bool,
2200 {
2201 while let Ok(mut kv) = self.cur_leaf_edge.take()?.next_kv() {
2202 let (k, v) = kv.kv_mut();
2203
2204 // On creation, we navigated directly to the left bound, so we need only check the
2205 // right bound here to decide whether to stop.
2206 match self.range.end_bound() {
2207 Bound::Included(ref end) if (*k).le(end) => (),
2208 Bound::Excluded(ref end) if (*k).lt(end) => (),
2209 Bound::Unbounded => (),
2210 _ => return None,
2211 }
2212
2213 if pred(k, v) {
2214 *self.length -= 1;
2215 let (kv, pos) = kv.remove_kv_tracking(
2216 || {
2217 // SAFETY: we will touch the root in a way that will not
2218 // invalidate the position returned.
2219 let root = unsafe { self.dormant_root.take().unwrap().awaken() };
2220 root.pop_internal_level(alloc.clone());
2221 self.dormant_root = Some(DormantMutRef::new(root).1);
2222 },
2223 alloc.clone(),
2224 );
2225 self.cur_leaf_edge = Some(pos);
2226 return Some(kv);
2227 }
2228 self.cur_leaf_edge = Some(kv.next_leaf_edge());
2229 }
2230 None
2231 }
2232
2233 /// Implementation of a typical `ExtractIf::size_hint` method.
2234 pub(super) fn size_hint(&self) -> (usize, Option<usize>) {
2235 // In most of the btree iterators, `self.length` is the number of elements
2236 // yet to be visited. Here, it includes elements that were visited and that
2237 // the predicate decided not to drain. Making this upper bound more tight
2238 // during iteration would require an extra field.
2239 (0, Some(*self.length))
2240 }
2241}
2242
2243#[stable(feature = "btree_extract_if", since = "1.91.0")]
2244impl<K, V, R, F> FusedIterator for ExtractIf<'_, K, V, R, F>
2245where
2246 K: PartialOrd,
2247 R: RangeBounds<K>,
2248 F: FnMut(&K, &mut V) -> bool,
2249{
2250}
2251
2252#[stable(feature = "btree_range", since = "1.17.0")]
2253impl<'a, K, V> Iterator for Range<'a, K, V> {
2254 type Item = (&'a K, &'a V);
2255
2256 fn next(&mut self) -> Option<(&'a K, &'a V)> {
2257 self.inner.next_checked()
2258 }
2259
2260 fn last(mut self) -> Option<(&'a K, &'a V)> {
2261 self.next_back()
2262 }
2263
2264 fn min(mut self) -> Option<(&'a K, &'a V)>
2265 where
2266 (&'a K, &'a V): Ord,
2267 {
2268 self.next()
2269 }
2270
2271 fn max(mut self) -> Option<(&'a K, &'a V)>
2272 where
2273 (&'a K, &'a V): Ord,
2274 {
2275 self.next_back()
2276 }
2277}
2278
2279#[stable(feature = "default_iters", since = "1.70.0")]
2280impl<K, V> Default for Range<'_, K, V> {
2281 /// Creates an empty `btree_map::Range`.
2282 ///
2283 /// ```
2284 /// # use std::collections::btree_map;
2285 /// let iter: btree_map::Range<'_, u8, u8> = Default::default();
2286 /// assert_eq!(iter.count(), 0);
2287 /// ```
2288 fn default() -> Self {
2289 Range { inner: Default::default() }
2290 }
2291}
2292
2293#[stable(feature = "default_iters_sequel", since = "1.82.0")]
2294impl<K, V> Default for RangeMut<'_, K, V> {
2295 /// Creates an empty `btree_map::RangeMut`.
2296 ///
2297 /// ```
2298 /// # use std::collections::btree_map;
2299 /// let iter: btree_map::RangeMut<'_, u8, u8> = Default::default();
2300 /// assert_eq!(iter.count(), 0);
2301 /// ```
2302 fn default() -> Self {
2303 RangeMut { inner: Default::default(), _marker: PhantomData }
2304 }
2305}
2306
2307#[stable(feature = "map_values_mut", since = "1.10.0")]
2308impl<'a, K, V> Iterator for ValuesMut<'a, K, V> {
2309 type Item = &'a mut V;
2310
2311 fn next(&mut self) -> Option<&'a mut V> {
2312 self.inner.next().map(|(_, v)| v)
2313 }
2314
2315 fn size_hint(&self) -> (usize, Option<usize>) {
2316 self.inner.size_hint()
2317 }
2318
2319 fn last(mut self) -> Option<&'a mut V> {
2320 self.next_back()
2321 }
2322}
2323
2324#[stable(feature = "map_values_mut", since = "1.10.0")]
2325impl<'a, K, V> DoubleEndedIterator for ValuesMut<'a, K, V> {
2326 fn next_back(&mut self) -> Option<&'a mut V> {
2327 self.inner.next_back().map(|(_, v)| v)
2328 }
2329}
2330
2331#[stable(feature = "map_values_mut", since = "1.10.0")]
2332impl<K, V> ExactSizeIterator for ValuesMut<'_, K, V> {
2333 fn len(&self) -> usize {
2334 self.inner.len()
2335 }
2336}
2337
2338#[unstable(feature = "trusted_len", issue = "37572")]
2339unsafe impl<K, V> TrustedLen for ValuesMut<'_, K, V> {}
2340
2341#[stable(feature = "fused", since = "1.26.0")]
2342impl<K, V> FusedIterator for ValuesMut<'_, K, V> {}
2343
2344#[stable(feature = "default_iters_sequel", since = "1.82.0")]
2345impl<K, V> Default for ValuesMut<'_, K, V> {
2346 /// Creates an empty `btree_map::ValuesMut`.
2347 ///
2348 /// ```
2349 /// # use std::collections::btree_map;
2350 /// let iter: btree_map::ValuesMut<'_, u8, u8> = Default::default();
2351 /// assert_eq!(iter.count(), 0);
2352 /// ```
2353 fn default() -> Self {
2354 ValuesMut { inner: Default::default() }
2355 }
2356}
2357
2358#[stable(feature = "map_into_keys_values", since = "1.54.0")]
2359impl<K, V, A: Allocator + Clone> Iterator for IntoKeys<K, V, A> {
2360 type Item = K;
2361
2362 fn next(&mut self) -> Option<K> {
2363 self.inner.next().map(|(k, _)| k)
2364 }
2365
2366 fn size_hint(&self) -> (usize, Option<usize>) {
2367 self.inner.size_hint()
2368 }
2369
2370 fn last(mut self) -> Option<K> {
2371 self.next_back()
2372 }
2373
2374 fn min(mut self) -> Option<K>
2375 where
2376 K: Ord,
2377 {
2378 self.next()
2379 }
2380
2381 fn max(mut self) -> Option<K>
2382 where
2383 K: Ord,
2384 {
2385 self.next_back()
2386 }
2387}
2388
2389#[stable(feature = "map_into_keys_values", since = "1.54.0")]
2390impl<K, V, A: Allocator + Clone> DoubleEndedIterator for IntoKeys<K, V, A> {
2391 fn next_back(&mut self) -> Option<K> {
2392 self.inner.next_back().map(|(k, _)| k)
2393 }
2394}
2395
2396#[stable(feature = "map_into_keys_values", since = "1.54.0")]
2397impl<K, V, A: Allocator + Clone> ExactSizeIterator for IntoKeys<K, V, A> {
2398 fn len(&self) -> usize {
2399 self.inner.len()
2400 }
2401}
2402
2403#[unstable(feature = "trusted_len", issue = "37572")]
2404unsafe impl<K, V, A: Allocator + Clone> TrustedLen for IntoKeys<K, V, A> {}
2405
2406#[stable(feature = "map_into_keys_values", since = "1.54.0")]
2407impl<K, V, A: Allocator + Clone> FusedIterator for IntoKeys<K, V, A> {}
2408
2409#[stable(feature = "default_iters", since = "1.70.0")]
2410impl<K, V, A> Default for IntoKeys<K, V, A>
2411where
2412 A: Allocator + Default + Clone,
2413{
2414 /// Creates an empty `btree_map::IntoKeys`.
2415 ///
2416 /// ```
2417 /// # use std::collections::btree_map;
2418 /// let iter: btree_map::IntoKeys<u8, u8> = Default::default();
2419 /// assert_eq!(iter.len(), 0);
2420 /// ```
2421 fn default() -> Self {
2422 IntoKeys { inner: Default::default() }
2423 }
2424}
2425
2426#[stable(feature = "map_into_keys_values", since = "1.54.0")]
2427impl<K, V, A: Allocator + Clone> Iterator for IntoValues<K, V, A> {
2428 type Item = V;
2429
2430 fn next(&mut self) -> Option<V> {
2431 self.inner.next().map(|(_, v)| v)
2432 }
2433
2434 fn size_hint(&self) -> (usize, Option<usize>) {
2435 self.inner.size_hint()
2436 }
2437
2438 fn last(mut self) -> Option<V> {
2439 self.next_back()
2440 }
2441}
2442
2443#[stable(feature = "map_into_keys_values", since = "1.54.0")]
2444impl<K, V, A: Allocator + Clone> DoubleEndedIterator for IntoValues<K, V, A> {
2445 fn next_back(&mut self) -> Option<V> {
2446 self.inner.next_back().map(|(_, v)| v)
2447 }
2448}
2449
2450#[stable(feature = "map_into_keys_values", since = "1.54.0")]
2451impl<K, V, A: Allocator + Clone> ExactSizeIterator for IntoValues<K, V, A> {
2452 fn len(&self) -> usize {
2453 self.inner.len()
2454 }
2455}
2456
2457#[unstable(feature = "trusted_len", issue = "37572")]
2458unsafe impl<K, V, A: Allocator + Clone> TrustedLen for IntoValues<K, V, A> {}
2459
2460#[stable(feature = "map_into_keys_values", since = "1.54.0")]
2461impl<K, V, A: Allocator + Clone> FusedIterator for IntoValues<K, V, A> {}
2462
2463#[stable(feature = "default_iters", since = "1.70.0")]
2464impl<K, V, A> Default for IntoValues<K, V, A>
2465where
2466 A: Allocator + Default + Clone,
2467{
2468 /// Creates an empty `btree_map::IntoValues`.
2469 ///
2470 /// ```
2471 /// # use std::collections::btree_map;
2472 /// let iter: btree_map::IntoValues<u8, u8> = Default::default();
2473 /// assert_eq!(iter.len(), 0);
2474 /// ```
2475 fn default() -> Self {
2476 IntoValues { inner: Default::default() }
2477 }
2478}
2479
2480#[stable(feature = "btree_range", since = "1.17.0")]
2481impl<'a, K, V> DoubleEndedIterator for Range<'a, K, V> {
2482 fn next_back(&mut self) -> Option<(&'a K, &'a V)> {
2483 self.inner.next_back_checked()
2484 }
2485}
2486
2487#[stable(feature = "fused", since = "1.26.0")]
2488impl<K, V> FusedIterator for Range<'_, K, V> {}
2489
2490#[stable(feature = "btree_range", since = "1.17.0")]
2491impl<K, V> Clone for Range<'_, K, V> {
2492 fn clone(&self) -> Self {
2493 Range { inner: self.inner.clone() }
2494 }
2495}
2496
2497#[stable(feature = "btree_range", since = "1.17.0")]
2498impl<'a, K, V> Iterator for RangeMut<'a, K, V> {
2499 type Item = (&'a K, &'a mut V);
2500
2501 fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
2502 self.inner.next_checked()
2503 }
2504
2505 fn last(mut self) -> Option<(&'a K, &'a mut V)> {
2506 self.next_back()
2507 }
2508
2509 fn min(mut self) -> Option<(&'a K, &'a mut V)>
2510 where
2511 (&'a K, &'a mut V): Ord,
2512 {
2513 self.next()
2514 }
2515
2516 fn max(mut self) -> Option<(&'a K, &'a mut V)>
2517 where
2518 (&'a K, &'a mut V): Ord,
2519 {
2520 self.next_back()
2521 }
2522}
2523
2524#[stable(feature = "btree_range", since = "1.17.0")]
2525impl<'a, K, V> DoubleEndedIterator for RangeMut<'a, K, V> {
2526 fn next_back(&mut self) -> Option<(&'a K, &'a mut V)> {
2527 self.inner.next_back_checked()
2528 }
2529}
2530
2531#[stable(feature = "fused", since = "1.26.0")]
2532impl<K, V> FusedIterator for RangeMut<'_, K, V> {}
2533
2534#[stable(feature = "rust1", since = "1.0.0")]
2535impl<K: Ord, V> FromIterator<(K, V)> for BTreeMap<K, V> {
2536 /// Constructs a `BTreeMap<K, V>` from an iterator of key-value pairs.
2537 ///
2538 /// If the iterator produces any pairs with equal keys,
2539 /// all but one of the corresponding values will be dropped.
2540 fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> BTreeMap<K, V> {
2541 let mut inputs: Vec<_> = iter.into_iter().collect();
2542
2543 if inputs.is_empty() {
2544 return BTreeMap::new();
2545 }
2546
2547 // use stable sort to preserve the insertion order.
2548 inputs.sort_by(|a, b| a.0.cmp(&b.0));
2549 BTreeMap::bulk_build_from_sorted_iter(inputs, Global)
2550 }
2551}
2552
2553#[stable(feature = "rust1", since = "1.0.0")]
2554impl<K: Ord, V, A: Allocator + Clone> Extend<(K, V)> for BTreeMap<K, V, A> {
2555 #[inline]
2556 fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) {
2557 iter.into_iter().for_each(move |(k, v)| {
2558 self.insert(k, v);
2559 });
2560 }
2561
2562 #[inline]
2563 fn extend_one(&mut self, (k, v): (K, V)) {
2564 self.insert(k, v);
2565 }
2566}
2567
2568#[stable(feature = "extend_ref", since = "1.2.0")]
2569impl<'a, K: Ord + Copy, V: Copy, A: Allocator + Clone> Extend<(&'a K, &'a V)>
2570 for BTreeMap<K, V, A>
2571{
2572 fn extend<I: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: I) {
2573 self.extend(iter.into_iter().map(|(&key, &value)| (key, value)));
2574 }
2575
2576 #[inline]
2577 fn extend_one(&mut self, (&k, &v): (&'a K, &'a V)) {
2578 self.insert(k, v);
2579 }
2580}
2581
2582#[stable(feature = "rust1", since = "1.0.0")]
2583impl<K: Hash, V: Hash, A: Allocator + Clone> Hash for BTreeMap<K, V, A> {
2584 fn hash<H: Hasher>(&self, state: &mut H) {
2585 state.write_length_prefix(self.len());
2586 for elt in self {
2587 elt.hash(state);
2588 }
2589 }
2590}
2591
2592#[stable(feature = "rust1", since = "1.0.0")]
2593impl<K, V> Default for BTreeMap<K, V> {
2594 /// Creates an empty `BTreeMap`.
2595 fn default() -> BTreeMap<K, V> {
2596 BTreeMap::new()
2597 }
2598}
2599
2600#[stable(feature = "rust1", since = "1.0.0")]
2601impl<K: PartialEq, V: PartialEq, A: Allocator + Clone> PartialEq for BTreeMap<K, V, A> {
2602 fn eq(&self, other: &BTreeMap<K, V, A>) -> bool {
2603 self.len() == other.len() && self.iter().zip(other).all(|(a, b)| a == b)
2604 }
2605}
2606
2607#[stable(feature = "rust1", since = "1.0.0")]
2608impl<K: Eq, V: Eq, A: Allocator + Clone> Eq for BTreeMap<K, V, A> {}
2609
2610#[stable(feature = "rust1", since = "1.0.0")]
2611impl<K: PartialOrd, V: PartialOrd, A: Allocator + Clone> PartialOrd for BTreeMap<K, V, A> {
2612 #[inline]
2613 fn partial_cmp(&self, other: &BTreeMap<K, V, A>) -> Option<Ordering> {
2614 self.iter().partial_cmp(other.iter())
2615 }
2616}
2617
2618#[stable(feature = "rust1", since = "1.0.0")]
2619impl<K: Ord, V: Ord, A: Allocator + Clone> Ord for BTreeMap<K, V, A> {
2620 #[inline]
2621 fn cmp(&self, other: &BTreeMap<K, V, A>) -> Ordering {
2622 self.iter().cmp(other.iter())
2623 }
2624}
2625
2626#[stable(feature = "rust1", since = "1.0.0")]
2627impl<K: Debug, V: Debug, A: Allocator + Clone> Debug for BTreeMap<K, V, A> {
2628 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2629 f.debug_map().entries(self.iter()).finish()
2630 }
2631}
2632
2633#[stable(feature = "rust1", since = "1.0.0")]
2634impl<K, Q: ?Sized, V, A: Allocator + Clone> Index<&Q> for BTreeMap<K, V, A>
2635where
2636 K: Borrow<Q> + Ord,
2637 Q: Ord,
2638{
2639 type Output = V;
2640
2641 /// Returns a reference to the value corresponding to the supplied key.
2642 ///
2643 /// # Panics
2644 ///
2645 /// Panics if the key is not present in the `BTreeMap`.
2646 #[inline]
2647 fn index(&self, key: &Q) -> &V {
2648 self.get(key).expect("no entry found for key")
2649 }
2650}
2651
2652#[stable(feature = "std_collections_from_array", since = "1.56.0")]
2653impl<K: Ord, V, const N: usize> From<[(K, V); N]> for BTreeMap<K, V> {
2654 /// Converts a `[(K, V); N]` into a `BTreeMap<K, V>`.
2655 ///
2656 /// If any entries in the array have equal keys,
2657 /// all but one of the corresponding values will be dropped.
2658 ///
2659 /// ```
2660 /// use std::collections::BTreeMap;
2661 ///
2662 /// let map1 = BTreeMap::from([(1, 2), (3, 4)]);
2663 /// let map2: BTreeMap<_, _> = [(1, 2), (3, 4)].into();
2664 /// assert_eq!(map1, map2);
2665 /// ```
2666 fn from(mut arr: [(K, V); N]) -> Self {
2667 if N == 0 {
2668 return BTreeMap::new();
2669 }
2670
2671 // use stable sort to preserve the insertion order.
2672 arr.sort_by(|a, b| a.0.cmp(&b.0));
2673 BTreeMap::bulk_build_from_sorted_iter(arr, Global)
2674 }
2675}
2676
2677impl<K, V, A: Allocator + Clone> BTreeMap<K, V, A> {
2678 /// Gets an iterator over the entries of the map, sorted by key.
2679 ///
2680 /// # Examples
2681 ///
2682 /// ```
2683 /// use std::collections::BTreeMap;
2684 ///
2685 /// let mut map = BTreeMap::new();
2686 /// map.insert(3, "c");
2687 /// map.insert(2, "b");
2688 /// map.insert(1, "a");
2689 ///
2690 /// for (key, value) in map.iter() {
2691 /// println!("{key}: {value}");
2692 /// }
2693 ///
2694 /// let (first_key, first_value) = map.iter().next().unwrap();
2695 /// assert_eq!((*first_key, *first_value), (1, "a"));
2696 /// ```
2697 #[stable(feature = "rust1", since = "1.0.0")]
2698 pub fn iter(&self) -> Iter<'_, K, V> {
2699 if let Some(root) = &self.root {
2700 let full_range = root.reborrow().full_range();
2701
2702 Iter { range: full_range, length: self.length }
2703 } else {
2704 Iter { range: LazyLeafRange::none(), length: 0 }
2705 }
2706 }
2707
2708 /// Gets a mutable iterator over the entries of the map, sorted by key.
2709 ///
2710 /// # Examples
2711 ///
2712 /// ```
2713 /// use std::collections::BTreeMap;
2714 ///
2715 /// let mut map = BTreeMap::from([
2716 /// ("a", 1),
2717 /// ("b", 2),
2718 /// ("c", 3),
2719 /// ]);
2720 ///
2721 /// // add 10 to the value if the key isn't "a"
2722 /// for (key, value) in map.iter_mut() {
2723 /// if key != &"a" {
2724 /// *value += 10;
2725 /// }
2726 /// }
2727 /// ```
2728 #[stable(feature = "rust1", since = "1.0.0")]
2729 pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {
2730 if let Some(root) = &mut self.root {
2731 let full_range = root.borrow_valmut().full_range();
2732
2733 IterMut { range: full_range, length: self.length, _marker: PhantomData }
2734 } else {
2735 IterMut { range: LazyLeafRange::none(), length: 0, _marker: PhantomData }
2736 }
2737 }
2738
2739 /// Gets an iterator over the keys of the map, in sorted order.
2740 ///
2741 /// # Examples
2742 ///
2743 /// ```
2744 /// use std::collections::BTreeMap;
2745 ///
2746 /// let mut a = BTreeMap::new();
2747 /// a.insert(2, "b");
2748 /// a.insert(1, "a");
2749 ///
2750 /// let keys: Vec<_> = a.keys().cloned().collect();
2751 /// assert_eq!(keys, [1, 2]);
2752 /// ```
2753 #[stable(feature = "rust1", since = "1.0.0")]
2754 pub fn keys(&self) -> Keys<'_, K, V> {
2755 Keys { inner: self.iter() }
2756 }
2757
2758 /// Gets an iterator over the values of the map, in order by key.
2759 ///
2760 /// # Examples
2761 ///
2762 /// ```
2763 /// use std::collections::BTreeMap;
2764 ///
2765 /// let mut a = BTreeMap::new();
2766 /// a.insert(1, "hello");
2767 /// a.insert(2, "goodbye");
2768 ///
2769 /// let values: Vec<&str> = a.values().cloned().collect();
2770 /// assert_eq!(values, ["hello", "goodbye"]);
2771 /// ```
2772 #[stable(feature = "rust1", since = "1.0.0")]
2773 pub fn values(&self) -> Values<'_, K, V> {
2774 Values { inner: self.iter() }
2775 }
2776
2777 /// Gets a mutable iterator over the values of the map, in order by key.
2778 ///
2779 /// # Examples
2780 ///
2781 /// ```
2782 /// use std::collections::BTreeMap;
2783 ///
2784 /// let mut a = BTreeMap::new();
2785 /// a.insert(1, String::from("hello"));
2786 /// a.insert(2, String::from("goodbye"));
2787 ///
2788 /// for value in a.values_mut() {
2789 /// value.push_str("!");
2790 /// }
2791 ///
2792 /// let values: Vec<String> = a.values().cloned().collect();
2793 /// assert_eq!(values, [String::from("hello!"),
2794 /// String::from("goodbye!")]);
2795 /// ```
2796 #[stable(feature = "map_values_mut", since = "1.10.0")]
2797 pub fn values_mut(&mut self) -> ValuesMut<'_, K, V> {
2798 ValuesMut { inner: self.iter_mut() }
2799 }
2800
2801 /// Returns the number of elements in the map.
2802 ///
2803 /// # Examples
2804 ///
2805 /// ```
2806 /// use std::collections::BTreeMap;
2807 ///
2808 /// let mut a = BTreeMap::new();
2809 /// assert_eq!(a.len(), 0);
2810 /// a.insert(1, "a");
2811 /// assert_eq!(a.len(), 1);
2812 /// ```
2813 #[must_use]
2814 #[stable(feature = "rust1", since = "1.0.0")]
2815 #[rustc_const_unstable(
2816 feature = "const_btree_len",
2817 issue = "71835",
2818 implied_by = "const_btree_new"
2819 )]
2820 #[rustc_confusables("length", "size")]
2821 pub const fn len(&self) -> usize {
2822 self.length
2823 }
2824
2825 /// Returns `true` if the map contains no elements.
2826 ///
2827 /// # Examples
2828 ///
2829 /// ```
2830 /// use std::collections::BTreeMap;
2831 ///
2832 /// let mut a = BTreeMap::new();
2833 /// assert!(a.is_empty());
2834 /// a.insert(1, "a");
2835 /// assert!(!a.is_empty());
2836 /// ```
2837 #[must_use]
2838 #[stable(feature = "rust1", since = "1.0.0")]
2839 #[rustc_const_unstable(
2840 feature = "const_btree_len",
2841 issue = "71835",
2842 implied_by = "const_btree_new"
2843 )]
2844 pub const fn is_empty(&self) -> bool {
2845 self.len() == 0
2846 }
2847
2848 /// Returns a [`Cursor`] pointing at the gap before the smallest key
2849 /// greater than the given bound.
2850 ///
2851 /// Passing `Bound::Included(x)` will return a cursor pointing to the
2852 /// gap before the smallest key greater than or equal to `x`.
2853 ///
2854 /// Passing `Bound::Excluded(x)` will return a cursor pointing to the
2855 /// gap before the smallest key greater than `x`.
2856 ///
2857 /// Passing `Bound::Unbounded` will return a cursor pointing to the
2858 /// gap before the smallest key in the map.
2859 ///
2860 /// # Examples
2861 ///
2862 /// ```
2863 /// #![feature(btree_cursors)]
2864 ///
2865 /// use std::collections::BTreeMap;
2866 /// use std::ops::Bound;
2867 ///
2868 /// let map = BTreeMap::from([
2869 /// (1, "a"),
2870 /// (2, "b"),
2871 /// (3, "c"),
2872 /// (4, "d"),
2873 /// ]);
2874 ///
2875 /// let cursor = map.lower_bound(Bound::Included(&2));
2876 /// assert_eq!(cursor.peek_prev(), Some((&1, &"a")));
2877 /// assert_eq!(cursor.peek_next(), Some((&2, &"b")));
2878 ///
2879 /// let cursor = map.lower_bound(Bound::Excluded(&2));
2880 /// assert_eq!(cursor.peek_prev(), Some((&2, &"b")));
2881 /// assert_eq!(cursor.peek_next(), Some((&3, &"c")));
2882 ///
2883 /// let cursor = map.lower_bound(Bound::Unbounded);
2884 /// assert_eq!(cursor.peek_prev(), None);
2885 /// assert_eq!(cursor.peek_next(), Some((&1, &"a")));
2886 /// ```
2887 #[unstable(feature = "btree_cursors", issue = "107540")]
2888 pub fn lower_bound<Q: ?Sized>(&self, bound: Bound<&Q>) -> Cursor<'_, K, V>
2889 where
2890 K: Borrow<Q> + Ord,
2891 Q: Ord,
2892 {
2893 let root_node = match self.root.as_ref() {
2894 None => return Cursor { current: None, root: None },
2895 Some(root) => root.reborrow(),
2896 };
2897 let edge = root_node.lower_bound(SearchBound::from_range(bound));
2898 Cursor { current: Some(edge), root: self.root.as_ref() }
2899 }
2900
2901 /// Returns a [`CursorMut`] pointing at the gap before the smallest key
2902 /// greater than the given bound.
2903 ///
2904 /// Passing `Bound::Included(x)` will return a cursor pointing to the
2905 /// gap before the smallest key greater than or equal to `x`.
2906 ///
2907 /// Passing `Bound::Excluded(x)` will return a cursor pointing to the
2908 /// gap before the smallest key greater than `x`.
2909 ///
2910 /// Passing `Bound::Unbounded` will return a cursor pointing to the
2911 /// gap before the smallest key in the map.
2912 ///
2913 /// # Examples
2914 ///
2915 /// ```
2916 /// #![feature(btree_cursors)]
2917 ///
2918 /// use std::collections::BTreeMap;
2919 /// use std::ops::Bound;
2920 ///
2921 /// let mut map = BTreeMap::from([
2922 /// (1, "a"),
2923 /// (2, "b"),
2924 /// (3, "c"),
2925 /// (4, "d"),
2926 /// ]);
2927 ///
2928 /// let mut cursor = map.lower_bound_mut(Bound::Included(&2));
2929 /// assert_eq!(cursor.peek_prev(), Some((&1, &mut "a")));
2930 /// assert_eq!(cursor.peek_next(), Some((&2, &mut "b")));
2931 ///
2932 /// let mut cursor = map.lower_bound_mut(Bound::Excluded(&2));
2933 /// assert_eq!(cursor.peek_prev(), Some((&2, &mut "b")));
2934 /// assert_eq!(cursor.peek_next(), Some((&3, &mut "c")));
2935 ///
2936 /// let mut cursor = map.lower_bound_mut(Bound::Unbounded);
2937 /// assert_eq!(cursor.peek_prev(), None);
2938 /// assert_eq!(cursor.peek_next(), Some((&1, &mut "a")));
2939 /// ```
2940 #[unstable(feature = "btree_cursors", issue = "107540")]
2941 pub fn lower_bound_mut<Q: ?Sized>(&mut self, bound: Bound<&Q>) -> CursorMut<'_, K, V, A>
2942 where
2943 K: Borrow<Q> + Ord,
2944 Q: Ord,
2945 {
2946 let (root, dormant_root) = DormantMutRef::new(&mut self.root);
2947 let root_node = match root.as_mut() {
2948 None => {
2949 return CursorMut {
2950 inner: CursorMutKey {
2951 current: None,
2952 root: dormant_root,
2953 length: &mut self.length,
2954 alloc: &mut *self.alloc,
2955 },
2956 };
2957 }
2958 Some(root) => root.borrow_mut(),
2959 };
2960 let edge = root_node.lower_bound(SearchBound::from_range(bound));
2961 CursorMut {
2962 inner: CursorMutKey {
2963 current: Some(edge),
2964 root: dormant_root,
2965 length: &mut self.length,
2966 alloc: &mut *self.alloc,
2967 },
2968 }
2969 }
2970
2971 /// Returns a [`Cursor`] pointing at the gap after the greatest key
2972 /// smaller than the given bound.
2973 ///
2974 /// Passing `Bound::Included(x)` will return a cursor pointing to the
2975 /// gap after the greatest key smaller than or equal to `x`.
2976 ///
2977 /// Passing `Bound::Excluded(x)` will return a cursor pointing to the
2978 /// gap after the greatest key smaller than `x`.
2979 ///
2980 /// Passing `Bound::Unbounded` will return a cursor pointing to the
2981 /// gap after the greatest key in the map.
2982 ///
2983 /// # Examples
2984 ///
2985 /// ```
2986 /// #![feature(btree_cursors)]
2987 ///
2988 /// use std::collections::BTreeMap;
2989 /// use std::ops::Bound;
2990 ///
2991 /// let map = BTreeMap::from([
2992 /// (1, "a"),
2993 /// (2, "b"),
2994 /// (3, "c"),
2995 /// (4, "d"),
2996 /// ]);
2997 ///
2998 /// let cursor = map.upper_bound(Bound::Included(&3));
2999 /// assert_eq!(cursor.peek_prev(), Some((&3, &"c")));
3000 /// assert_eq!(cursor.peek_next(), Some((&4, &"d")));
3001 ///
3002 /// let cursor = map.upper_bound(Bound::Excluded(&3));
3003 /// assert_eq!(cursor.peek_prev(), Some((&2, &"b")));
3004 /// assert_eq!(cursor.peek_next(), Some((&3, &"c")));
3005 ///
3006 /// let cursor = map.upper_bound(Bound::Unbounded);
3007 /// assert_eq!(cursor.peek_prev(), Some((&4, &"d")));
3008 /// assert_eq!(cursor.peek_next(), None);
3009 /// ```
3010 #[unstable(feature = "btree_cursors", issue = "107540")]
3011 pub fn upper_bound<Q: ?Sized>(&self, bound: Bound<&Q>) -> Cursor<'_, K, V>
3012 where
3013 K: Borrow<Q> + Ord,
3014 Q: Ord,
3015 {
3016 let root_node = match self.root.as_ref() {
3017 None => return Cursor { current: None, root: None },
3018 Some(root) => root.reborrow(),
3019 };
3020 let edge = root_node.upper_bound(SearchBound::from_range(bound));
3021 Cursor { current: Some(edge), root: self.root.as_ref() }
3022 }
3023
3024 /// Returns a [`CursorMut`] pointing at the gap after the greatest key
3025 /// smaller than the given bound.
3026 ///
3027 /// Passing `Bound::Included(x)` will return a cursor pointing to the
3028 /// gap after the greatest key smaller than or equal to `x`.
3029 ///
3030 /// Passing `Bound::Excluded(x)` will return a cursor pointing to the
3031 /// gap after the greatest key smaller than `x`.
3032 ///
3033 /// Passing `Bound::Unbounded` will return a cursor pointing to the
3034 /// gap after the greatest key in the map.
3035 ///
3036 /// # Examples
3037 ///
3038 /// ```
3039 /// #![feature(btree_cursors)]
3040 ///
3041 /// use std::collections::BTreeMap;
3042 /// use std::ops::Bound;
3043 ///
3044 /// let mut map = BTreeMap::from([
3045 /// (1, "a"),
3046 /// (2, "b"),
3047 /// (3, "c"),
3048 /// (4, "d"),
3049 /// ]);
3050 ///
3051 /// let mut cursor = map.upper_bound_mut(Bound::Included(&3));
3052 /// assert_eq!(cursor.peek_prev(), Some((&3, &mut "c")));
3053 /// assert_eq!(cursor.peek_next(), Some((&4, &mut "d")));
3054 ///
3055 /// let mut cursor = map.upper_bound_mut(Bound::Excluded(&3));
3056 /// assert_eq!(cursor.peek_prev(), Some((&2, &mut "b")));
3057 /// assert_eq!(cursor.peek_next(), Some((&3, &mut "c")));
3058 ///
3059 /// let mut cursor = map.upper_bound_mut(Bound::Unbounded);
3060 /// assert_eq!(cursor.peek_prev(), Some((&4, &mut "d")));
3061 /// assert_eq!(cursor.peek_next(), None);
3062 /// ```
3063 #[unstable(feature = "btree_cursors", issue = "107540")]
3064 pub fn upper_bound_mut<Q: ?Sized>(&mut self, bound: Bound<&Q>) -> CursorMut<'_, K, V, A>
3065 where
3066 K: Borrow<Q> + Ord,
3067 Q: Ord,
3068 {
3069 let (root, dormant_root) = DormantMutRef::new(&mut self.root);
3070 let root_node = match root.as_mut() {
3071 None => {
3072 return CursorMut {
3073 inner: CursorMutKey {
3074 current: None,
3075 root: dormant_root,
3076 length: &mut self.length,
3077 alloc: &mut *self.alloc,
3078 },
3079 };
3080 }
3081 Some(root) => root.borrow_mut(),
3082 };
3083 let edge = root_node.upper_bound(SearchBound::from_range(bound));
3084 CursorMut {
3085 inner: CursorMutKey {
3086 current: Some(edge),
3087 root: dormant_root,
3088 length: &mut self.length,
3089 alloc: &mut *self.alloc,
3090 },
3091 }
3092 }
3093}
3094
3095/// A cursor over a `BTreeMap`.
3096///
3097/// A `Cursor` is like an iterator, except that it can freely seek back-and-forth.
3098///
3099/// Cursors always point to a gap between two elements in the map, and can
3100/// operate on the two immediately adjacent elements.
3101///
3102/// A `Cursor` is created with the [`BTreeMap::lower_bound`] and [`BTreeMap::upper_bound`] methods.
3103#[unstable(feature = "btree_cursors", issue = "107540")]
3104pub struct Cursor<'a, K: 'a, V: 'a> {
3105 // If current is None then it means the tree has not been allocated yet.
3106 current: Option<Handle<NodeRef<marker::Immut<'a>, K, V, marker::Leaf>, marker::Edge>>,
3107 root: Option<&'a node::Root<K, V>>,
3108}
3109
3110#[unstable(feature = "btree_cursors", issue = "107540")]
3111impl<K, V> Clone for Cursor<'_, K, V> {
3112 fn clone(&self) -> Self {
3113 let Cursor { current, root } = *self;
3114 Cursor { current, root }
3115 }
3116}
3117
3118#[unstable(feature = "btree_cursors", issue = "107540")]
3119impl<K: Debug, V: Debug> Debug for Cursor<'_, K, V> {
3120 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3121 f.write_str("Cursor")
3122 }
3123}
3124
3125/// A cursor over a `BTreeMap` with editing operations.
3126///
3127/// A `Cursor` is like an iterator, except that it can freely seek back-and-forth, and can
3128/// safely mutate the map during iteration. This is because the lifetime of its yielded
3129/// references is tied to its own lifetime, instead of just the underlying map. This means
3130/// cursors cannot yield multiple elements at once.
3131///
3132/// Cursors always point to a gap between two elements in the map, and can
3133/// operate on the two immediately adjacent elements.
3134///
3135/// A `CursorMut` is created with the [`BTreeMap::lower_bound_mut`] and [`BTreeMap::upper_bound_mut`]
3136/// methods.
3137#[unstable(feature = "btree_cursors", issue = "107540")]
3138pub struct CursorMut<
3139 'a,
3140 K: 'a,
3141 V: 'a,
3142 #[unstable(feature = "allocator_api", issue = "32838")] A = Global,
3143> {
3144 inner: CursorMutKey<'a, K, V, A>,
3145}
3146
3147#[unstable(feature = "btree_cursors", issue = "107540")]
3148impl<K: Debug, V: Debug, A> Debug for CursorMut<'_, K, V, A> {
3149 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3150 f.write_str("CursorMut")
3151 }
3152}
3153
3154/// A cursor over a `BTreeMap` with editing operations, and which allows
3155/// mutating the key of elements.
3156///
3157/// A `Cursor` is like an iterator, except that it can freely seek back-and-forth, and can
3158/// safely mutate the map during iteration. This is because the lifetime of its yielded
3159/// references is tied to its own lifetime, instead of just the underlying map. This means
3160/// cursors cannot yield multiple elements at once.
3161///
3162/// Cursors always point to a gap between two elements in the map, and can
3163/// operate on the two immediately adjacent elements.
3164///
3165/// A `CursorMutKey` is created from a [`CursorMut`] with the
3166/// [`CursorMut::with_mutable_key`] method.
3167///
3168/// # Safety
3169///
3170/// Since this cursor allows mutating keys, you must ensure that the `BTreeMap`
3171/// invariants are maintained. Specifically:
3172///
3173/// * The key of the newly inserted element must be unique in the tree.
3174/// * All keys in the tree must remain in sorted order.
3175#[unstable(feature = "btree_cursors", issue = "107540")]
3176pub struct CursorMutKey<
3177 'a,
3178 K: 'a,
3179 V: 'a,
3180 #[unstable(feature = "allocator_api", issue = "32838")] A = Global,
3181> {
3182 // If current is None then it means the tree has not been allocated yet.
3183 current: Option<Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge>>,
3184 root: DormantMutRef<'a, Option<node::Root<K, V>>>,
3185 length: &'a mut usize,
3186 alloc: &'a mut A,
3187}
3188
3189#[unstable(feature = "btree_cursors", issue = "107540")]
3190impl<K: Debug, V: Debug, A> Debug for CursorMutKey<'_, K, V, A> {
3191 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3192 f.write_str("CursorMutKey")
3193 }
3194}
3195
3196impl<'a, K, V> Cursor<'a, K, V> {
3197 /// Advances the cursor to the next gap, returning the key and value of the
3198 /// element that it moved over.
3199 ///
3200 /// If the cursor is already at the end of the map then `None` is returned
3201 /// and the cursor is not moved.
3202 #[unstable(feature = "btree_cursors", issue = "107540")]
3203 pub fn next(&mut self) -> Option<(&'a K, &'a V)> {
3204 let current = self.current.take()?;
3205 match current.next_kv() {
3206 Ok(kv) => {
3207 let result = kv.into_kv();
3208 self.current = Some(kv.next_leaf_edge());
3209 Some(result)
3210 }
3211 Err(root) => {
3212 self.current = Some(root.last_leaf_edge());
3213 None
3214 }
3215 }
3216 }
3217
3218 /// Advances the cursor to the previous gap, returning the key and value of
3219 /// the element that it moved over.
3220 ///
3221 /// If the cursor is already at the start of the map then `None` is returned
3222 /// and the cursor is not moved.
3223 #[unstable(feature = "btree_cursors", issue = "107540")]
3224 pub fn prev(&mut self) -> Option<(&'a K, &'a V)> {
3225 let current = self.current.take()?;
3226 match current.next_back_kv() {
3227 Ok(kv) => {
3228 let result = kv.into_kv();
3229 self.current = Some(kv.next_back_leaf_edge());
3230 Some(result)
3231 }
3232 Err(root) => {
3233 self.current = Some(root.first_leaf_edge());
3234 None
3235 }
3236 }
3237 }
3238
3239 /// Returns a reference to the key and value of the next element without
3240 /// moving the cursor.
3241 ///
3242 /// If the cursor is at the end of the map then `None` is returned.
3243 #[unstable(feature = "btree_cursors", issue = "107540")]
3244 pub fn peek_next(&self) -> Option<(&'a K, &'a V)> {
3245 self.clone().next()
3246 }
3247
3248 /// Returns a reference to the key and value of the previous element
3249 /// without moving the cursor.
3250 ///
3251 /// If the cursor is at the start of the map then `None` is returned.
3252 #[unstable(feature = "btree_cursors", issue = "107540")]
3253 pub fn peek_prev(&self) -> Option<(&'a K, &'a V)> {
3254 self.clone().prev()
3255 }
3256}
3257
3258impl<'a, K, V, A> CursorMut<'a, K, V, A> {
3259 /// Advances the cursor to the next gap, returning the key and value of the
3260 /// element that it moved over.
3261 ///
3262 /// If the cursor is already at the end of the map then `None` is returned
3263 /// and the cursor is not moved.
3264 #[unstable(feature = "btree_cursors", issue = "107540")]
3265 pub fn next(&mut self) -> Option<(&K, &mut V)> {
3266 let (k, v) = self.inner.next()?;
3267 Some((&*k, v))
3268 }
3269
3270 /// Advances the cursor to the previous gap, returning the key and value of
3271 /// the element that it moved over.
3272 ///
3273 /// If the cursor is already at the start of the map then `None` is returned
3274 /// and the cursor is not moved.
3275 #[unstable(feature = "btree_cursors", issue = "107540")]
3276 pub fn prev(&mut self) -> Option<(&K, &mut V)> {
3277 let (k, v) = self.inner.prev()?;
3278 Some((&*k, v))
3279 }
3280
3281 /// Returns a reference to the key and value of the next element without
3282 /// moving the cursor.
3283 ///
3284 /// If the cursor is at the end of the map then `None` is returned.
3285 #[unstable(feature = "btree_cursors", issue = "107540")]
3286 pub fn peek_next(&mut self) -> Option<(&K, &mut V)> {
3287 let (k, v) = self.inner.peek_next()?;
3288 Some((&*k, v))
3289 }
3290
3291 /// Returns a reference to the key and value of the previous element
3292 /// without moving the cursor.
3293 ///
3294 /// If the cursor is at the start of the map then `None` is returned.
3295 #[unstable(feature = "btree_cursors", issue = "107540")]
3296 pub fn peek_prev(&mut self) -> Option<(&K, &mut V)> {
3297 let (k, v) = self.inner.peek_prev()?;
3298 Some((&*k, v))
3299 }
3300
3301 /// Returns a read-only cursor pointing to the same location as the
3302 /// `CursorMut`.
3303 ///
3304 /// The lifetime of the returned `Cursor` is bound to that of the
3305 /// `CursorMut`, which means it cannot outlive the `CursorMut` and that the
3306 /// `CursorMut` is frozen for the lifetime of the `Cursor`.
3307 #[unstable(feature = "btree_cursors", issue = "107540")]
3308 pub fn as_cursor(&self) -> Cursor<'_, K, V> {
3309 self.inner.as_cursor()
3310 }
3311
3312 /// Converts the cursor into a [`CursorMutKey`], which allows mutating
3313 /// the key of elements in the tree.
3314 ///
3315 /// # Safety
3316 ///
3317 /// Since this cursor allows mutating keys, you must ensure that the `BTreeMap`
3318 /// invariants are maintained. Specifically:
3319 ///
3320 /// * The key of the newly inserted element must be unique in the tree.
3321 /// * All keys in the tree must remain in sorted order.
3322 #[unstable(feature = "btree_cursors", issue = "107540")]
3323 pub unsafe fn with_mutable_key(self) -> CursorMutKey<'a, K, V, A> {
3324 self.inner
3325 }
3326}
3327
3328impl<'a, K, V, A> CursorMutKey<'a, K, V, A> {
3329 /// Advances the cursor to the next gap, returning the key and value of the
3330 /// element that it moved over.
3331 ///
3332 /// If the cursor is already at the end of the map then `None` is returned
3333 /// and the cursor is not moved.
3334 #[unstable(feature = "btree_cursors", issue = "107540")]
3335 pub fn next(&mut self) -> Option<(&mut K, &mut V)> {
3336 let current = self.current.take()?;
3337 match current.next_kv() {
3338 Ok(mut kv) => {
3339 // SAFETY: The key/value pointers remain valid even after the
3340 // cursor is moved forward. The lifetimes then prevent any
3341 // further access to the cursor.
3342 let (k, v) = unsafe { kv.reborrow_mut().into_kv_mut() };
3343 let (k, v) = (k as *mut _, v as *mut _);
3344 self.current = Some(kv.next_leaf_edge());
3345 Some(unsafe { (&mut *k, &mut *v) })
3346 }
3347 Err(root) => {
3348 self.current = Some(root.last_leaf_edge());
3349 None
3350 }
3351 }
3352 }
3353
3354 /// Advances the cursor to the previous gap, returning the key and value of
3355 /// the element that it moved over.
3356 ///
3357 /// If the cursor is already at the start of the map then `None` is returned
3358 /// and the cursor is not moved.
3359 #[unstable(feature = "btree_cursors", issue = "107540")]
3360 pub fn prev(&mut self) -> Option<(&mut K, &mut V)> {
3361 let current = self.current.take()?;
3362 match current.next_back_kv() {
3363 Ok(mut kv) => {
3364 // SAFETY: The key/value pointers remain valid even after the
3365 // cursor is moved forward. The lifetimes then prevent any
3366 // further access to the cursor.
3367 let (k, v) = unsafe { kv.reborrow_mut().into_kv_mut() };
3368 let (k, v) = (k as *mut _, v as *mut _);
3369 self.current = Some(kv.next_back_leaf_edge());
3370 Some(unsafe { (&mut *k, &mut *v) })
3371 }
3372 Err(root) => {
3373 self.current = Some(root.first_leaf_edge());
3374 None
3375 }
3376 }
3377 }
3378
3379 /// Returns a reference to the key and value of the next element without
3380 /// moving the cursor.
3381 ///
3382 /// If the cursor is at the end of the map then `None` is returned.
3383 #[unstable(feature = "btree_cursors", issue = "107540")]
3384 pub fn peek_next(&mut self) -> Option<(&mut K, &mut V)> {
3385 let current = self.current.as_mut()?;
3386 // SAFETY: We're not using this to mutate the tree.
3387 let kv = unsafe { current.reborrow_mut() }.next_kv().ok()?.into_kv_mut();
3388 Some(kv)
3389 }
3390
3391 /// Returns a reference to the key and value of the previous element
3392 /// without moving the cursor.
3393 ///
3394 /// If the cursor is at the start of the map then `None` is returned.
3395 #[unstable(feature = "btree_cursors", issue = "107540")]
3396 pub fn peek_prev(&mut self) -> Option<(&mut K, &mut V)> {
3397 let current = self.current.as_mut()?;
3398 // SAFETY: We're not using this to mutate the tree.
3399 let kv = unsafe { current.reborrow_mut() }.next_back_kv().ok()?.into_kv_mut();
3400 Some(kv)
3401 }
3402
3403 /// Returns a read-only cursor pointing to the same location as the
3404 /// `CursorMutKey`.
3405 ///
3406 /// The lifetime of the returned `Cursor` is bound to that of the
3407 /// `CursorMutKey`, which means it cannot outlive the `CursorMutKey` and that the
3408 /// `CursorMutKey` is frozen for the lifetime of the `Cursor`.
3409 #[unstable(feature = "btree_cursors", issue = "107540")]
3410 pub fn as_cursor(&self) -> Cursor<'_, K, V> {
3411 Cursor {
3412 // SAFETY: The tree is immutable while the cursor exists.
3413 root: unsafe { self.root.reborrow_shared().as_ref() },
3414 current: self.current.as_ref().map(|current| current.reborrow()),
3415 }
3416 }
3417}
3418
3419// Now the tree editing operations
3420impl<'a, K: Ord, V, A: Allocator + Clone> CursorMutKey<'a, K, V, A> {
3421 /// Inserts a new key-value pair into the map in the gap that the
3422 /// cursor is currently pointing to.
3423 ///
3424 /// After the insertion the cursor will be pointing at the gap before the
3425 /// newly inserted element.
3426 ///
3427 /// # Safety
3428 ///
3429 /// You must ensure that the `BTreeMap` invariants are maintained.
3430 /// Specifically:
3431 ///
3432 /// * The key of the newly inserted element must be unique in the tree.
3433 /// * All keys in the tree must remain in sorted order.
3434 #[unstable(feature = "btree_cursors", issue = "107540")]
3435 pub unsafe fn insert_after_unchecked(&mut self, key: K, value: V) {
3436 let edge = match self.current.take() {
3437 None => {
3438 // Tree is empty, allocate a new root.
3439 // SAFETY: We have no other reference to the tree.
3440 let root = unsafe { self.root.reborrow() };
3441 debug_assert!(root.is_none());
3442 let mut node = NodeRef::new_leaf(self.alloc.clone());
3443 // SAFETY: We don't touch the root while the handle is alive.
3444 let handle = unsafe { node.borrow_mut().push_with_handle(key, value) };
3445 *root = Some(node.forget_type());
3446 *self.length += 1;
3447 self.current = Some(handle.left_edge());
3448 return;
3449 }
3450 Some(current) => current,
3451 };
3452
3453 let handle = edge.insert_recursing(key, value, self.alloc.clone(), |ins| {
3454 drop(ins.left);
3455 // SAFETY: The handle to the newly inserted value is always on a
3456 // leaf node, so adding a new root node doesn't invalidate it.
3457 let root = unsafe { self.root.reborrow().as_mut().unwrap() };
3458 root.push_internal_level(self.alloc.clone()).push(ins.kv.0, ins.kv.1, ins.right)
3459 });
3460 self.current = Some(handle.left_edge());
3461 *self.length += 1;
3462 }
3463
3464 /// Inserts a new key-value pair into the map in the gap that the
3465 /// cursor is currently pointing to.
3466 ///
3467 /// After the insertion the cursor will be pointing at the gap after the
3468 /// newly inserted element.
3469 ///
3470 /// # Safety
3471 ///
3472 /// You must ensure that the `BTreeMap` invariants are maintained.
3473 /// Specifically:
3474 ///
3475 /// * The key of the newly inserted element must be unique in the tree.
3476 /// * All keys in the tree must remain in sorted order.
3477 #[unstable(feature = "btree_cursors", issue = "107540")]
3478 pub unsafe fn insert_before_unchecked(&mut self, key: K, value: V) {
3479 let edge = match self.current.take() {
3480 None => {
3481 // SAFETY: We have no other reference to the tree.
3482 match unsafe { self.root.reborrow() } {
3483 root @ None => {
3484 // Tree is empty, allocate a new root.
3485 let mut node = NodeRef::new_leaf(self.alloc.clone());
3486 // SAFETY: We don't touch the root while the handle is alive.
3487 let handle = unsafe { node.borrow_mut().push_with_handle(key, value) };
3488 *root = Some(node.forget_type());
3489 *self.length += 1;
3490 self.current = Some(handle.right_edge());
3491 return;
3492 }
3493 Some(root) => root.borrow_mut().last_leaf_edge(),
3494 }
3495 }
3496 Some(current) => current,
3497 };
3498
3499 let handle = edge.insert_recursing(key, value, self.alloc.clone(), |ins| {
3500 drop(ins.left);
3501 // SAFETY: The handle to the newly inserted value is always on a
3502 // leaf node, so adding a new root node doesn't invalidate it.
3503 let root = unsafe { self.root.reborrow().as_mut().unwrap() };
3504 root.push_internal_level(self.alloc.clone()).push(ins.kv.0, ins.kv.1, ins.right)
3505 });
3506 self.current = Some(handle.right_edge());
3507 *self.length += 1;
3508 }
3509
3510 /// Inserts a new key-value pair into the map in the gap that the
3511 /// cursor is currently pointing to.
3512 ///
3513 /// After the insertion the cursor will be pointing at the gap before the
3514 /// newly inserted element.
3515 ///
3516 /// If the inserted key is not greater than the key before the cursor
3517 /// (if any), or if it not less than the key after the cursor (if any),
3518 /// then an [`UnorderedKeyError`] is returned since this would
3519 /// invalidate the [`Ord`] invariant between the keys of the map.
3520 #[unstable(feature = "btree_cursors", issue = "107540")]
3521 pub fn insert_after(&mut self, key: K, value: V) -> Result<(), UnorderedKeyError> {
3522 if let Some((prev, _)) = self.peek_prev() {
3523 if &key <= prev {
3524 return Err(UnorderedKeyError {});
3525 }
3526 }
3527 if let Some((next, _)) = self.peek_next() {
3528 if &key >= next {
3529 return Err(UnorderedKeyError {});
3530 }
3531 }
3532 unsafe {
3533 self.insert_after_unchecked(key, value);
3534 }
3535 Ok(())
3536 }
3537
3538 /// Inserts a new key-value pair into the map in the gap that the
3539 /// cursor is currently pointing to.
3540 ///
3541 /// After the insertion the cursor will be pointing at the gap after the
3542 /// newly inserted element.
3543 ///
3544 /// If the inserted key is not greater than the key before the cursor
3545 /// (if any), or if it not less than the key after the cursor (if any),
3546 /// then an [`UnorderedKeyError`] is returned since this would
3547 /// invalidate the [`Ord`] invariant between the keys of the map.
3548 #[unstable(feature = "btree_cursors", issue = "107540")]
3549 pub fn insert_before(&mut self, key: K, value: V) -> Result<(), UnorderedKeyError> {
3550 if let Some((prev, _)) = self.peek_prev() {
3551 if &key <= prev {
3552 return Err(UnorderedKeyError {});
3553 }
3554 }
3555 if let Some((next, _)) = self.peek_next() {
3556 if &key >= next {
3557 return Err(UnorderedKeyError {});
3558 }
3559 }
3560 unsafe {
3561 self.insert_before_unchecked(key, value);
3562 }
3563 Ok(())
3564 }
3565
3566 /// Removes the next element from the `BTreeMap`.
3567 ///
3568 /// The element that was removed is returned. The cursor position is
3569 /// unchanged (before the removed element).
3570 #[unstable(feature = "btree_cursors", issue = "107540")]
3571 pub fn remove_next(&mut self) -> Option<(K, V)> {
3572 let current = self.current.take()?;
3573 if current.reborrow().next_kv().is_err() {
3574 self.current = Some(current);
3575 return None;
3576 }
3577 let mut emptied_internal_root = false;
3578 let (kv, pos) = current
3579 .next_kv()
3580 // This should be unwrap(), but that doesn't work because NodeRef
3581 // doesn't implement Debug. The condition is checked above.
3582 .ok()?
3583 .remove_kv_tracking(|| emptied_internal_root = true, self.alloc.clone());
3584 self.current = Some(pos);
3585 *self.length -= 1;
3586 if emptied_internal_root {
3587 // SAFETY: This is safe since current does not point within the now
3588 // empty root node.
3589 let root = unsafe { self.root.reborrow().as_mut().unwrap() };
3590 root.pop_internal_level(self.alloc.clone());
3591 }
3592 Some(kv)
3593 }
3594
3595 /// Removes the preceding element from the `BTreeMap`.
3596 ///
3597 /// The element that was removed is returned. The cursor position is
3598 /// unchanged (after the removed element).
3599 #[unstable(feature = "btree_cursors", issue = "107540")]
3600 pub fn remove_prev(&mut self) -> Option<(K, V)> {
3601 let current = self.current.take()?;
3602 if current.reborrow().next_back_kv().is_err() {
3603 self.current = Some(current);
3604 return None;
3605 }
3606 let mut emptied_internal_root = false;
3607 let (kv, pos) = current
3608 .next_back_kv()
3609 // This should be unwrap(), but that doesn't work because NodeRef
3610 // doesn't implement Debug. The condition is checked above.
3611 .ok()?
3612 .remove_kv_tracking(|| emptied_internal_root = true, self.alloc.clone());
3613 self.current = Some(pos);
3614 *self.length -= 1;
3615 if emptied_internal_root {
3616 // SAFETY: This is safe since current does not point within the now
3617 // empty root node.
3618 let root = unsafe { self.root.reborrow().as_mut().unwrap() };
3619 root.pop_internal_level(self.alloc.clone());
3620 }
3621 Some(kv)
3622 }
3623}
3624
3625impl<'a, K: Ord, V, A: Allocator + Clone> CursorMut<'a, K, V, A> {
3626 /// Inserts a new key-value pair into the map in the gap that the
3627 /// cursor is currently pointing to.
3628 ///
3629 /// After the insertion the cursor will be pointing at the gap after the
3630 /// newly inserted element.
3631 ///
3632 /// # Safety
3633 ///
3634 /// You must ensure that the `BTreeMap` invariants are maintained.
3635 /// Specifically:
3636 ///
3637 /// * The key of the newly inserted element must be unique in the tree.
3638 /// * All keys in the tree must remain in sorted order.
3639 #[unstable(feature = "btree_cursors", issue = "107540")]
3640 pub unsafe fn insert_after_unchecked(&mut self, key: K, value: V) {
3641 unsafe { self.inner.insert_after_unchecked(key, value) }
3642 }
3643
3644 /// Inserts a new key-value pair into the map in the gap that the
3645 /// cursor is currently pointing to.
3646 ///
3647 /// After the insertion the cursor will be pointing at the gap after the
3648 /// newly inserted element.
3649 ///
3650 /// # Safety
3651 ///
3652 /// You must ensure that the `BTreeMap` invariants are maintained.
3653 /// Specifically:
3654 ///
3655 /// * The key of the newly inserted element must be unique in the tree.
3656 /// * All keys in the tree must remain in sorted order.
3657 #[unstable(feature = "btree_cursors", issue = "107540")]
3658 pub unsafe fn insert_before_unchecked(&mut self, key: K, value: V) {
3659 unsafe { self.inner.insert_before_unchecked(key, value) }
3660 }
3661
3662 /// Inserts a new key-value pair into the map in the gap that the
3663 /// cursor is currently pointing to.
3664 ///
3665 /// After the insertion the cursor will be pointing at the gap before the
3666 /// newly inserted element.
3667 ///
3668 /// If the inserted key is not greater than the key before the cursor
3669 /// (if any), or if it not less than the key after the cursor (if any),
3670 /// then an [`UnorderedKeyError`] is returned since this would
3671 /// invalidate the [`Ord`] invariant between the keys of the map.
3672 #[unstable(feature = "btree_cursors", issue = "107540")]
3673 pub fn insert_after(&mut self, key: K, value: V) -> Result<(), UnorderedKeyError> {
3674 self.inner.insert_after(key, value)
3675 }
3676
3677 /// Inserts a new key-value pair into the map in the gap that the
3678 /// cursor is currently pointing to.
3679 ///
3680 /// After the insertion the cursor will be pointing at the gap after the
3681 /// newly inserted element.
3682 ///
3683 /// If the inserted key is not greater than the key before the cursor
3684 /// (if any), or if it not less than the key after the cursor (if any),
3685 /// then an [`UnorderedKeyError`] is returned since this would
3686 /// invalidate the [`Ord`] invariant between the keys of the map.
3687 #[unstable(feature = "btree_cursors", issue = "107540")]
3688 pub fn insert_before(&mut self, key: K, value: V) -> Result<(), UnorderedKeyError> {
3689 self.inner.insert_before(key, value)
3690 }
3691
3692 /// Removes the next element from the `BTreeMap`.
3693 ///
3694 /// The element that was removed is returned. The cursor position is
3695 /// unchanged (before the removed element).
3696 #[unstable(feature = "btree_cursors", issue = "107540")]
3697 pub fn remove_next(&mut self) -> Option<(K, V)> {
3698 self.inner.remove_next()
3699 }
3700
3701 /// Removes the preceding element from the `BTreeMap`.
3702 ///
3703 /// The element that was removed is returned. The cursor position is
3704 /// unchanged (after the removed element).
3705 #[unstable(feature = "btree_cursors", issue = "107540")]
3706 pub fn remove_prev(&mut self) -> Option<(K, V)> {
3707 self.inner.remove_prev()
3708 }
3709}
3710
3711/// Error type returned by [`CursorMut::insert_before`] and
3712/// [`CursorMut::insert_after`] if the key being inserted is not properly
3713/// ordered with regards to adjacent keys.
3714#[derive(Clone, PartialEq, Eq, Debug)]
3715#[unstable(feature = "btree_cursors", issue = "107540")]
3716pub struct UnorderedKeyError {}
3717
3718#[unstable(feature = "btree_cursors", issue = "107540")]
3719impl fmt::Display for UnorderedKeyError {
3720 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3721 write!(f, "key is not properly ordered relative to neighbors")
3722 }
3723}
3724
3725#[unstable(feature = "btree_cursors", issue = "107540")]
3726impl Error for UnorderedKeyError {}
3727
3728#[cfg(test)]
3729mod tests;