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::{AllocatorClone, 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: AllocatorClone = 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: AllocatorClone> 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: AllocatorClone> 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: AllocatorClone> Clone for BTreeMap<K, V, A> {
227 fn clone(&self) -> BTreeMap<K, V, A> {
228 fn clone_subtree<'a, K: Clone, V: Clone, A: AllocatorClone>(
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: AllocatorClone> 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: AllocatorClone = 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: AllocatorClone> 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: AllocatorClone> 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: AllocatorClone + Default,
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: AllocatorClone = 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: AllocatorClone> 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: AllocatorClone = 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: AllocatorClone> 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: AllocatorClone> 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: self.root.take(),
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 ///
688 /// use std::collections::BTreeMap;
689 /// use std::alloc::Global;
690 ///
691 /// let map: BTreeMap<i32, i32> = BTreeMap::new_in(Global);
692 /// ```
693 #[unstable(feature = "btreemap_alloc", issue = "32838")]
694 #[must_use]
695 pub const fn new_in(alloc: A) -> BTreeMap<K, V, A> {
696 BTreeMap { root: None, length: 0, alloc: ManuallyDrop::new(alloc), _marker: PhantomData }
697 }
698}
699
700impl<K, V, A: AllocatorClone> BTreeMap<K, V, A> {
701 /// Returns a reference to the value corresponding to the key.
702 ///
703 /// The key may be any borrowed form of the map's key type, but the ordering
704 /// on the borrowed form *must* match the ordering on the key type.
705 ///
706 /// # Examples
707 ///
708 /// ```
709 /// use std::collections::BTreeMap;
710 ///
711 /// let mut map = BTreeMap::new();
712 /// map.insert(1, "a");
713 /// assert_eq!(map.get(&1), Some(&"a"));
714 /// assert_eq!(map.get(&2), None);
715 /// ```
716 #[stable(feature = "rust1", since = "1.0.0")]
717 pub fn get<Q: ?Sized>(&self, key: &Q) -> Option<&V>
718 where
719 K: Borrow<Q> + Ord,
720 Q: Ord,
721 {
722 let root_node = self.root.as_ref()?.reborrow();
723 match root_node.search_tree(key) {
724 Found(handle) => Some(handle.into_kv().1),
725 GoDown(_) => None,
726 }
727 }
728
729 /// Returns the key-value pair corresponding to the supplied key. This is
730 /// potentially useful:
731 /// - for key types where non-identical keys can be considered equal;
732 /// - for getting the `&K` stored key value from a borrowed `&Q` lookup key; or
733 /// - for getting a reference to a key with the same lifetime as the collection.
734 ///
735 /// The supplied key may be any borrowed form of the map's key type, but the ordering
736 /// on the borrowed form *must* match the ordering on the key type.
737 ///
738 /// # Examples
739 ///
740 /// ```
741 /// use std::cmp::Ordering;
742 /// use std::collections::BTreeMap;
743 ///
744 /// #[derive(Clone, Copy, Debug)]
745 /// struct S {
746 /// id: u32,
747 /// # #[allow(unused)] // prevents a "field `name` is never read" error
748 /// name: &'static str, // ignored by equality and ordering operations
749 /// }
750 ///
751 /// impl PartialEq for S {
752 /// fn eq(&self, other: &S) -> bool {
753 /// self.id == other.id
754 /// }
755 /// }
756 ///
757 /// impl Eq for S {}
758 ///
759 /// impl PartialOrd for S {
760 /// fn partial_cmp(&self, other: &S) -> Option<Ordering> {
761 /// self.id.partial_cmp(&other.id)
762 /// }
763 /// }
764 ///
765 /// impl Ord for S {
766 /// fn cmp(&self, other: &S) -> Ordering {
767 /// self.id.cmp(&other.id)
768 /// }
769 /// }
770 ///
771 /// let j_a = S { id: 1, name: "Jessica" };
772 /// let j_b = S { id: 1, name: "Jess" };
773 /// let p = S { id: 2, name: "Paul" };
774 /// assert_eq!(j_a, j_b);
775 ///
776 /// let mut map = BTreeMap::new();
777 /// map.insert(j_a, "Paris");
778 /// assert_eq!(map.get_key_value(&j_a), Some((&j_a, &"Paris")));
779 /// assert_eq!(map.get_key_value(&j_b), Some((&j_a, &"Paris"))); // the notable case
780 /// assert_eq!(map.get_key_value(&p), None);
781 /// ```
782 #[stable(feature = "map_get_key_value", since = "1.40.0")]
783 pub fn get_key_value<Q: ?Sized>(&self, k: &Q) -> Option<(&K, &V)>
784 where
785 K: Borrow<Q> + Ord,
786 Q: Ord,
787 {
788 let root_node = self.root.as_ref()?.reborrow();
789 match root_node.search_tree(k) {
790 Found(handle) => Some(handle.into_kv()),
791 GoDown(_) => None,
792 }
793 }
794
795 /// Returns the first key-value pair in the map.
796 /// The key in this pair is the minimum key in the map.
797 ///
798 /// # Examples
799 ///
800 /// ```
801 /// use std::collections::BTreeMap;
802 ///
803 /// let mut map = BTreeMap::new();
804 /// assert_eq!(map.first_key_value(), None);
805 /// map.insert(1, "b");
806 /// map.insert(2, "a");
807 /// assert_eq!(map.first_key_value(), Some((&1, &"b")));
808 /// ```
809 #[stable(feature = "map_first_last", since = "1.66.0")]
810 pub fn first_key_value(&self) -> Option<(&K, &V)>
811 where
812 K: Ord,
813 {
814 let root_node = self.root.as_ref()?.reborrow();
815 root_node.first_leaf_edge().right_kv().ok().map(Handle::into_kv)
816 }
817
818 /// Returns the first entry in the map for in-place manipulation.
819 /// The key of this entry is the minimum key in the map.
820 ///
821 /// # Examples
822 ///
823 /// ```
824 /// use std::collections::BTreeMap;
825 ///
826 /// let mut map = BTreeMap::new();
827 /// map.insert(1, "a");
828 /// map.insert(2, "b");
829 /// if let Some(mut entry) = map.first_entry() {
830 /// if *entry.key() > 0 {
831 /// entry.insert("first");
832 /// }
833 /// }
834 /// assert_eq!(*map.get(&1).unwrap(), "first");
835 /// assert_eq!(*map.get(&2).unwrap(), "b");
836 /// ```
837 #[stable(feature = "map_first_last", since = "1.66.0")]
838 pub fn first_entry(&mut self) -> Option<OccupiedEntry<'_, K, V, A>>
839 where
840 K: Ord,
841 {
842 let (map, dormant_map) = DormantMutRef::new(self);
843 let root_node = map.root.as_mut()?.borrow_mut();
844 let kv = root_node.first_leaf_edge().right_kv().ok()?;
845 Some(OccupiedEntry {
846 handle: kv.forget_node_type(),
847 dormant_map,
848 alloc: (*map.alloc).clone(),
849 _marker: PhantomData,
850 })
851 }
852
853 /// Removes and returns the first element in the map.
854 /// The key of this element is the minimum key that was in the map.
855 ///
856 /// # Examples
857 ///
858 /// Draining elements in ascending order, while keeping a usable map each iteration.
859 ///
860 /// ```
861 /// use std::collections::BTreeMap;
862 ///
863 /// let mut map = BTreeMap::new();
864 /// map.insert(1, "a");
865 /// map.insert(2, "b");
866 /// while let Some((key, _val)) = map.pop_first() {
867 /// assert!(map.iter().all(|(k, _v)| *k > key));
868 /// }
869 /// assert!(map.is_empty());
870 /// ```
871 #[stable(feature = "map_first_last", since = "1.66.0")]
872 pub fn pop_first(&mut self) -> Option<(K, V)>
873 where
874 K: Ord,
875 {
876 self.first_entry().map(|entry| entry.remove_entry())
877 }
878
879 /// Returns the last key-value pair in the map.
880 /// The key in this pair is the maximum key in the map.
881 ///
882 /// # Examples
883 ///
884 /// ```
885 /// use std::collections::BTreeMap;
886 ///
887 /// let mut map = BTreeMap::new();
888 /// map.insert(1, "b");
889 /// map.insert(2, "a");
890 /// assert_eq!(map.last_key_value(), Some((&2, &"a")));
891 /// ```
892 #[stable(feature = "map_first_last", since = "1.66.0")]
893 pub fn last_key_value(&self) -> Option<(&K, &V)>
894 where
895 K: Ord,
896 {
897 let root_node = self.root.as_ref()?.reborrow();
898 root_node.last_leaf_edge().left_kv().ok().map(Handle::into_kv)
899 }
900
901 /// Returns the last entry in the map for in-place manipulation.
902 /// The key of this entry is the maximum key in the map.
903 ///
904 /// # Examples
905 ///
906 /// ```
907 /// use std::collections::BTreeMap;
908 ///
909 /// let mut map = BTreeMap::new();
910 /// map.insert(1, "a");
911 /// map.insert(2, "b");
912 /// if let Some(mut entry) = map.last_entry() {
913 /// if *entry.key() > 0 {
914 /// entry.insert("last");
915 /// }
916 /// }
917 /// assert_eq!(*map.get(&1).unwrap(), "a");
918 /// assert_eq!(*map.get(&2).unwrap(), "last");
919 /// ```
920 #[stable(feature = "map_first_last", since = "1.66.0")]
921 pub fn last_entry(&mut self) -> Option<OccupiedEntry<'_, K, V, A>>
922 where
923 K: Ord,
924 {
925 let (map, dormant_map) = DormantMutRef::new(self);
926 let root_node = map.root.as_mut()?.borrow_mut();
927 let kv = root_node.last_leaf_edge().left_kv().ok()?;
928 Some(OccupiedEntry {
929 handle: kv.forget_node_type(),
930 dormant_map,
931 alloc: (*map.alloc).clone(),
932 _marker: PhantomData,
933 })
934 }
935
936 /// Removes and returns the last element in the map.
937 /// The key of this element is the maximum key that was in the map.
938 ///
939 /// # Examples
940 ///
941 /// Draining elements in descending order, while keeping a usable map each iteration.
942 ///
943 /// ```
944 /// use std::collections::BTreeMap;
945 ///
946 /// let mut map = BTreeMap::new();
947 /// map.insert(1, "a");
948 /// map.insert(2, "b");
949 /// while let Some((key, _val)) = map.pop_last() {
950 /// assert!(map.iter().all(|(k, _v)| *k < key));
951 /// }
952 /// assert!(map.is_empty());
953 /// ```
954 #[stable(feature = "map_first_last", since = "1.66.0")]
955 pub fn pop_last(&mut self) -> Option<(K, V)>
956 where
957 K: Ord,
958 {
959 self.last_entry().map(|entry| entry.remove_entry())
960 }
961
962 /// Returns `true` if the map contains a value for the specified key.
963 ///
964 /// The key may be any borrowed form of the map's key type, but the ordering
965 /// on the borrowed form *must* match the ordering on the key type.
966 ///
967 /// # Examples
968 ///
969 /// ```
970 /// use std::collections::BTreeMap;
971 ///
972 /// let mut map = BTreeMap::new();
973 /// map.insert(1, "a");
974 /// assert_eq!(map.contains_key(&1), true);
975 /// assert_eq!(map.contains_key(&2), false);
976 /// ```
977 #[stable(feature = "rust1", since = "1.0.0")]
978 #[cfg_attr(not(test), rustc_diagnostic_item = "btreemap_contains_key")]
979 pub fn contains_key<Q: ?Sized>(&self, key: &Q) -> bool
980 where
981 K: Borrow<Q> + Ord,
982 Q: Ord,
983 {
984 self.get(key).is_some()
985 }
986
987 /// Returns a mutable reference to the value corresponding to the key.
988 ///
989 /// The key may be any borrowed form of the map's key type, but the ordering
990 /// on the borrowed form *must* match the ordering on the key type.
991 ///
992 /// # Examples
993 ///
994 /// ```
995 /// use std::collections::BTreeMap;
996 ///
997 /// let mut map = BTreeMap::new();
998 /// map.insert(1, "a");
999 /// if let Some(x) = map.get_mut(&1) {
1000 /// *x = "b";
1001 /// }
1002 /// assert_eq!(map[&1], "b");
1003 /// ```
1004 // See `get` for implementation notes, this is basically a copy-paste with mut's added
1005 #[stable(feature = "rust1", since = "1.0.0")]
1006 pub fn get_mut<Q: ?Sized>(&mut self, key: &Q) -> Option<&mut V>
1007 where
1008 K: Borrow<Q> + Ord,
1009 Q: Ord,
1010 {
1011 let root_node = self.root.as_mut()?.borrow_mut();
1012 match root_node.search_tree(key) {
1013 Found(handle) => Some(handle.into_val_mut()),
1014 GoDown(_) => None,
1015 }
1016 }
1017
1018 /// Inserts a key-value pair into the map.
1019 ///
1020 /// If the map did not have this key present, `None` is returned.
1021 ///
1022 /// If the map did have this key present, the value is updated, and the old
1023 /// value is returned. The key is not updated, though; this matters for
1024 /// types that can be `==` without being identical. See the [module-level
1025 /// documentation] for more.
1026 ///
1027 /// [module-level documentation]: index.html#insert-and-complex-keys
1028 ///
1029 /// # Examples
1030 ///
1031 /// ```
1032 /// use std::collections::BTreeMap;
1033 ///
1034 /// let mut map = BTreeMap::new();
1035 /// assert_eq!(map.insert(37, "a"), None);
1036 /// assert_eq!(map.is_empty(), false);
1037 ///
1038 /// map.insert(37, "b");
1039 /// assert_eq!(map.insert(37, "c"), Some("b"));
1040 /// assert_eq!(map[&37], "c");
1041 /// ```
1042 #[stable(feature = "rust1", since = "1.0.0")]
1043 #[rustc_confusables("push", "put", "set")]
1044 #[cfg_attr(not(test), rustc_diagnostic_item = "btreemap_insert")]
1045 pub fn insert(&mut self, key: K, value: V) -> Option<V>
1046 where
1047 K: Ord,
1048 {
1049 match self.entry(key) {
1050 Occupied(mut entry) => Some(entry.insert(value)),
1051 Vacant(entry) => {
1052 entry.insert(value);
1053 None
1054 }
1055 }
1056 }
1057
1058 /// Tries to insert a key-value pair into the map, and returns
1059 /// a mutable reference to the value in the entry.
1060 ///
1061 /// If the map already had this key present, nothing is updated, and
1062 /// an error containing the occupied entry, key, and the value is returned.
1063 ///
1064 /// # Examples
1065 ///
1066 /// ```
1067 /// #![feature(map_try_insert)]
1068 ///
1069 /// use std::collections::BTreeMap;
1070 ///
1071 /// let mut map = BTreeMap::new();
1072 /// assert_eq!(map.try_insert(37, "a").unwrap(), &"a");
1073 ///
1074 /// let err = map.try_insert(37, "b").unwrap_err();
1075 /// assert_eq!(err.entry.key(), &37);
1076 /// assert_eq!(err.entry.get(), &"a");
1077 /// assert_eq!(err.key, 37);
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 let (map, dormant_map) = DormantMutRef::new(self);
1086 let handle = match map.root {
1087 Some(ref mut root) => match root.borrow_mut().search_tree(&key) {
1088 Found(handle) => {
1089 let entry = OccupiedEntry {
1090 handle,
1091 dormant_map,
1092 alloc: (*map.alloc).clone(),
1093 _marker: PhantomData,
1094 };
1095 return Err(OccupiedError { entry, key, value });
1096 }
1097 GoDown(handle) => Some(handle),
1098 },
1099 None => None,
1100 };
1101 let entry = VacantEntry {
1102 key,
1103 handle,
1104 dormant_map,
1105 alloc: (*map.alloc).clone(),
1106 _marker: PhantomData,
1107 };
1108 Ok(entry.insert(value))
1109 }
1110
1111 /// Removes a key from the map, returning the value at the key if the key
1112 /// was previously in the map.
1113 ///
1114 /// The key may be any borrowed form of the map's key type, but the ordering
1115 /// on the borrowed form *must* match the ordering on the key type.
1116 ///
1117 /// # Examples
1118 ///
1119 /// ```
1120 /// use std::collections::BTreeMap;
1121 ///
1122 /// let mut map = BTreeMap::new();
1123 /// map.insert(1, "a");
1124 /// assert_eq!(map.remove(&1), Some("a"));
1125 /// assert_eq!(map.remove(&1), None);
1126 /// ```
1127 #[stable(feature = "rust1", since = "1.0.0")]
1128 #[rustc_confusables("delete", "take")]
1129 pub fn remove<Q: ?Sized>(&mut self, key: &Q) -> Option<V>
1130 where
1131 K: Borrow<Q> + Ord,
1132 Q: Ord,
1133 {
1134 self.remove_entry(key).map(|(_, v)| v)
1135 }
1136
1137 /// Removes a key from the map, returning the stored key and value if the key
1138 /// was previously in the map.
1139 ///
1140 /// The key may be any borrowed form of the map's key type, but the ordering
1141 /// on the borrowed form *must* match the ordering on the key type.
1142 ///
1143 /// # Examples
1144 ///
1145 /// ```
1146 /// use std::collections::BTreeMap;
1147 ///
1148 /// let mut map = BTreeMap::new();
1149 /// map.insert(1, "a");
1150 /// assert_eq!(map.remove_entry(&1), Some((1, "a")));
1151 /// assert_eq!(map.remove_entry(&1), None);
1152 /// ```
1153 #[stable(feature = "btreemap_remove_entry", since = "1.45.0")]
1154 pub fn remove_entry<Q: ?Sized>(&mut self, key: &Q) -> Option<(K, V)>
1155 where
1156 K: Borrow<Q> + Ord,
1157 Q: Ord,
1158 {
1159 let (map, dormant_map) = DormantMutRef::new(self);
1160 let root_node = map.root.as_mut()?.borrow_mut();
1161 match root_node.search_tree(key) {
1162 Found(handle) => Some(
1163 OccupiedEntry {
1164 handle,
1165 dormant_map,
1166 alloc: (*map.alloc).clone(),
1167 _marker: PhantomData,
1168 }
1169 .remove_entry(),
1170 ),
1171 GoDown(_) => None,
1172 }
1173 }
1174
1175 /// Retains only the elements specified by the predicate.
1176 ///
1177 /// In other words, remove all pairs `(k, v)` for which `f(&k, &mut v)` returns `false`.
1178 /// The elements are visited in ascending key order.
1179 ///
1180 /// # Examples
1181 ///
1182 /// ```
1183 /// use std::collections::BTreeMap;
1184 ///
1185 /// let mut map: BTreeMap<i32, i32> = (0..8).map(|x| (x, x*10)).collect();
1186 /// // Keep only the elements with even-numbered keys.
1187 /// map.retain(|&k, _| k % 2 == 0);
1188 /// assert!(map.into_iter().eq(vec![(0, 0), (2, 20), (4, 40), (6, 60)]));
1189 /// ```
1190 #[inline]
1191 #[stable(feature = "btree_retain", since = "1.53.0")]
1192 pub fn retain<F>(&mut self, mut f: F)
1193 where
1194 K: Ord,
1195 F: FnMut(&K, &mut V) -> bool,
1196 {
1197 self.extract_if(.., |k, v| !f(k, v)).for_each(drop);
1198 }
1199
1200 /// Moves all elements from `other` into `self`, leaving `other` empty.
1201 ///
1202 /// If a key from `other` is already present in `self`, the respective
1203 /// value from `self` will be overwritten with the respective value from `other`.
1204 /// Similar to [`insert`], though, the key is not overwritten,
1205 /// which matters for types that can be `==` without being identical.
1206 ///
1207 /// [`insert`]: BTreeMap::insert
1208 ///
1209 /// # Examples
1210 ///
1211 /// ```
1212 /// use std::collections::BTreeMap;
1213 ///
1214 /// let mut a = BTreeMap::new();
1215 /// a.insert(1, "a");
1216 /// a.insert(2, "b");
1217 /// a.insert(3, "c"); // Note: Key (3) also present in b.
1218 ///
1219 /// let mut b = BTreeMap::new();
1220 /// b.insert(3, "d"); // Note: Key (3) also present in a.
1221 /// b.insert(4, "e");
1222 /// b.insert(5, "f");
1223 ///
1224 /// a.append(&mut b);
1225 ///
1226 /// assert_eq!(a.len(), 5);
1227 /// assert_eq!(b.len(), 0);
1228 ///
1229 /// assert_eq!(a[&1], "a");
1230 /// assert_eq!(a[&2], "b");
1231 /// assert_eq!(a[&3], "d"); // Note: "c" has been overwritten.
1232 /// assert_eq!(a[&4], "e");
1233 /// assert_eq!(a[&5], "f");
1234 /// ```
1235 #[stable(feature = "btree_append", since = "1.11.0")]
1236 pub fn append(&mut self, other: &mut Self)
1237 where
1238 K: Ord,
1239 A: Clone,
1240 {
1241 let other = mem::replace(other, Self::new_in((*self.alloc).clone()));
1242 self.merge(other, |_key, _self_val, other_val| other_val);
1243 }
1244
1245 /// Moves all elements from `other` into `self`, leaving `other` empty.
1246 ///
1247 /// If a key from `other` is already present in `self`, then the `conflict`
1248 /// closure is used to return a value to `self`. The `conflict`
1249 /// closure takes in a borrow of `self`'s key, `self`'s value, and `other`'s value
1250 /// in that order.
1251 ///
1252 /// An example of why one might use this method over [`append`]
1253 /// is to combine `self`'s value with `other`'s value when their keys conflict.
1254 ///
1255 /// Similar to [`insert`], though, the key is not overwritten,
1256 /// which matters for types that can be `==` without being identical.
1257 ///
1258 /// [`insert`]: BTreeMap::insert
1259 /// [`append`]: BTreeMap::append
1260 ///
1261 /// # Examples
1262 ///
1263 /// ```
1264 /// #![feature(btree_merge)]
1265 /// use std::collections::BTreeMap;
1266 ///
1267 /// let mut a = BTreeMap::new();
1268 /// a.insert(1, String::from("a"));
1269 /// a.insert(2, String::from("b"));
1270 /// a.insert(3, String::from("c")); // Note: Key (3) also present in b.
1271 ///
1272 /// let mut b = BTreeMap::new();
1273 /// b.insert(3, String::from("d")); // Note: Key (3) also present in a.
1274 /// b.insert(4, String::from("e"));
1275 /// b.insert(5, String::from("f"));
1276 ///
1277 /// // concatenate a's value and b's value
1278 /// a.merge(b, |_, a_val, b_val| {
1279 /// format!("{a_val}{b_val}")
1280 /// });
1281 ///
1282 /// assert_eq!(a.len(), 5); // all of b's keys in a
1283 ///
1284 /// assert_eq!(a[&1], "a");
1285 /// assert_eq!(a[&2], "b");
1286 /// assert_eq!(a[&3], "cd"); // Note: "c" has been combined with "d".
1287 /// assert_eq!(a[&4], "e");
1288 /// assert_eq!(a[&5], "f");
1289 /// ```
1290 #[unstable(feature = "btree_merge", issue = "152152")]
1291 pub fn merge(&mut self, mut other: Self, mut conflict: impl FnMut(&K, V, V) -> V)
1292 where
1293 K: Ord,
1294 A: Clone,
1295 {
1296 // Do we have to append anything at all?
1297 if other.is_empty() {
1298 return;
1299 }
1300
1301 // We can just swap `self` and `other` if `self` is empty.
1302 if self.is_empty() {
1303 mem::swap(self, &mut other);
1304 return;
1305 }
1306
1307 let mut other_iter = other.into_iter();
1308 let (first_other_key, first_other_val) = other_iter.next().unwrap();
1309
1310 // find the first gap that has the smallest key greater than or equal to
1311 // the first key from other
1312 let mut self_cursor = self.lower_bound_mut(Bound::Included(&first_other_key));
1313
1314 if let Some((self_key, _)) = self_cursor.peek_next() {
1315 match K::cmp(self_key, &first_other_key) {
1316 Ordering::Equal => {
1317 // if `f` unwinds, the next entry is already removed leaving
1318 // the tree in valid state.
1319 // FIXME: Once `MaybeDangling` is implemented, we can optimize
1320 // this through using a drop handler and transmutating CursorMutKey<K, V>
1321 // to CursorMutKey<ManuallyDrop<K>, ManuallyDrop<V>> (see PR #152418)
1322 if let Some((k, v)) = self_cursor.remove_next() {
1323 // SAFETY: we remove the K, V out of the next entry,
1324 // apply 'f' to get a new (K, V), and insert it back
1325 // into the next entry that the cursor is pointing at
1326 let v = conflict(&k, v, first_other_val);
1327 unsafe { self_cursor.insert_after_unchecked(k, v) };
1328 }
1329 }
1330 Ordering::Greater =>
1331 // SAFETY: we know our other_key's ordering is less than self_key,
1332 // so inserting before will guarantee sorted order
1333 unsafe {
1334 self_cursor.insert_before_unchecked(first_other_key, first_other_val);
1335 },
1336 Ordering::Less => {
1337 unreachable!("Cursor's peek_next should return None.");
1338 }
1339 }
1340 } else {
1341 // SAFETY: reaching here means our cursor is at the end
1342 // self BTreeMap so we just insert other_key here
1343 unsafe {
1344 self_cursor.insert_before_unchecked(first_other_key, first_other_val);
1345 }
1346 }
1347
1348 for (other_key, other_val) in other_iter {
1349 loop {
1350 if let Some((self_key, _)) = self_cursor.peek_next() {
1351 match K::cmp(self_key, &other_key) {
1352 Ordering::Equal => {
1353 // if `f` unwinds, the next entry is already removed leaving
1354 // the tree in valid state.
1355 // FIXME: Once `MaybeDangling` is implemented, we can optimize
1356 // this through using a drop handler and transmutating CursorMutKey<K, V>
1357 // to CursorMutKey<ManuallyDrop<K>, ManuallyDrop<V>> (see PR #152418)
1358 if let Some((k, v)) = self_cursor.remove_next() {
1359 // SAFETY: we remove the K, V out of the next entry,
1360 // apply 'f' to get a new (K, V), and insert it back
1361 // into the next entry that the cursor is pointing at
1362 let v = conflict(&k, v, other_val);
1363 unsafe { self_cursor.insert_after_unchecked(k, v) };
1364 }
1365 break;
1366 }
1367 Ordering::Greater => {
1368 // SAFETY: we know our self_key's ordering is greater than other_key,
1369 // so inserting before will guarantee sorted order
1370 unsafe {
1371 self_cursor.insert_before_unchecked(other_key, other_val);
1372 }
1373 break;
1374 }
1375 Ordering::Less => {
1376 // FIXME: instead of doing a linear search here,
1377 // this can be optimized to search the tree by starting
1378 // from self_cursor and going towards the root and then
1379 // back down to the proper node -- that should probably
1380 // be a new method on Cursor*.
1381 self_cursor.next();
1382 }
1383 }
1384 } else {
1385 // FIXME: If we get here, that means all of other's keys are greater than
1386 // self's keys. For performance, this should really do a bulk insertion of items
1387 // from other_iter into the end of self `BTreeMap`. Maybe this should be
1388 // a method for Cursor*?
1389
1390 // SAFETY: reaching here means our cursor is at the end
1391 // self BTreeMap so we just insert other_key here
1392 unsafe {
1393 self_cursor.insert_before_unchecked(other_key, other_val);
1394 }
1395 break;
1396 }
1397 }
1398 }
1399 }
1400
1401 /// Constructs a double-ended iterator over a sub-range of elements in the map.
1402 /// The simplest way is to use the range syntax `min..max`, thus `range(min..max)` will
1403 /// yield elements from min (inclusive) to max (exclusive).
1404 /// The range may also be entered as `(Bound<T>, Bound<T>)`, so for example
1405 /// `range((Excluded(4), Included(10)))` will yield a left-exclusive, right-inclusive
1406 /// range from 4 to 10.
1407 ///
1408 /// # Panics
1409 ///
1410 /// Panics if range `start > end`.
1411 /// Panics if range `start == end` and both bounds are `Excluded`.
1412 ///
1413 /// # Examples
1414 ///
1415 /// ```
1416 /// use std::collections::BTreeMap;
1417 /// use std::ops::Bound::Included;
1418 ///
1419 /// let mut map = BTreeMap::new();
1420 /// map.insert(3, "a");
1421 /// map.insert(5, "b");
1422 /// map.insert(8, "c");
1423 /// for (&key, &value) in map.range((Included(&4), Included(&8))) {
1424 /// println!("{key}: {value}");
1425 /// }
1426 /// assert_eq!(Some((&5, &"b")), map.range(4..).next());
1427 /// ```
1428 #[stable(feature = "btree_range", since = "1.17.0")]
1429 pub fn range<T: ?Sized, R>(&self, range: R) -> Range<'_, K, V>
1430 where
1431 T: Ord,
1432 K: Borrow<T> + Ord,
1433 R: RangeBounds<T>,
1434 {
1435 if let Some(root) = &self.root {
1436 Range { inner: root.reborrow().range_search(range) }
1437 } else {
1438 Range { inner: LeafRange::none() }
1439 }
1440 }
1441
1442 /// Constructs a mutable double-ended iterator over a sub-range of elements in the map.
1443 /// The simplest way is to use the range syntax `min..max`, thus `range(min..max)` will
1444 /// yield elements from min (inclusive) to max (exclusive).
1445 /// The range may also be entered as `(Bound<T>, Bound<T>)`, so for example
1446 /// `range((Excluded(4), Included(10)))` will yield a left-exclusive, right-inclusive
1447 /// range from 4 to 10.
1448 ///
1449 /// # Panics
1450 ///
1451 /// Panics if range `start > end`.
1452 /// Panics if range `start == end` and both bounds are `Excluded`.
1453 ///
1454 /// # Examples
1455 ///
1456 /// ```
1457 /// use std::collections::BTreeMap;
1458 ///
1459 /// let mut map: BTreeMap<&str, i32> =
1460 /// [("Alice", 0), ("Bob", 0), ("Carol", 0), ("Cheryl", 0)].into();
1461 /// for (_, balance) in map.range_mut("B".."Cheryl") {
1462 /// *balance += 100;
1463 /// }
1464 /// for (name, balance) in &map {
1465 /// println!("{name} => {balance}");
1466 /// }
1467 /// ```
1468 #[stable(feature = "btree_range", since = "1.17.0")]
1469 pub fn range_mut<T: ?Sized, R>(&mut self, range: R) -> RangeMut<'_, K, V>
1470 where
1471 T: Ord,
1472 K: Borrow<T> + Ord,
1473 R: RangeBounds<T>,
1474 {
1475 if let Some(root) = &mut self.root {
1476 RangeMut { inner: root.borrow_valmut().range_search(range), _marker: PhantomData }
1477 } else {
1478 RangeMut { inner: LeafRange::none(), _marker: PhantomData }
1479 }
1480 }
1481
1482 /// Gets the given key's corresponding entry in the map for in-place manipulation.
1483 ///
1484 /// # Examples
1485 ///
1486 /// ```
1487 /// use std::collections::BTreeMap;
1488 ///
1489 /// let mut count: BTreeMap<&str, usize> = BTreeMap::new();
1490 ///
1491 /// // count the number of occurrences of letters in the vec
1492 /// for x in ["a", "b", "a", "c", "a", "b"] {
1493 /// count.entry(x).and_modify(|curr| *curr += 1).or_insert(1);
1494 /// }
1495 ///
1496 /// assert_eq!(count["a"], 3);
1497 /// assert_eq!(count["b"], 2);
1498 /// assert_eq!(count["c"], 1);
1499 /// ```
1500 #[stable(feature = "rust1", since = "1.0.0")]
1501 pub fn entry(&mut self, key: K) -> Entry<'_, K, V, A>
1502 where
1503 K: Ord,
1504 {
1505 let (map, dormant_map) = DormantMutRef::new(self);
1506 match map.root {
1507 None => Vacant(VacantEntry {
1508 key,
1509 handle: None,
1510 dormant_map,
1511 alloc: (*map.alloc).clone(),
1512 _marker: PhantomData,
1513 }),
1514 Some(ref mut root) => match root.borrow_mut().search_tree(&key) {
1515 Found(handle) => Occupied(OccupiedEntry {
1516 handle,
1517 dormant_map,
1518 alloc: (*map.alloc).clone(),
1519 _marker: PhantomData,
1520 }),
1521 GoDown(handle) => Vacant(VacantEntry {
1522 key,
1523 handle: Some(handle),
1524 dormant_map,
1525 alloc: (*map.alloc).clone(),
1526 _marker: PhantomData,
1527 }),
1528 },
1529 }
1530 }
1531
1532 /// Splits the collection into two at the given key. Returns everything after the given key,
1533 /// including the key. If the key is not present, the split will occur at the nearest
1534 /// greater key, or return an empty map if no such key exists.
1535 ///
1536 /// # Examples
1537 ///
1538 /// ```
1539 /// use std::collections::BTreeMap;
1540 ///
1541 /// let mut a = BTreeMap::new();
1542 /// a.insert(1, "a");
1543 /// a.insert(2, "b");
1544 /// a.insert(3, "c");
1545 /// a.insert(17, "d");
1546 /// a.insert(41, "e");
1547 ///
1548 /// let b = a.split_off(&3);
1549 ///
1550 /// assert_eq!(a.len(), 2);
1551 /// assert_eq!(b.len(), 3);
1552 ///
1553 /// assert_eq!(a[&1], "a");
1554 /// assert_eq!(a[&2], "b");
1555 ///
1556 /// assert_eq!(b[&3], "c");
1557 /// assert_eq!(b[&17], "d");
1558 /// assert_eq!(b[&41], "e");
1559 /// ```
1560 #[stable(feature = "btree_split_off", since = "1.11.0")]
1561 pub fn split_off<Q: ?Sized + Ord>(&mut self, key: &Q) -> Self
1562 where
1563 K: Borrow<Q> + Ord,
1564 A: Clone,
1565 {
1566 if self.is_empty() {
1567 return Self::new_in((*self.alloc).clone());
1568 }
1569
1570 let total_num = self.len();
1571 let left_root = self.root.as_mut().unwrap(); // unwrap succeeds because not empty
1572
1573 let right_root = left_root.split_off(key, (*self.alloc).clone());
1574
1575 let (new_left_len, right_len) = Root::calc_split_length(total_num, left_root, &right_root);
1576 self.length = new_left_len;
1577
1578 BTreeMap {
1579 root: Some(right_root),
1580 length: right_len,
1581 alloc: self.alloc.clone(),
1582 _marker: PhantomData,
1583 }
1584 }
1585
1586 /// Creates an iterator that visits elements (key-value pairs) in the specified range in
1587 /// ascending key order and uses a closure to determine if an element
1588 /// should be removed.
1589 ///
1590 /// If the closure returns `true`, the element is removed from the map and
1591 /// yielded. If the closure returns `false`, or panics, the element remains
1592 /// in the map and will not be yielded.
1593 ///
1594 /// The iterator also lets you mutate the value of each element in the
1595 /// closure, regardless of whether you choose to keep or remove it.
1596 ///
1597 /// If the returned `ExtractIf` is not exhausted, e.g. because it is dropped without iterating
1598 /// or the iteration short-circuits, then the remaining elements will be retained.
1599 /// Use `extract_if().for_each(drop)` if you do not need the returned iterator,
1600 /// or [`retain`] with a negated predicate if you also do not need to restrict the range.
1601 ///
1602 /// [`retain`]: BTreeMap::retain
1603 ///
1604 /// # Examples
1605 ///
1606 /// ```
1607 /// use std::collections::BTreeMap;
1608 ///
1609 /// // Splitting a map into even and odd keys, reusing the original map:
1610 /// let mut map: BTreeMap<i32, i32> = (0..8).map(|x| (x, x)).collect();
1611 /// let evens: BTreeMap<_, _> = map.extract_if(.., |k, _v| k % 2 == 0).collect();
1612 /// let odds = map;
1613 /// assert_eq!(evens.keys().copied().collect::<Vec<_>>(), [0, 2, 4, 6]);
1614 /// assert_eq!(odds.keys().copied().collect::<Vec<_>>(), [1, 3, 5, 7]);
1615 ///
1616 /// // Splitting a map into low and high halves, reusing the original map:
1617 /// let mut map: BTreeMap<i32, i32> = (0..8).map(|x| (x, x)).collect();
1618 /// let low: BTreeMap<_, _> = map.extract_if(0..4, |_k, _v| true).collect();
1619 /// let high = map;
1620 /// assert_eq!(low.keys().copied().collect::<Vec<_>>(), [0, 1, 2, 3]);
1621 /// assert_eq!(high.keys().copied().collect::<Vec<_>>(), [4, 5, 6, 7]);
1622 /// ```
1623 #[stable(feature = "btree_extract_if", since = "1.91.0")]
1624 pub fn extract_if<F, R>(&mut self, range: R, pred: F) -> ExtractIf<'_, K, V, R, F, A>
1625 where
1626 K: Ord,
1627 R: RangeBounds<K>,
1628 F: FnMut(&K, &mut V) -> bool,
1629 {
1630 let (inner, alloc) = self.extract_if_inner(range);
1631 ExtractIf { pred, inner, alloc }
1632 }
1633
1634 pub(super) fn extract_if_inner<R>(&mut self, range: R) -> (ExtractIfInner<'_, K, V, R>, A)
1635 where
1636 K: Ord,
1637 R: RangeBounds<K>,
1638 {
1639 if let Some(root) = self.root.as_mut() {
1640 let (root, dormant_root) = DormantMutRef::new(root);
1641 let first = root.borrow_mut().lower_bound(SearchBound::from_range(range.start_bound()));
1642 (
1643 ExtractIfInner {
1644 length: &mut self.length,
1645 dormant_root: Some(dormant_root),
1646 cur_leaf_edge: Some(first),
1647 range,
1648 },
1649 (*self.alloc).clone(),
1650 )
1651 } else {
1652 (
1653 ExtractIfInner {
1654 length: &mut self.length,
1655 dormant_root: None,
1656 cur_leaf_edge: None,
1657 range,
1658 },
1659 (*self.alloc).clone(),
1660 )
1661 }
1662 }
1663
1664 /// Creates a consuming iterator visiting all the keys, in sorted order.
1665 /// The map cannot be used after calling this.
1666 /// The iterator element type is `K`.
1667 ///
1668 /// # Examples
1669 ///
1670 /// ```
1671 /// use std::collections::BTreeMap;
1672 ///
1673 /// let mut a = BTreeMap::new();
1674 /// a.insert(2, "b");
1675 /// a.insert(1, "a");
1676 ///
1677 /// let keys: Vec<i32> = a.into_keys().collect();
1678 /// assert_eq!(keys, [1, 2]);
1679 /// ```
1680 #[inline]
1681 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
1682 pub fn into_keys(self) -> IntoKeys<K, V, A> {
1683 IntoKeys { inner: self.into_iter() }
1684 }
1685
1686 /// Creates a consuming iterator visiting all the values, in order by key.
1687 /// The map cannot be used after calling this.
1688 /// The iterator element type is `V`.
1689 ///
1690 /// # Examples
1691 ///
1692 /// ```
1693 /// use std::collections::BTreeMap;
1694 ///
1695 /// let mut a = BTreeMap::new();
1696 /// a.insert(1, "hello");
1697 /// a.insert(2, "goodbye");
1698 ///
1699 /// let values: Vec<&str> = a.into_values().collect();
1700 /// assert_eq!(values, ["hello", "goodbye"]);
1701 /// ```
1702 #[inline]
1703 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
1704 pub fn into_values(self) -> IntoValues<K, V, A> {
1705 IntoValues { inner: self.into_iter() }
1706 }
1707
1708 /// Makes a `BTreeMap` from a sorted iterator.
1709 pub(crate) fn bulk_build_from_sorted_iter<I>(iter: I, alloc: A) -> Self
1710 where
1711 K: Ord,
1712 I: IntoIterator<Item = (K, V)>,
1713 {
1714 let mut root = Root::new(alloc.clone());
1715 let mut length = 0;
1716 root.bulk_push(DedupSortedIter::new(iter.into_iter()), &mut length, alloc.clone());
1717 BTreeMap { root: Some(root), length, alloc: ManuallyDrop::new(alloc), _marker: PhantomData }
1718 }
1719}
1720
1721#[stable(feature = "rust1", since = "1.0.0")]
1722impl<'a, K, V, A: AllocatorClone> IntoIterator for &'a BTreeMap<K, V, A> {
1723 type Item = (&'a K, &'a V);
1724 type IntoIter = Iter<'a, K, V>;
1725
1726 fn into_iter(self) -> Iter<'a, K, V> {
1727 self.iter()
1728 }
1729}
1730
1731#[stable(feature = "rust1", since = "1.0.0")]
1732impl<'a, K: 'a, V: 'a> Iterator for Iter<'a, K, V> {
1733 type Item = (&'a K, &'a V);
1734
1735 fn next(&mut self) -> Option<(&'a K, &'a V)> {
1736 if self.length == 0 {
1737 None
1738 } else {
1739 self.length -= 1;
1740 Some(unsafe { self.range.next_unchecked() })
1741 }
1742 }
1743
1744 fn size_hint(&self) -> (usize, Option<usize>) {
1745 (self.length, Some(self.length))
1746 }
1747
1748 fn last(mut self) -> Option<(&'a K, &'a V)> {
1749 self.next_back()
1750 }
1751
1752 fn min(mut self) -> Option<(&'a K, &'a V)>
1753 where
1754 (&'a K, &'a V): Ord,
1755 {
1756 self.next()
1757 }
1758
1759 fn max(mut self) -> Option<(&'a K, &'a V)>
1760 where
1761 (&'a K, &'a V): Ord,
1762 {
1763 self.next_back()
1764 }
1765}
1766
1767#[stable(feature = "fused", since = "1.26.0")]
1768impl<K, V> FusedIterator for Iter<'_, K, V> {}
1769
1770#[stable(feature = "rust1", since = "1.0.0")]
1771impl<'a, K: 'a, V: 'a> DoubleEndedIterator for Iter<'a, K, V> {
1772 fn next_back(&mut self) -> Option<(&'a K, &'a V)> {
1773 if self.length == 0 {
1774 None
1775 } else {
1776 self.length -= 1;
1777 Some(unsafe { self.range.next_back_unchecked() })
1778 }
1779 }
1780}
1781
1782#[stable(feature = "rust1", since = "1.0.0")]
1783impl<K, V> ExactSizeIterator for Iter<'_, K, V> {
1784 fn len(&self) -> usize {
1785 self.length
1786 }
1787}
1788
1789#[unstable(feature = "trusted_len", issue = "37572")]
1790unsafe impl<K, V> TrustedLen for Iter<'_, K, V> {}
1791
1792#[stable(feature = "rust1", since = "1.0.0")]
1793impl<K, V> Clone for Iter<'_, K, V> {
1794 fn clone(&self) -> Self {
1795 Iter { range: self.range.clone(), length: self.length }
1796 }
1797}
1798
1799#[stable(feature = "rust1", since = "1.0.0")]
1800impl<'a, K, V, A: AllocatorClone> IntoIterator for &'a mut BTreeMap<K, V, A> {
1801 type Item = (&'a K, &'a mut V);
1802 type IntoIter = IterMut<'a, K, V>;
1803
1804 fn into_iter(self) -> IterMut<'a, K, V> {
1805 self.iter_mut()
1806 }
1807}
1808
1809#[stable(feature = "rust1", since = "1.0.0")]
1810impl<'a, K, V> Iterator for IterMut<'a, K, V> {
1811 type Item = (&'a K, &'a mut V);
1812
1813 fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
1814 if self.length == 0 {
1815 None
1816 } else {
1817 self.length -= 1;
1818 Some(unsafe { self.range.next_unchecked() })
1819 }
1820 }
1821
1822 fn size_hint(&self) -> (usize, Option<usize>) {
1823 (self.length, Some(self.length))
1824 }
1825
1826 fn last(mut self) -> Option<(&'a K, &'a mut V)> {
1827 self.next_back()
1828 }
1829
1830 fn min(mut self) -> Option<(&'a K, &'a mut V)>
1831 where
1832 (&'a K, &'a mut V): Ord,
1833 {
1834 self.next()
1835 }
1836
1837 fn max(mut self) -> Option<(&'a K, &'a mut V)>
1838 where
1839 (&'a K, &'a mut V): Ord,
1840 {
1841 self.next_back()
1842 }
1843}
1844
1845#[stable(feature = "rust1", since = "1.0.0")]
1846impl<'a, K, V> DoubleEndedIterator for IterMut<'a, K, V> {
1847 fn next_back(&mut self) -> Option<(&'a K, &'a mut V)> {
1848 if self.length == 0 {
1849 None
1850 } else {
1851 self.length -= 1;
1852 Some(unsafe { self.range.next_back_unchecked() })
1853 }
1854 }
1855}
1856
1857#[stable(feature = "rust1", since = "1.0.0")]
1858impl<K, V> ExactSizeIterator for IterMut<'_, K, V> {
1859 fn len(&self) -> usize {
1860 self.length
1861 }
1862}
1863
1864#[unstable(feature = "trusted_len", issue = "37572")]
1865unsafe impl<K, V> TrustedLen for IterMut<'_, K, V> {}
1866
1867#[stable(feature = "fused", since = "1.26.0")]
1868impl<K, V> FusedIterator for IterMut<'_, K, V> {}
1869
1870impl<'a, K, V> IterMut<'a, K, V> {
1871 /// Returns an iterator of references over the remaining items.
1872 #[inline]
1873 pub(super) fn iter(&self) -> Iter<'_, K, V> {
1874 Iter { range: self.range.reborrow(), length: self.length }
1875 }
1876}
1877
1878#[stable(feature = "rust1", since = "1.0.0")]
1879impl<K, V, A: AllocatorClone> IntoIterator for BTreeMap<K, V, A> {
1880 type Item = (K, V);
1881 type IntoIter = IntoIter<K, V, A>;
1882
1883 /// Gets an owning iterator over the entries of the map, sorted by key.
1884 fn into_iter(self) -> IntoIter<K, V, A> {
1885 let mut me = ManuallyDrop::new(self);
1886 if let Some(root) = me.root.take() {
1887 let full_range = root.into_dying().full_range();
1888
1889 IntoIter {
1890 range: full_range,
1891 length: me.length,
1892 alloc: unsafe { ManuallyDrop::take(&mut me.alloc) },
1893 }
1894 } else {
1895 IntoIter {
1896 range: LazyLeafRange::none(),
1897 length: 0,
1898 alloc: unsafe { ManuallyDrop::take(&mut me.alloc) },
1899 }
1900 }
1901 }
1902}
1903
1904#[stable(feature = "btree_drop", since = "1.7.0")]
1905impl<K, V, A: AllocatorClone> Drop for IntoIter<K, V, A> {
1906 fn drop(&mut self) {
1907 struct DropGuard<'a, K, V, A: AllocatorClone>(&'a mut IntoIter<K, V, A>);
1908
1909 impl<'a, K, V, A: AllocatorClone> Drop for DropGuard<'a, K, V, A> {
1910 fn drop(&mut self) {
1911 // Continue the same loop we perform below. This only runs when unwinding, so we
1912 // don't have to care about panics this time (they'll abort).
1913 while let Some(kv) = self.0.dying_next() {
1914 // SAFETY: we consume the dying handle immediately.
1915 unsafe { kv.drop_key_val() };
1916 }
1917 }
1918 }
1919
1920 while let Some(kv) = self.dying_next() {
1921 let guard = DropGuard(self);
1922 // SAFETY: we don't touch the tree before consuming the dying handle.
1923 unsafe { kv.drop_key_val() };
1924 mem::forget(guard);
1925 }
1926 }
1927}
1928
1929impl<K, V, A: AllocatorClone> IntoIter<K, V, A> {
1930 /// Core of a `next` method returning a dying KV handle,
1931 /// invalidated by further calls to this function and some others.
1932 fn dying_next(
1933 &mut self,
1934 ) -> Option<Handle<NodeRef<marker::Dying, K, V, marker::LeafOrInternal>, marker::KV>> {
1935 if self.length == 0 {
1936 self.range.deallocating_end(self.alloc.clone());
1937 None
1938 } else {
1939 self.length -= 1;
1940 Some(unsafe { self.range.deallocating_next_unchecked(self.alloc.clone()) })
1941 }
1942 }
1943
1944 /// Core of a `next_back` method returning a dying KV handle,
1945 /// invalidated by further calls to this function and some others.
1946 fn dying_next_back(
1947 &mut self,
1948 ) -> Option<Handle<NodeRef<marker::Dying, K, V, marker::LeafOrInternal>, marker::KV>> {
1949 if self.length == 0 {
1950 self.range.deallocating_end(self.alloc.clone());
1951 None
1952 } else {
1953 self.length -= 1;
1954 Some(unsafe { self.range.deallocating_next_back_unchecked(self.alloc.clone()) })
1955 }
1956 }
1957}
1958
1959#[stable(feature = "rust1", since = "1.0.0")]
1960impl<K, V, A: AllocatorClone> Iterator for IntoIter<K, V, A> {
1961 type Item = (K, V);
1962
1963 fn next(&mut self) -> Option<(K, V)> {
1964 // SAFETY: we consume the dying handle immediately.
1965 self.dying_next().map(unsafe { |kv| kv.into_key_val() })
1966 }
1967
1968 fn size_hint(&self) -> (usize, Option<usize>) {
1969 (self.length, Some(self.length))
1970 }
1971}
1972
1973#[stable(feature = "rust1", since = "1.0.0")]
1974impl<K, V, A: AllocatorClone> DoubleEndedIterator for IntoIter<K, V, A> {
1975 fn next_back(&mut self) -> Option<(K, V)> {
1976 // SAFETY: we consume the dying handle immediately.
1977 self.dying_next_back().map(unsafe { |kv| kv.into_key_val() })
1978 }
1979}
1980
1981#[stable(feature = "rust1", since = "1.0.0")]
1982impl<K, V, A: AllocatorClone> ExactSizeIterator for IntoIter<K, V, A> {
1983 fn len(&self) -> usize {
1984 self.length
1985 }
1986}
1987
1988#[unstable(feature = "trusted_len", issue = "37572")]
1989unsafe impl<K, V, A: AllocatorClone> TrustedLen for IntoIter<K, V, A> {}
1990
1991#[stable(feature = "fused", since = "1.26.0")]
1992impl<K, V, A: AllocatorClone> FusedIterator for IntoIter<K, V, A> {}
1993
1994#[stable(feature = "rust1", since = "1.0.0")]
1995impl<'a, K, V> Iterator for Keys<'a, K, V> {
1996 type Item = &'a K;
1997
1998 fn next(&mut self) -> Option<&'a K> {
1999 self.inner.next().map(|(k, _)| k)
2000 }
2001
2002 fn size_hint(&self) -> (usize, Option<usize>) {
2003 self.inner.size_hint()
2004 }
2005
2006 fn last(mut self) -> Option<&'a K> {
2007 self.next_back()
2008 }
2009
2010 fn min(mut self) -> Option<&'a K>
2011 where
2012 &'a K: Ord,
2013 {
2014 self.next()
2015 }
2016
2017 fn max(mut self) -> Option<&'a K>
2018 where
2019 &'a K: Ord,
2020 {
2021 self.next_back()
2022 }
2023}
2024
2025#[stable(feature = "rust1", since = "1.0.0")]
2026impl<'a, K, V> DoubleEndedIterator for Keys<'a, K, V> {
2027 fn next_back(&mut self) -> Option<&'a K> {
2028 self.inner.next_back().map(|(k, _)| k)
2029 }
2030}
2031
2032#[stable(feature = "rust1", since = "1.0.0")]
2033impl<K, V> ExactSizeIterator for Keys<'_, K, V> {
2034 fn len(&self) -> usize {
2035 self.inner.len()
2036 }
2037}
2038
2039#[unstable(feature = "trusted_len", issue = "37572")]
2040unsafe impl<K, V> TrustedLen for Keys<'_, K, V> {}
2041
2042#[stable(feature = "fused", since = "1.26.0")]
2043impl<K, V> FusedIterator for Keys<'_, K, V> {}
2044
2045#[stable(feature = "rust1", since = "1.0.0")]
2046impl<K, V> Clone for Keys<'_, K, V> {
2047 fn clone(&self) -> Self {
2048 Keys { inner: self.inner.clone() }
2049 }
2050}
2051
2052#[stable(feature = "default_iters", since = "1.70.0")]
2053impl<K, V> Default for Keys<'_, K, V> {
2054 /// Creates an empty `btree_map::Keys`.
2055 ///
2056 /// ```
2057 /// # use std::collections::btree_map;
2058 /// let iter: btree_map::Keys<'_, u8, u8> = Default::default();
2059 /// assert_eq!(iter.len(), 0);
2060 /// ```
2061 fn default() -> Self {
2062 Keys { inner: Default::default() }
2063 }
2064}
2065
2066#[stable(feature = "rust1", since = "1.0.0")]
2067impl<'a, K, V> Iterator for Values<'a, K, V> {
2068 type Item = &'a V;
2069
2070 fn next(&mut self) -> Option<&'a V> {
2071 self.inner.next().map(|(_, v)| v)
2072 }
2073
2074 fn size_hint(&self) -> (usize, Option<usize>) {
2075 self.inner.size_hint()
2076 }
2077
2078 fn last(mut self) -> Option<&'a V> {
2079 self.next_back()
2080 }
2081}
2082
2083#[stable(feature = "rust1", since = "1.0.0")]
2084impl<'a, K, V> DoubleEndedIterator for Values<'a, K, V> {
2085 fn next_back(&mut self) -> Option<&'a V> {
2086 self.inner.next_back().map(|(_, v)| v)
2087 }
2088}
2089
2090#[stable(feature = "rust1", since = "1.0.0")]
2091impl<K, V> ExactSizeIterator for Values<'_, K, V> {
2092 fn len(&self) -> usize {
2093 self.inner.len()
2094 }
2095}
2096
2097#[unstable(feature = "trusted_len", issue = "37572")]
2098unsafe impl<K, V> TrustedLen for Values<'_, K, V> {}
2099
2100#[stable(feature = "fused", since = "1.26.0")]
2101impl<K, V> FusedIterator for Values<'_, K, V> {}
2102
2103#[stable(feature = "rust1", since = "1.0.0")]
2104impl<K, V> Clone for Values<'_, K, V> {
2105 fn clone(&self) -> Self {
2106 Values { inner: self.inner.clone() }
2107 }
2108}
2109
2110#[stable(feature = "default_iters", since = "1.70.0")]
2111impl<K, V> Default for Values<'_, K, V> {
2112 /// Creates an empty `btree_map::Values`.
2113 ///
2114 /// ```
2115 /// # use std::collections::btree_map;
2116 /// let iter: btree_map::Values<'_, u8, u8> = Default::default();
2117 /// assert_eq!(iter.len(), 0);
2118 /// ```
2119 fn default() -> Self {
2120 Values { inner: Default::default() }
2121 }
2122}
2123
2124/// This `struct` is created by the [`extract_if`] method on [`BTreeMap`].
2125///
2126/// [`extract_if`]: BTreeMap::extract_if
2127#[stable(feature = "btree_extract_if", since = "1.91.0")]
2128#[must_use = "iterators are lazy and do nothing unless consumed; \
2129 use `retain` or `extract_if().for_each(drop)` to remove and discard elements"]
2130pub struct ExtractIf<
2131 'a,
2132 K,
2133 V,
2134 R,
2135 F,
2136 #[unstable(feature = "allocator_api", issue = "32838")] A: AllocatorClone = Global,
2137> {
2138 pred: F,
2139 inner: ExtractIfInner<'a, K, V, R>,
2140 /// The BTreeMap will outlive this IntoIter so we don't care about drop order for `alloc`.
2141 alloc: A,
2142}
2143
2144/// Most of the implementation of ExtractIf are generic over the type
2145/// of the predicate, thus also serving for BTreeSet::ExtractIf.
2146pub(super) struct ExtractIfInner<'a, K, V, R> {
2147 /// Reference to the length field in the borrowed map, updated live.
2148 length: &'a mut usize,
2149 /// Buried reference to the root field in the borrowed map.
2150 /// Wrapped in `Option` to allow drop handler to `take` it.
2151 dormant_root: Option<DormantMutRef<'a, Root<K, V>>>,
2152 /// Contains a leaf edge preceding the next element to be returned, or the last leaf edge.
2153 /// Empty if the map has no root, if iteration went beyond the last leaf edge,
2154 /// or if a panic occurred in the predicate.
2155 cur_leaf_edge: Option<Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge>>,
2156 /// Range over which iteration was requested. We don't need the left side, but we
2157 /// can't extract the right side without requiring K: Clone.
2158 range: R,
2159}
2160
2161#[stable(feature = "btree_extract_if", since = "1.91.0")]
2162impl<K, V, R, F, A> fmt::Debug for ExtractIf<'_, K, V, R, F, A>
2163where
2164 K: fmt::Debug,
2165 V: fmt::Debug,
2166 A: AllocatorClone,
2167{
2168 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2169 f.debug_struct("ExtractIf").field("peek", &self.inner.peek()).finish_non_exhaustive()
2170 }
2171}
2172
2173#[stable(feature = "btree_extract_if", since = "1.91.0")]
2174impl<K, V, R, F, A: AllocatorClone> Iterator for ExtractIf<'_, K, V, R, F, A>
2175where
2176 K: PartialOrd,
2177 R: RangeBounds<K>,
2178 F: FnMut(&K, &mut V) -> bool,
2179{
2180 type Item = (K, V);
2181
2182 fn next(&mut self) -> Option<(K, V)> {
2183 self.inner.next(&mut self.pred, self.alloc.clone())
2184 }
2185
2186 fn size_hint(&self) -> (usize, Option<usize>) {
2187 self.inner.size_hint()
2188 }
2189}
2190
2191impl<'a, K, V, R> ExtractIfInner<'a, K, V, R> {
2192 /// Allow Debug implementations to predict the next element.
2193 pub(super) fn peek(&self) -> Option<(&K, &V)> {
2194 let edge = self.cur_leaf_edge.as_ref()?;
2195 edge.reborrow().next_kv().ok().map(Handle::into_kv)
2196 }
2197
2198 /// Implementation of a typical `ExtractIf::next` method, given the predicate.
2199 pub(super) fn next<F, A: AllocatorClone>(&mut self, pred: &mut F, alloc: A) -> Option<(K, V)>
2200 where
2201 K: PartialOrd,
2202 R: RangeBounds<K>,
2203 F: FnMut(&K, &mut V) -> bool,
2204 {
2205 while let Ok(mut kv) = self.cur_leaf_edge.take()?.next_kv() {
2206 let (k, v) = kv.kv_mut();
2207
2208 // On creation, we navigated directly to the left bound, so we need only check the
2209 // right bound here to decide whether to stop.
2210 match self.range.end_bound() {
2211 Bound::Included(end) if (*k).le(end) => (),
2212 Bound::Excluded(end) if (*k).lt(end) => (),
2213 Bound::Unbounded => (),
2214 _ => return None,
2215 }
2216
2217 if pred(k, v) {
2218 *self.length -= 1;
2219 let (kv, pos) = kv.remove_kv_tracking(
2220 || {
2221 // SAFETY: we will touch the root in a way that will not
2222 // invalidate the position returned.
2223 let root = unsafe { self.dormant_root.take().unwrap().awaken() };
2224 root.pop_internal_level(alloc.clone());
2225 self.dormant_root = Some(DormantMutRef::new(root).1);
2226 },
2227 alloc.clone(),
2228 );
2229 self.cur_leaf_edge = Some(pos);
2230 return Some(kv);
2231 }
2232 self.cur_leaf_edge = Some(kv.next_leaf_edge());
2233 }
2234 None
2235 }
2236
2237 /// Implementation of a typical `ExtractIf::size_hint` method.
2238 pub(super) fn size_hint(&self) -> (usize, Option<usize>) {
2239 // In most of the btree iterators, `self.length` is the number of elements
2240 // yet to be visited. Here, it includes elements that were visited and that
2241 // the predicate decided not to drain. Making this upper bound more tight
2242 // during iteration would require an extra field.
2243 (0, Some(*self.length))
2244 }
2245}
2246
2247#[stable(feature = "btree_extract_if", since = "1.91.0")]
2248impl<K, V, R, F> FusedIterator for ExtractIf<'_, K, V, R, F>
2249where
2250 K: PartialOrd,
2251 R: RangeBounds<K>,
2252 F: FnMut(&K, &mut V) -> bool,
2253{
2254}
2255
2256#[stable(feature = "btree_range", since = "1.17.0")]
2257impl<'a, K, V> Iterator for Range<'a, K, V> {
2258 type Item = (&'a K, &'a V);
2259
2260 fn next(&mut self) -> Option<(&'a K, &'a V)> {
2261 self.inner.next_checked()
2262 }
2263
2264 fn last(mut self) -> Option<(&'a K, &'a V)> {
2265 self.next_back()
2266 }
2267
2268 fn min(mut self) -> Option<(&'a K, &'a V)>
2269 where
2270 (&'a K, &'a V): Ord,
2271 {
2272 self.next()
2273 }
2274
2275 fn max(mut self) -> Option<(&'a K, &'a V)>
2276 where
2277 (&'a K, &'a V): Ord,
2278 {
2279 self.next_back()
2280 }
2281}
2282
2283#[stable(feature = "default_iters", since = "1.70.0")]
2284impl<K, V> Default for Range<'_, K, V> {
2285 /// Creates an empty `btree_map::Range`.
2286 ///
2287 /// ```
2288 /// # use std::collections::btree_map;
2289 /// let iter: btree_map::Range<'_, u8, u8> = Default::default();
2290 /// assert_eq!(iter.count(), 0);
2291 /// ```
2292 fn default() -> Self {
2293 Range { inner: Default::default() }
2294 }
2295}
2296
2297#[stable(feature = "default_iters_sequel", since = "1.82.0")]
2298impl<K, V> Default for RangeMut<'_, K, V> {
2299 /// Creates an empty `btree_map::RangeMut`.
2300 ///
2301 /// ```
2302 /// # use std::collections::btree_map;
2303 /// let iter: btree_map::RangeMut<'_, u8, u8> = Default::default();
2304 /// assert_eq!(iter.count(), 0);
2305 /// ```
2306 fn default() -> Self {
2307 RangeMut { inner: Default::default(), _marker: PhantomData }
2308 }
2309}
2310
2311#[stable(feature = "map_values_mut", since = "1.10.0")]
2312impl<'a, K, V> Iterator for ValuesMut<'a, K, V> {
2313 type Item = &'a mut V;
2314
2315 fn next(&mut self) -> Option<&'a mut V> {
2316 self.inner.next().map(|(_, v)| v)
2317 }
2318
2319 fn size_hint(&self) -> (usize, Option<usize>) {
2320 self.inner.size_hint()
2321 }
2322
2323 fn last(mut self) -> Option<&'a mut V> {
2324 self.next_back()
2325 }
2326}
2327
2328#[stable(feature = "map_values_mut", since = "1.10.0")]
2329impl<'a, K, V> DoubleEndedIterator for ValuesMut<'a, K, V> {
2330 fn next_back(&mut self) -> Option<&'a mut V> {
2331 self.inner.next_back().map(|(_, v)| v)
2332 }
2333}
2334
2335#[stable(feature = "map_values_mut", since = "1.10.0")]
2336impl<K, V> ExactSizeIterator for ValuesMut<'_, K, V> {
2337 fn len(&self) -> usize {
2338 self.inner.len()
2339 }
2340}
2341
2342#[unstable(feature = "trusted_len", issue = "37572")]
2343unsafe impl<K, V> TrustedLen for ValuesMut<'_, K, V> {}
2344
2345#[stable(feature = "fused", since = "1.26.0")]
2346impl<K, V> FusedIterator for ValuesMut<'_, K, V> {}
2347
2348#[stable(feature = "default_iters_sequel", since = "1.82.0")]
2349impl<K, V> Default for ValuesMut<'_, K, V> {
2350 /// Creates an empty `btree_map::ValuesMut`.
2351 ///
2352 /// ```
2353 /// # use std::collections::btree_map;
2354 /// let iter: btree_map::ValuesMut<'_, u8, u8> = Default::default();
2355 /// assert_eq!(iter.count(), 0);
2356 /// ```
2357 fn default() -> Self {
2358 ValuesMut { inner: Default::default() }
2359 }
2360}
2361
2362#[stable(feature = "map_into_keys_values", since = "1.54.0")]
2363impl<K, V, A: AllocatorClone> Iterator for IntoKeys<K, V, A> {
2364 type Item = K;
2365
2366 fn next(&mut self) -> Option<K> {
2367 self.inner.next().map(|(k, _)| k)
2368 }
2369
2370 fn size_hint(&self) -> (usize, Option<usize>) {
2371 self.inner.size_hint()
2372 }
2373
2374 fn last(mut self) -> Option<K> {
2375 self.next_back()
2376 }
2377
2378 fn min(mut self) -> Option<K>
2379 where
2380 K: Ord,
2381 {
2382 self.next()
2383 }
2384
2385 fn max(mut self) -> Option<K>
2386 where
2387 K: Ord,
2388 {
2389 self.next_back()
2390 }
2391}
2392
2393#[stable(feature = "map_into_keys_values", since = "1.54.0")]
2394impl<K, V, A: AllocatorClone> DoubleEndedIterator for IntoKeys<K, V, A> {
2395 fn next_back(&mut self) -> Option<K> {
2396 self.inner.next_back().map(|(k, _)| k)
2397 }
2398}
2399
2400#[stable(feature = "map_into_keys_values", since = "1.54.0")]
2401impl<K, V, A: AllocatorClone> ExactSizeIterator for IntoKeys<K, V, A> {
2402 fn len(&self) -> usize {
2403 self.inner.len()
2404 }
2405}
2406
2407#[unstable(feature = "trusted_len", issue = "37572")]
2408unsafe impl<K, V, A: AllocatorClone> TrustedLen for IntoKeys<K, V, A> {}
2409
2410#[stable(feature = "map_into_keys_values", since = "1.54.0")]
2411impl<K, V, A: AllocatorClone> FusedIterator for IntoKeys<K, V, A> {}
2412
2413#[stable(feature = "default_iters", since = "1.70.0")]
2414impl<K, V, A> Default for IntoKeys<K, V, A>
2415where
2416 A: AllocatorClone + Default,
2417{
2418 /// Creates an empty `btree_map::IntoKeys`.
2419 ///
2420 /// ```
2421 /// # use std::collections::btree_map;
2422 /// let iter: btree_map::IntoKeys<u8, u8> = Default::default();
2423 /// assert_eq!(iter.len(), 0);
2424 /// ```
2425 fn default() -> Self {
2426 IntoKeys { inner: Default::default() }
2427 }
2428}
2429
2430#[stable(feature = "map_into_keys_values", since = "1.54.0")]
2431impl<K, V, A: AllocatorClone> Iterator for IntoValues<K, V, A> {
2432 type Item = V;
2433
2434 fn next(&mut self) -> Option<V> {
2435 self.inner.next().map(|(_, v)| v)
2436 }
2437
2438 fn size_hint(&self) -> (usize, Option<usize>) {
2439 self.inner.size_hint()
2440 }
2441
2442 fn last(mut self) -> Option<V> {
2443 self.next_back()
2444 }
2445}
2446
2447#[stable(feature = "map_into_keys_values", since = "1.54.0")]
2448impl<K, V, A: AllocatorClone> DoubleEndedIterator for IntoValues<K, V, A> {
2449 fn next_back(&mut self) -> Option<V> {
2450 self.inner.next_back().map(|(_, v)| v)
2451 }
2452}
2453
2454#[stable(feature = "map_into_keys_values", since = "1.54.0")]
2455impl<K, V, A: AllocatorClone> ExactSizeIterator for IntoValues<K, V, A> {
2456 fn len(&self) -> usize {
2457 self.inner.len()
2458 }
2459}
2460
2461#[unstable(feature = "trusted_len", issue = "37572")]
2462unsafe impl<K, V, A: AllocatorClone> TrustedLen for IntoValues<K, V, A> {}
2463
2464#[stable(feature = "map_into_keys_values", since = "1.54.0")]
2465impl<K, V, A: AllocatorClone> FusedIterator for IntoValues<K, V, A> {}
2466
2467#[stable(feature = "default_iters", since = "1.70.0")]
2468impl<K, V, A> Default for IntoValues<K, V, A>
2469where
2470 A: AllocatorClone + Default,
2471{
2472 /// Creates an empty `btree_map::IntoValues`.
2473 ///
2474 /// ```
2475 /// # use std::collections::btree_map;
2476 /// let iter: btree_map::IntoValues<u8, u8> = Default::default();
2477 /// assert_eq!(iter.len(), 0);
2478 /// ```
2479 fn default() -> Self {
2480 IntoValues { inner: Default::default() }
2481 }
2482}
2483
2484#[stable(feature = "btree_range", since = "1.17.0")]
2485impl<'a, K, V> DoubleEndedIterator for Range<'a, K, V> {
2486 fn next_back(&mut self) -> Option<(&'a K, &'a V)> {
2487 self.inner.next_back_checked()
2488 }
2489}
2490
2491#[stable(feature = "fused", since = "1.26.0")]
2492impl<K, V> FusedIterator for Range<'_, K, V> {}
2493
2494#[stable(feature = "btree_range", since = "1.17.0")]
2495impl<K, V> Clone for Range<'_, K, V> {
2496 fn clone(&self) -> Self {
2497 Range { inner: self.inner.clone() }
2498 }
2499}
2500
2501#[stable(feature = "btree_range", since = "1.17.0")]
2502impl<'a, K, V> Iterator for RangeMut<'a, K, V> {
2503 type Item = (&'a K, &'a mut V);
2504
2505 fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
2506 self.inner.next_checked()
2507 }
2508
2509 fn last(mut self) -> Option<(&'a K, &'a mut V)> {
2510 self.next_back()
2511 }
2512
2513 fn min(mut self) -> Option<(&'a K, &'a mut V)>
2514 where
2515 (&'a K, &'a mut V): Ord,
2516 {
2517 self.next()
2518 }
2519
2520 fn max(mut self) -> Option<(&'a K, &'a mut V)>
2521 where
2522 (&'a K, &'a mut V): Ord,
2523 {
2524 self.next_back()
2525 }
2526}
2527
2528#[stable(feature = "btree_range", since = "1.17.0")]
2529impl<'a, K, V> DoubleEndedIterator for RangeMut<'a, K, V> {
2530 fn next_back(&mut self) -> Option<(&'a K, &'a mut V)> {
2531 self.inner.next_back_checked()
2532 }
2533}
2534
2535#[stable(feature = "fused", since = "1.26.0")]
2536impl<K, V> FusedIterator for RangeMut<'_, K, V> {}
2537
2538#[stable(feature = "rust1", since = "1.0.0")]
2539impl<K: Ord, V> FromIterator<(K, V)> for BTreeMap<K, V> {
2540 /// Constructs a `BTreeMap<K, V>` from an iterator of key-value pairs.
2541 ///
2542 /// If the iterator produces any pairs with equal keys,
2543 /// all but one of the corresponding values will be dropped.
2544 fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> BTreeMap<K, V> {
2545 let mut inputs: Vec<_> = iter.into_iter().collect();
2546
2547 if inputs.is_empty() {
2548 return BTreeMap::new();
2549 }
2550
2551 // use stable sort to preserve the insertion order.
2552 inputs.sort_by(|a, b| a.0.cmp(&b.0));
2553 BTreeMap::bulk_build_from_sorted_iter(inputs, Global)
2554 }
2555}
2556
2557#[stable(feature = "rust1", since = "1.0.0")]
2558impl<K: Ord, V, A: AllocatorClone> Extend<(K, V)> for BTreeMap<K, V, A> {
2559 #[inline]
2560 fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) {
2561 iter.into_iter().for_each(move |(k, v)| {
2562 self.insert(k, v);
2563 });
2564 }
2565
2566 #[inline]
2567 fn extend_one(&mut self, (k, v): (K, V)) {
2568 self.insert(k, v);
2569 }
2570}
2571
2572#[stable(feature = "extend_ref", since = "1.2.0")]
2573impl<'a, K: Ord + Copy, V: Copy, A: AllocatorClone> Extend<(&'a K, &'a V)> for BTreeMap<K, V, A> {
2574 fn extend<I: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: I) {
2575 self.extend(iter.into_iter().map(|(&key, &value)| (key, value)));
2576 }
2577
2578 #[inline]
2579 fn extend_one(&mut self, (&k, &v): (&'a K, &'a V)) {
2580 self.insert(k, v);
2581 }
2582}
2583
2584#[stable(feature = "rust1", since = "1.0.0")]
2585impl<K: Hash, V: Hash, A: AllocatorClone> Hash for BTreeMap<K, V, A> {
2586 fn hash<H: Hasher>(&self, state: &mut H) {
2587 state.write_length_prefix(self.len());
2588 for elt in self {
2589 elt.hash(state);
2590 }
2591 }
2592}
2593
2594#[stable(feature = "rust1", since = "1.0.0")]
2595#[rustc_const_unstable(feature = "const_default", issue = "143894")]
2596const impl<K, V> Default for BTreeMap<K, V> {
2597 /// Creates an empty `BTreeMap`.
2598 fn default() -> BTreeMap<K, V> {
2599 BTreeMap::new()
2600 }
2601}
2602
2603#[stable(feature = "rust1", since = "1.0.0")]
2604impl<K: PartialEq, V: PartialEq, A: AllocatorClone> PartialEq for BTreeMap<K, V, A> {
2605 fn eq(&self, other: &BTreeMap<K, V, A>) -> bool {
2606 self.len() == other.len() && self.iter().zip(other).all(|(a, b)| a == b)
2607 }
2608}
2609
2610#[stable(feature = "rust1", since = "1.0.0")]
2611impl<K: Eq, V: Eq, A: AllocatorClone> Eq for BTreeMap<K, V, A> {}
2612
2613#[stable(feature = "rust1", since = "1.0.0")]
2614impl<K: PartialOrd, V: PartialOrd, A: AllocatorClone> PartialOrd for BTreeMap<K, V, A> {
2615 #[inline]
2616 fn partial_cmp(&self, other: &BTreeMap<K, V, A>) -> Option<Ordering> {
2617 self.iter().partial_cmp(other.iter())
2618 }
2619}
2620
2621#[stable(feature = "rust1", since = "1.0.0")]
2622impl<K: Ord, V: Ord, A: AllocatorClone> Ord for BTreeMap<K, V, A> {
2623 #[inline]
2624 fn cmp(&self, other: &BTreeMap<K, V, A>) -> Ordering {
2625 self.iter().cmp(other.iter())
2626 }
2627}
2628
2629#[stable(feature = "rust1", since = "1.0.0")]
2630impl<K: Debug, V: Debug, A: AllocatorClone> Debug for BTreeMap<K, V, A> {
2631 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2632 f.debug_map().entries(self.iter()).finish()
2633 }
2634}
2635
2636#[stable(feature = "rust1", since = "1.0.0")]
2637impl<K, Q: ?Sized, V, A: AllocatorClone> Index<&Q> for BTreeMap<K, V, A>
2638where
2639 K: Borrow<Q> + Ord,
2640 Q: Ord,
2641{
2642 type Output = V;
2643
2644 /// Returns a reference to the value corresponding to the supplied key.
2645 ///
2646 /// # Panics
2647 ///
2648 /// Panics if the key is not present in the `BTreeMap`.
2649 #[inline]
2650 fn index(&self, key: &Q) -> &V {
2651 self.get(key).expect("no entry found for key")
2652 }
2653}
2654
2655#[stable(feature = "std_collections_from_array", since = "1.56.0")]
2656impl<K: Ord, V, const N: usize> From<[(K, V); N]> for BTreeMap<K, V> {
2657 /// Converts a `[(K, V); N]` into a `BTreeMap<K, V>`.
2658 ///
2659 /// If any entries in the array have equal keys,
2660 /// all but one of the corresponding values will be dropped.
2661 ///
2662 /// ```
2663 /// use std::collections::BTreeMap;
2664 ///
2665 /// let map1 = BTreeMap::from([(1, 2), (3, 4)]);
2666 /// let map2: BTreeMap<_, _> = [(1, 2), (3, 4)].into();
2667 /// assert_eq!(map1, map2);
2668 /// ```
2669 fn from(mut arr: [(K, V); N]) -> Self {
2670 if N == 0 {
2671 return BTreeMap::new();
2672 }
2673
2674 // use stable sort to preserve the insertion order.
2675 arr.sort_by(|a, b| a.0.cmp(&b.0));
2676 BTreeMap::bulk_build_from_sorted_iter(arr, Global)
2677 }
2678}
2679
2680impl<K, V, A: AllocatorClone> BTreeMap<K, V, A> {
2681 /// Gets an iterator over the entries of the map, sorted by key.
2682 ///
2683 /// # Examples
2684 ///
2685 /// ```
2686 /// use std::collections::BTreeMap;
2687 ///
2688 /// let mut map = BTreeMap::new();
2689 /// map.insert(3, "c");
2690 /// map.insert(2, "b");
2691 /// map.insert(1, "a");
2692 ///
2693 /// for (key, value) in map.iter() {
2694 /// println!("{key}: {value}");
2695 /// }
2696 ///
2697 /// let (first_key, first_value) = map.iter().next().unwrap();
2698 /// assert_eq!((*first_key, *first_value), (1, "a"));
2699 /// ```
2700 #[stable(feature = "rust1", since = "1.0.0")]
2701 pub fn iter(&self) -> Iter<'_, K, V> {
2702 if let Some(root) = &self.root {
2703 let full_range = root.reborrow().full_range();
2704
2705 Iter { range: full_range, length: self.length }
2706 } else {
2707 Iter { range: LazyLeafRange::none(), length: 0 }
2708 }
2709 }
2710
2711 /// Gets a mutable iterator over the entries of the map, sorted by key.
2712 ///
2713 /// # Examples
2714 ///
2715 /// ```
2716 /// use std::collections::BTreeMap;
2717 ///
2718 /// let mut map = BTreeMap::from([
2719 /// ("a", 1),
2720 /// ("b", 2),
2721 /// ("c", 3),
2722 /// ]);
2723 ///
2724 /// // add 10 to the value if the key isn't "a"
2725 /// for (key, value) in map.iter_mut() {
2726 /// if key != &"a" {
2727 /// *value += 10;
2728 /// }
2729 /// }
2730 /// ```
2731 #[stable(feature = "rust1", since = "1.0.0")]
2732 pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {
2733 if let Some(root) = &mut self.root {
2734 let full_range = root.borrow_valmut().full_range();
2735
2736 IterMut { range: full_range, length: self.length, _marker: PhantomData }
2737 } else {
2738 IterMut { range: LazyLeafRange::none(), length: 0, _marker: PhantomData }
2739 }
2740 }
2741
2742 /// Gets an iterator over the keys of the map, in sorted order.
2743 ///
2744 /// # Examples
2745 ///
2746 /// ```
2747 /// use std::collections::BTreeMap;
2748 ///
2749 /// let mut a = BTreeMap::new();
2750 /// a.insert(2, "b");
2751 /// a.insert(1, "a");
2752 ///
2753 /// let keys: Vec<_> = a.keys().cloned().collect();
2754 /// assert_eq!(keys, [1, 2]);
2755 /// ```
2756 #[stable(feature = "rust1", since = "1.0.0")]
2757 pub fn keys(&self) -> Keys<'_, K, V> {
2758 Keys { inner: self.iter() }
2759 }
2760
2761 /// Gets an iterator over the values of the map, in order by key.
2762 ///
2763 /// # Examples
2764 ///
2765 /// ```
2766 /// use std::collections::BTreeMap;
2767 ///
2768 /// let mut a = BTreeMap::new();
2769 /// a.insert(1, "hello");
2770 /// a.insert(2, "goodbye");
2771 ///
2772 /// let values: Vec<&str> = a.values().cloned().collect();
2773 /// assert_eq!(values, ["hello", "goodbye"]);
2774 /// ```
2775 #[stable(feature = "rust1", since = "1.0.0")]
2776 pub fn values(&self) -> Values<'_, K, V> {
2777 Values { inner: self.iter() }
2778 }
2779
2780 /// Gets a mutable iterator over the values of the map, in order by key.
2781 ///
2782 /// # Examples
2783 ///
2784 /// ```
2785 /// use std::collections::BTreeMap;
2786 ///
2787 /// let mut a = BTreeMap::new();
2788 /// a.insert(1, String::from("hello"));
2789 /// a.insert(2, String::from("goodbye"));
2790 ///
2791 /// for value in a.values_mut() {
2792 /// value.push_str("!");
2793 /// }
2794 ///
2795 /// let values: Vec<String> = a.values().cloned().collect();
2796 /// assert_eq!(values, [String::from("hello!"),
2797 /// String::from("goodbye!")]);
2798 /// ```
2799 #[stable(feature = "map_values_mut", since = "1.10.0")]
2800 pub fn values_mut(&mut self) -> ValuesMut<'_, K, V> {
2801 ValuesMut { inner: self.iter_mut() }
2802 }
2803
2804 /// Returns the number of elements in the map.
2805 ///
2806 /// # Examples
2807 ///
2808 /// ```
2809 /// use std::collections::BTreeMap;
2810 ///
2811 /// let mut a = BTreeMap::new();
2812 /// assert_eq!(a.len(), 0);
2813 /// a.insert(1, "a");
2814 /// assert_eq!(a.len(), 1);
2815 /// ```
2816 #[must_use]
2817 #[stable(feature = "rust1", since = "1.0.0")]
2818 #[rustc_const_unstable(
2819 feature = "const_btree_len",
2820 issue = "71835",
2821 implied_by = "const_btree_new"
2822 )]
2823 #[rustc_confusables("length", "size")]
2824 pub const fn len(&self) -> usize {
2825 self.length
2826 }
2827
2828 /// Returns `true` if the map contains no elements.
2829 ///
2830 /// # Examples
2831 ///
2832 /// ```
2833 /// use std::collections::BTreeMap;
2834 ///
2835 /// let mut a = BTreeMap::new();
2836 /// assert!(a.is_empty());
2837 /// a.insert(1, "a");
2838 /// assert!(!a.is_empty());
2839 /// ```
2840 #[must_use]
2841 #[stable(feature = "rust1", since = "1.0.0")]
2842 #[rustc_const_unstable(
2843 feature = "const_btree_len",
2844 issue = "71835",
2845 implied_by = "const_btree_new"
2846 )]
2847 pub const fn is_empty(&self) -> bool {
2848 self.len() == 0
2849 }
2850
2851 /// Returns a [`Cursor`] pointing at the gap before the smallest key
2852 /// greater than the given bound.
2853 ///
2854 /// Passing `Bound::Included(x)` will return a cursor pointing to the
2855 /// gap before the smallest key greater than or equal to `x`.
2856 ///
2857 /// Passing `Bound::Excluded(x)` will return a cursor pointing to the
2858 /// gap before the smallest key greater than `x`.
2859 ///
2860 /// Passing `Bound::Unbounded` will return a cursor pointing to the
2861 /// gap before the smallest key in the map.
2862 ///
2863 /// # Examples
2864 ///
2865 /// ```
2866 /// #![feature(btree_cursors)]
2867 ///
2868 /// use std::collections::BTreeMap;
2869 /// use std::ops::Bound;
2870 ///
2871 /// let map = BTreeMap::from([
2872 /// (1, "a"),
2873 /// (2, "b"),
2874 /// (3, "c"),
2875 /// (4, "d"),
2876 /// ]);
2877 ///
2878 /// let cursor = map.lower_bound(Bound::Included(&2));
2879 /// assert_eq!(cursor.peek_prev(), Some((&1, &"a")));
2880 /// assert_eq!(cursor.peek_next(), Some((&2, &"b")));
2881 ///
2882 /// let cursor = map.lower_bound(Bound::Excluded(&2));
2883 /// assert_eq!(cursor.peek_prev(), Some((&2, &"b")));
2884 /// assert_eq!(cursor.peek_next(), Some((&3, &"c")));
2885 ///
2886 /// let cursor = map.lower_bound(Bound::Unbounded);
2887 /// assert_eq!(cursor.peek_prev(), None);
2888 /// assert_eq!(cursor.peek_next(), Some((&1, &"a")));
2889 /// ```
2890 #[unstable(feature = "btree_cursors", issue = "107540")]
2891 pub fn lower_bound<Q: ?Sized>(&self, bound: Bound<&Q>) -> Cursor<'_, K, V>
2892 where
2893 K: Borrow<Q> + Ord,
2894 Q: Ord,
2895 {
2896 let root_node = match self.root.as_ref() {
2897 None => return Cursor { current: None, root: None },
2898 Some(root) => root.reborrow(),
2899 };
2900 let edge = root_node.lower_bound(SearchBound::from_range(bound));
2901 Cursor { current: Some(edge), root: self.root.as_ref() }
2902 }
2903
2904 /// Returns a [`CursorMut`] pointing at the gap before the smallest key
2905 /// greater than the given bound.
2906 ///
2907 /// Passing `Bound::Included(x)` will return a cursor pointing to the
2908 /// gap before the smallest key greater than or equal to `x`.
2909 ///
2910 /// Passing `Bound::Excluded(x)` will return a cursor pointing to the
2911 /// gap before the smallest key greater than `x`.
2912 ///
2913 /// Passing `Bound::Unbounded` will return a cursor pointing to the
2914 /// gap before the smallest key in the map.
2915 ///
2916 /// # Examples
2917 ///
2918 /// ```
2919 /// #![feature(btree_cursors)]
2920 ///
2921 /// use std::collections::BTreeMap;
2922 /// use std::ops::Bound;
2923 ///
2924 /// let mut map = BTreeMap::from([
2925 /// (1, "a"),
2926 /// (2, "b"),
2927 /// (3, "c"),
2928 /// (4, "d"),
2929 /// ]);
2930 ///
2931 /// let mut cursor = map.lower_bound_mut(Bound::Included(&2));
2932 /// assert_eq!(cursor.peek_prev(), Some((&1, &mut "a")));
2933 /// assert_eq!(cursor.peek_next(), Some((&2, &mut "b")));
2934 ///
2935 /// let mut cursor = map.lower_bound_mut(Bound::Excluded(&2));
2936 /// assert_eq!(cursor.peek_prev(), Some((&2, &mut "b")));
2937 /// assert_eq!(cursor.peek_next(), Some((&3, &mut "c")));
2938 ///
2939 /// let mut cursor = map.lower_bound_mut(Bound::Unbounded);
2940 /// assert_eq!(cursor.peek_prev(), None);
2941 /// assert_eq!(cursor.peek_next(), Some((&1, &mut "a")));
2942 /// ```
2943 #[unstable(feature = "btree_cursors", issue = "107540")]
2944 pub fn lower_bound_mut<Q: ?Sized>(&mut self, bound: Bound<&Q>) -> CursorMut<'_, K, V, A>
2945 where
2946 K: Borrow<Q> + Ord,
2947 Q: Ord,
2948 {
2949 let (root, dormant_root) = DormantMutRef::new(&mut self.root);
2950 let root_node = match root.as_mut() {
2951 None => {
2952 return CursorMut {
2953 inner: CursorMutKey {
2954 current: None,
2955 root: dormant_root,
2956 length: &mut self.length,
2957 alloc: &mut *self.alloc,
2958 },
2959 };
2960 }
2961 Some(root) => root.borrow_mut(),
2962 };
2963 let edge = root_node.lower_bound(SearchBound::from_range(bound));
2964 CursorMut {
2965 inner: CursorMutKey {
2966 current: Some(edge),
2967 root: dormant_root,
2968 length: &mut self.length,
2969 alloc: &mut *self.alloc,
2970 },
2971 }
2972 }
2973
2974 /// Returns a [`Cursor`] pointing at the gap after the greatest key
2975 /// smaller than the given bound.
2976 ///
2977 /// Passing `Bound::Included(x)` will return a cursor pointing to the
2978 /// gap after the greatest key smaller than or equal to `x`.
2979 ///
2980 /// Passing `Bound::Excluded(x)` will return a cursor pointing to the
2981 /// gap after the greatest key smaller than `x`.
2982 ///
2983 /// Passing `Bound::Unbounded` will return a cursor pointing to the
2984 /// gap after the greatest key in the map.
2985 ///
2986 /// # Examples
2987 ///
2988 /// ```
2989 /// #![feature(btree_cursors)]
2990 ///
2991 /// use std::collections::BTreeMap;
2992 /// use std::ops::Bound;
2993 ///
2994 /// let map = BTreeMap::from([
2995 /// (1, "a"),
2996 /// (2, "b"),
2997 /// (3, "c"),
2998 /// (4, "d"),
2999 /// ]);
3000 ///
3001 /// let cursor = map.upper_bound(Bound::Included(&3));
3002 /// assert_eq!(cursor.peek_prev(), Some((&3, &"c")));
3003 /// assert_eq!(cursor.peek_next(), Some((&4, &"d")));
3004 ///
3005 /// let cursor = map.upper_bound(Bound::Excluded(&3));
3006 /// assert_eq!(cursor.peek_prev(), Some((&2, &"b")));
3007 /// assert_eq!(cursor.peek_next(), Some((&3, &"c")));
3008 ///
3009 /// let cursor = map.upper_bound(Bound::Unbounded);
3010 /// assert_eq!(cursor.peek_prev(), Some((&4, &"d")));
3011 /// assert_eq!(cursor.peek_next(), None);
3012 /// ```
3013 #[unstable(feature = "btree_cursors", issue = "107540")]
3014 pub fn upper_bound<Q: ?Sized>(&self, bound: Bound<&Q>) -> Cursor<'_, K, V>
3015 where
3016 K: Borrow<Q> + Ord,
3017 Q: Ord,
3018 {
3019 let root_node = match self.root.as_ref() {
3020 None => return Cursor { current: None, root: None },
3021 Some(root) => root.reborrow(),
3022 };
3023 let edge = root_node.upper_bound(SearchBound::from_range(bound));
3024 Cursor { current: Some(edge), root: self.root.as_ref() }
3025 }
3026
3027 /// Returns a [`CursorMut`] pointing at the gap after the greatest key
3028 /// smaller than the given bound.
3029 ///
3030 /// Passing `Bound::Included(x)` will return a cursor pointing to the
3031 /// gap after the greatest key smaller than or equal to `x`.
3032 ///
3033 /// Passing `Bound::Excluded(x)` will return a cursor pointing to the
3034 /// gap after the greatest key smaller than `x`.
3035 ///
3036 /// Passing `Bound::Unbounded` will return a cursor pointing to the
3037 /// gap after the greatest key in the map.
3038 ///
3039 /// # Examples
3040 ///
3041 /// ```
3042 /// #![feature(btree_cursors)]
3043 ///
3044 /// use std::collections::BTreeMap;
3045 /// use std::ops::Bound;
3046 ///
3047 /// let mut map = BTreeMap::from([
3048 /// (1, "a"),
3049 /// (2, "b"),
3050 /// (3, "c"),
3051 /// (4, "d"),
3052 /// ]);
3053 ///
3054 /// let mut cursor = map.upper_bound_mut(Bound::Included(&3));
3055 /// assert_eq!(cursor.peek_prev(), Some((&3, &mut "c")));
3056 /// assert_eq!(cursor.peek_next(), Some((&4, &mut "d")));
3057 ///
3058 /// let mut cursor = map.upper_bound_mut(Bound::Excluded(&3));
3059 /// assert_eq!(cursor.peek_prev(), Some((&2, &mut "b")));
3060 /// assert_eq!(cursor.peek_next(), Some((&3, &mut "c")));
3061 ///
3062 /// let mut cursor = map.upper_bound_mut(Bound::Unbounded);
3063 /// assert_eq!(cursor.peek_prev(), Some((&4, &mut "d")));
3064 /// assert_eq!(cursor.peek_next(), None);
3065 /// ```
3066 #[unstable(feature = "btree_cursors", issue = "107540")]
3067 pub fn upper_bound_mut<Q: ?Sized>(&mut self, bound: Bound<&Q>) -> CursorMut<'_, K, V, A>
3068 where
3069 K: Borrow<Q> + Ord,
3070 Q: Ord,
3071 {
3072 let (root, dormant_root) = DormantMutRef::new(&mut self.root);
3073 let root_node = match root.as_mut() {
3074 None => {
3075 return CursorMut {
3076 inner: CursorMutKey {
3077 current: None,
3078 root: dormant_root,
3079 length: &mut self.length,
3080 alloc: &mut *self.alloc,
3081 },
3082 };
3083 }
3084 Some(root) => root.borrow_mut(),
3085 };
3086 let edge = root_node.upper_bound(SearchBound::from_range(bound));
3087 CursorMut {
3088 inner: CursorMutKey {
3089 current: Some(edge),
3090 root: dormant_root,
3091 length: &mut self.length,
3092 alloc: &mut *self.alloc,
3093 },
3094 }
3095 }
3096}
3097
3098/// A cursor over a `BTreeMap`.
3099///
3100/// A `Cursor` is like an iterator, except that it can freely seek back-and-forth.
3101///
3102/// Cursors always point to a gap between two elements in the map, and can
3103/// operate on the two immediately adjacent elements.
3104///
3105/// A `Cursor` is created with the [`BTreeMap::lower_bound`] and [`BTreeMap::upper_bound`] methods.
3106#[unstable(feature = "btree_cursors", issue = "107540")]
3107pub struct Cursor<'a, K: 'a, V: 'a> {
3108 // If current is None then it means the tree has not been allocated yet.
3109 current: Option<Handle<NodeRef<marker::Immut<'a>, K, V, marker::Leaf>, marker::Edge>>,
3110 root: Option<&'a node::Root<K, V>>,
3111}
3112
3113#[unstable(feature = "btree_cursors", issue = "107540")]
3114impl<K, V> Clone for Cursor<'_, K, V> {
3115 fn clone(&self) -> Self {
3116 let Cursor { current, root } = *self;
3117 Cursor { current, root }
3118 }
3119}
3120
3121#[unstable(feature = "btree_cursors", issue = "107540")]
3122impl<K: Debug, V: Debug> Debug for Cursor<'_, K, V> {
3123 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3124 f.write_str("Cursor")
3125 }
3126}
3127
3128/// A cursor over a `BTreeMap` with editing operations.
3129///
3130/// A `Cursor` is like an iterator, except that it can freely seek back-and-forth, and can
3131/// safely mutate the map during iteration. This is because the lifetime of its yielded
3132/// references is tied to its own lifetime, instead of just the underlying map. This means
3133/// cursors cannot yield multiple elements at once.
3134///
3135/// Cursors always point to a gap between two elements in the map, and can
3136/// operate on the two immediately adjacent elements.
3137///
3138/// A `CursorMut` is created with the [`BTreeMap::lower_bound_mut`] and [`BTreeMap::upper_bound_mut`]
3139/// methods.
3140#[unstable(feature = "btree_cursors", issue = "107540")]
3141pub struct CursorMut<
3142 'a,
3143 K: 'a,
3144 V: 'a,
3145 #[unstable(feature = "allocator_api", issue = "32838")] A = Global,
3146> {
3147 inner: CursorMutKey<'a, K, V, A>,
3148}
3149
3150#[unstable(feature = "btree_cursors", issue = "107540")]
3151impl<K: Debug, V: Debug, A> Debug for CursorMut<'_, K, V, A> {
3152 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3153 f.write_str("CursorMut")
3154 }
3155}
3156
3157/// A cursor over a `BTreeMap` with editing operations, and which allows
3158/// mutating the key of elements.
3159///
3160/// A `Cursor` is like an iterator, except that it can freely seek back-and-forth, and can
3161/// safely mutate the map during iteration. This is because the lifetime of its yielded
3162/// references is tied to its own lifetime, instead of just the underlying map. This means
3163/// cursors cannot yield multiple elements at once.
3164///
3165/// Cursors always point to a gap between two elements in the map, and can
3166/// operate on the two immediately adjacent elements.
3167///
3168/// A `CursorMutKey` is created from a [`CursorMut`] with the
3169/// [`CursorMut::with_mutable_key`] method.
3170///
3171/// # Safety
3172///
3173/// Since this cursor allows mutating keys, you must ensure that the `BTreeMap`
3174/// invariants are maintained. Specifically:
3175///
3176/// * The key of the newly inserted element must be unique in the tree.
3177/// * All keys in the tree must remain in sorted order.
3178#[unstable(feature = "btree_cursors", issue = "107540")]
3179pub struct CursorMutKey<
3180 'a,
3181 K: 'a,
3182 V: 'a,
3183 #[unstable(feature = "allocator_api", issue = "32838")] A = Global,
3184> {
3185 // If current is None then it means the tree has not been allocated yet.
3186 current: Option<Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge>>,
3187 root: DormantMutRef<'a, Option<node::Root<K, V>>>,
3188 length: &'a mut usize,
3189 alloc: &'a mut A,
3190}
3191
3192#[unstable(feature = "btree_cursors", issue = "107540")]
3193impl<K: Debug, V: Debug, A> Debug for CursorMutKey<'_, K, V, A> {
3194 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3195 f.write_str("CursorMutKey")
3196 }
3197}
3198
3199impl<'a, K, V> Cursor<'a, K, V> {
3200 /// Advances the cursor to the next gap, returning the key and value of the
3201 /// element that it moved over.
3202 ///
3203 /// If the cursor is already at the end of the map then `None` is returned
3204 /// and the cursor is not moved.
3205 #[unstable(feature = "btree_cursors", issue = "107540")]
3206 pub fn next(&mut self) -> Option<(&'a K, &'a V)> {
3207 let current = self.current.take()?;
3208 match current.next_kv() {
3209 Ok(kv) => {
3210 let result = kv.into_kv();
3211 self.current = Some(kv.next_leaf_edge());
3212 Some(result)
3213 }
3214 Err(root) => {
3215 self.current = Some(root.last_leaf_edge());
3216 None
3217 }
3218 }
3219 }
3220
3221 /// Advances the cursor to the previous gap, returning the key and value of
3222 /// the element that it moved over.
3223 ///
3224 /// If the cursor is already at the start of the map then `None` is returned
3225 /// and the cursor is not moved.
3226 #[unstable(feature = "btree_cursors", issue = "107540")]
3227 pub fn prev(&mut self) -> Option<(&'a K, &'a V)> {
3228 let current = self.current.take()?;
3229 match current.next_back_kv() {
3230 Ok(kv) => {
3231 let result = kv.into_kv();
3232 self.current = Some(kv.next_back_leaf_edge());
3233 Some(result)
3234 }
3235 Err(root) => {
3236 self.current = Some(root.first_leaf_edge());
3237 None
3238 }
3239 }
3240 }
3241
3242 /// Returns a reference to the key and value of the next element without
3243 /// moving the cursor.
3244 ///
3245 /// If the cursor is at the end of the map then `None` is returned.
3246 #[unstable(feature = "btree_cursors", issue = "107540")]
3247 pub fn peek_next(&self) -> Option<(&'a K, &'a V)> {
3248 self.clone().next()
3249 }
3250
3251 /// Returns a reference to the key and value of the previous element
3252 /// without moving the cursor.
3253 ///
3254 /// If the cursor is at the start of the map then `None` is returned.
3255 #[unstable(feature = "btree_cursors", issue = "107540")]
3256 pub fn peek_prev(&self) -> Option<(&'a K, &'a V)> {
3257 self.clone().prev()
3258 }
3259}
3260
3261impl<'a, K, V, A> CursorMut<'a, K, V, A> {
3262 /// Advances the cursor to the next gap, returning the key and value of the
3263 /// element that it moved over.
3264 ///
3265 /// If the cursor is already at the end of the map then `None` is returned
3266 /// and the cursor is not moved.
3267 #[unstable(feature = "btree_cursors", issue = "107540")]
3268 pub fn next(&mut self) -> Option<(&K, &mut V)> {
3269 let (k, v) = self.inner.next()?;
3270 Some((&*k, v))
3271 }
3272
3273 /// Advances the cursor to the previous gap, returning the key and value of
3274 /// the element that it moved over.
3275 ///
3276 /// If the cursor is already at the start of the map then `None` is returned
3277 /// and the cursor is not moved.
3278 #[unstable(feature = "btree_cursors", issue = "107540")]
3279 pub fn prev(&mut self) -> Option<(&K, &mut V)> {
3280 let (k, v) = self.inner.prev()?;
3281 Some((&*k, v))
3282 }
3283
3284 /// Returns a reference to the key and value of the next element without
3285 /// moving the cursor.
3286 ///
3287 /// If the cursor is at the end of the map then `None` is returned.
3288 #[unstable(feature = "btree_cursors", issue = "107540")]
3289 pub fn peek_next(&mut self) -> Option<(&K, &mut V)> {
3290 let (k, v) = self.inner.peek_next()?;
3291 Some((&*k, v))
3292 }
3293
3294 /// Returns a reference to the key and value of the previous element
3295 /// without moving the cursor.
3296 ///
3297 /// If the cursor is at the start of the map then `None` is returned.
3298 #[unstable(feature = "btree_cursors", issue = "107540")]
3299 pub fn peek_prev(&mut self) -> Option<(&K, &mut V)> {
3300 let (k, v) = self.inner.peek_prev()?;
3301 Some((&*k, v))
3302 }
3303
3304 /// Returns a read-only cursor pointing to the same location as the
3305 /// `CursorMut`.
3306 ///
3307 /// The lifetime of the returned `Cursor` is bound to that of the
3308 /// `CursorMut`, which means it cannot outlive the `CursorMut` and that the
3309 /// `CursorMut` is frozen for the lifetime of the `Cursor`.
3310 #[unstable(feature = "btree_cursors", issue = "107540")]
3311 pub fn as_cursor(&self) -> Cursor<'_, K, V> {
3312 self.inner.as_cursor()
3313 }
3314
3315 /// Converts the cursor into a [`CursorMutKey`], which allows mutating
3316 /// the key of elements in the tree.
3317 ///
3318 /// # Safety
3319 ///
3320 /// Since this cursor allows mutating keys, you must ensure that the `BTreeMap`
3321 /// invariants are maintained. Specifically:
3322 ///
3323 /// * The key of the newly inserted element must be unique in the tree.
3324 /// * All keys in the tree must remain in sorted order.
3325 #[unstable(feature = "btree_cursors", issue = "107540")]
3326 pub unsafe fn with_mutable_key(self) -> CursorMutKey<'a, K, V, A> {
3327 self.inner
3328 }
3329}
3330
3331impl<'a, K, V, A> CursorMutKey<'a, K, V, A> {
3332 /// Advances the cursor to the next gap, returning the key and value of the
3333 /// element that it moved over.
3334 ///
3335 /// If the cursor is already at the end of the map then `None` is returned
3336 /// and the cursor is not moved.
3337 #[unstable(feature = "btree_cursors", issue = "107540")]
3338 pub fn next(&mut self) -> Option<(&mut K, &mut V)> {
3339 let current = self.current.take()?;
3340 match current.next_kv() {
3341 Ok(mut kv) => {
3342 // SAFETY: The key/value pointers remain valid even after the
3343 // cursor is moved forward. The lifetimes then prevent any
3344 // further access to the cursor.
3345 let (k, v) = unsafe { kv.reborrow_mut().into_kv_mut() };
3346 let (k, v) = (k as *mut _, v as *mut _);
3347 self.current = Some(kv.next_leaf_edge());
3348 Some(unsafe { (&mut *k, &mut *v) })
3349 }
3350 Err(root) => {
3351 self.current = Some(root.last_leaf_edge());
3352 None
3353 }
3354 }
3355 }
3356
3357 /// Advances the cursor to the previous gap, returning the key and value of
3358 /// the element that it moved over.
3359 ///
3360 /// If the cursor is already at the start of the map then `None` is returned
3361 /// and the cursor is not moved.
3362 #[unstable(feature = "btree_cursors", issue = "107540")]
3363 pub fn prev(&mut self) -> Option<(&mut K, &mut V)> {
3364 let current = self.current.take()?;
3365 match current.next_back_kv() {
3366 Ok(mut kv) => {
3367 // SAFETY: The key/value pointers remain valid even after the
3368 // cursor is moved forward. The lifetimes then prevent any
3369 // further access to the cursor.
3370 let (k, v) = unsafe { kv.reborrow_mut().into_kv_mut() };
3371 let (k, v) = (k as *mut _, v as *mut _);
3372 self.current = Some(kv.next_back_leaf_edge());
3373 Some(unsafe { (&mut *k, &mut *v) })
3374 }
3375 Err(root) => {
3376 self.current = Some(root.first_leaf_edge());
3377 None
3378 }
3379 }
3380 }
3381
3382 /// Returns a reference to the key and value of the next element without
3383 /// moving the cursor.
3384 ///
3385 /// If the cursor is at the end of the map then `None` is returned.
3386 #[unstable(feature = "btree_cursors", issue = "107540")]
3387 pub fn peek_next(&mut self) -> Option<(&mut K, &mut V)> {
3388 let current = self.current.as_mut()?;
3389 // SAFETY: We're not using this to mutate the tree.
3390 let kv = unsafe { current.reborrow_mut() }.next_kv().ok()?.into_kv_mut();
3391 Some(kv)
3392 }
3393
3394 /// Returns a reference to the key and value of the previous element
3395 /// without moving the cursor.
3396 ///
3397 /// If the cursor is at the start of the map then `None` is returned.
3398 #[unstable(feature = "btree_cursors", issue = "107540")]
3399 pub fn peek_prev(&mut self) -> Option<(&mut K, &mut V)> {
3400 let current = self.current.as_mut()?;
3401 // SAFETY: We're not using this to mutate the tree.
3402 let kv = unsafe { current.reborrow_mut() }.next_back_kv().ok()?.into_kv_mut();
3403 Some(kv)
3404 }
3405
3406 /// Returns a read-only cursor pointing to the same location as the
3407 /// `CursorMutKey`.
3408 ///
3409 /// The lifetime of the returned `Cursor` is bound to that of the
3410 /// `CursorMutKey`, which means it cannot outlive the `CursorMutKey` and that the
3411 /// `CursorMutKey` is frozen for the lifetime of the `Cursor`.
3412 #[unstable(feature = "btree_cursors", issue = "107540")]
3413 pub fn as_cursor(&self) -> Cursor<'_, K, V> {
3414 Cursor {
3415 // SAFETY: The tree is immutable while the cursor exists.
3416 root: unsafe { self.root.reborrow_shared().as_ref() },
3417 current: self.current.as_ref().map(|current| current.reborrow()),
3418 }
3419 }
3420}
3421
3422// Now the tree editing operations
3423impl<'a, K: Ord, V, A: AllocatorClone> CursorMutKey<'a, K, V, A> {
3424 /// Inserts a new key-value pair into the map in the gap that the
3425 /// cursor is currently pointing to.
3426 ///
3427 /// After the insertion the cursor will be pointing at the gap before the
3428 /// newly inserted element.
3429 ///
3430 /// # Safety
3431 ///
3432 /// You must ensure that the `BTreeMap` invariants are maintained.
3433 /// Specifically:
3434 ///
3435 /// * The key of the newly inserted element must be unique in the tree.
3436 /// * All keys in the tree must remain in sorted order.
3437 #[unstable(feature = "btree_cursors", issue = "107540")]
3438 pub unsafe fn insert_after_unchecked(&mut self, key: K, value: V) {
3439 let edge = match self.current.take() {
3440 None => {
3441 // Tree is empty, allocate a new root.
3442 // SAFETY: We have no other reference to the tree.
3443 let root = unsafe { self.root.reborrow() };
3444 debug_assert!(root.is_none());
3445 let mut node = NodeRef::new_leaf(self.alloc.clone());
3446 // SAFETY: We don't touch the root while the handle is alive.
3447 let handle = unsafe { node.borrow_mut().push_with_handle(key, value) };
3448 *root = Some(node.forget_type());
3449 *self.length += 1;
3450 self.current = Some(handle.left_edge());
3451 return;
3452 }
3453 Some(current) => current,
3454 };
3455
3456 let handle = edge.insert_recursing(key, value, self.alloc.clone(), |ins| {
3457 drop(ins.left);
3458 // SAFETY: The handle to the newly inserted value is always on a
3459 // leaf node, so adding a new root node doesn't invalidate it.
3460 let root = unsafe { self.root.reborrow().as_mut().unwrap() };
3461 root.push_internal_level(self.alloc.clone()).push(ins.kv.0, ins.kv.1, ins.right)
3462 });
3463 self.current = Some(handle.left_edge());
3464 *self.length += 1;
3465 }
3466
3467 /// Inserts a new key-value pair into the map in the gap that the
3468 /// cursor is currently pointing to.
3469 ///
3470 /// After the insertion the cursor will be pointing at the gap after the
3471 /// newly inserted element.
3472 ///
3473 /// # Safety
3474 ///
3475 /// You must ensure that the `BTreeMap` invariants are maintained.
3476 /// Specifically:
3477 ///
3478 /// * The key of the newly inserted element must be unique in the tree.
3479 /// * All keys in the tree must remain in sorted order.
3480 #[unstable(feature = "btree_cursors", issue = "107540")]
3481 pub unsafe fn insert_before_unchecked(&mut self, key: K, value: V) {
3482 let edge = match self.current.take() {
3483 None => {
3484 // SAFETY: We have no other reference to the tree.
3485 match unsafe { self.root.reborrow() } {
3486 root @ None => {
3487 // Tree is empty, allocate a new root.
3488 let mut node = NodeRef::new_leaf(self.alloc.clone());
3489 // SAFETY: We don't touch the root while the handle is alive.
3490 let handle = unsafe { node.borrow_mut().push_with_handle(key, value) };
3491 *root = Some(node.forget_type());
3492 *self.length += 1;
3493 self.current = Some(handle.right_edge());
3494 return;
3495 }
3496 Some(root) => root.borrow_mut().last_leaf_edge(),
3497 }
3498 }
3499 Some(current) => current,
3500 };
3501
3502 let handle = edge.insert_recursing(key, value, self.alloc.clone(), |ins| {
3503 drop(ins.left);
3504 // SAFETY: The handle to the newly inserted value is always on a
3505 // leaf node, so adding a new root node doesn't invalidate it.
3506 let root = unsafe { self.root.reborrow().as_mut().unwrap() };
3507 root.push_internal_level(self.alloc.clone()).push(ins.kv.0, ins.kv.1, ins.right)
3508 });
3509 self.current = Some(handle.right_edge());
3510 *self.length += 1;
3511 }
3512
3513 /// Inserts a new key-value pair into the map in the gap that the
3514 /// cursor is currently pointing to.
3515 ///
3516 /// After the insertion the cursor will be pointing at the gap before the
3517 /// newly inserted element.
3518 ///
3519 /// If the inserted key is not greater than the key before the cursor
3520 /// (if any), or if it not less than the key after the cursor (if any),
3521 /// then an [`UnorderedKeyError`] is returned since this would
3522 /// invalidate the [`Ord`] invariant between the keys of the map.
3523 #[unstable(feature = "btree_cursors", issue = "107540")]
3524 pub fn insert_after(&mut self, key: K, value: V) -> Result<(), UnorderedKeyError> {
3525 if let Some((prev, _)) = self.peek_prev() {
3526 if &key <= prev {
3527 return Err(UnorderedKeyError {});
3528 }
3529 }
3530 if let Some((next, _)) = self.peek_next() {
3531 if &key >= next {
3532 return Err(UnorderedKeyError {});
3533 }
3534 }
3535 unsafe {
3536 self.insert_after_unchecked(key, value);
3537 }
3538 Ok(())
3539 }
3540
3541 /// Inserts a new key-value pair into the map in the gap that the
3542 /// cursor is currently pointing to.
3543 ///
3544 /// After the insertion the cursor will be pointing at the gap after the
3545 /// newly inserted element.
3546 ///
3547 /// If the inserted key is not greater than the key before the cursor
3548 /// (if any), or if it not less than the key after the cursor (if any),
3549 /// then an [`UnorderedKeyError`] is returned since this would
3550 /// invalidate the [`Ord`] invariant between the keys of the map.
3551 #[unstable(feature = "btree_cursors", issue = "107540")]
3552 pub fn insert_before(&mut self, key: K, value: V) -> Result<(), UnorderedKeyError> {
3553 if let Some((prev, _)) = self.peek_prev() {
3554 if &key <= prev {
3555 return Err(UnorderedKeyError {});
3556 }
3557 }
3558 if let Some((next, _)) = self.peek_next() {
3559 if &key >= next {
3560 return Err(UnorderedKeyError {});
3561 }
3562 }
3563 unsafe {
3564 self.insert_before_unchecked(key, value);
3565 }
3566 Ok(())
3567 }
3568
3569 /// Removes the next element from the `BTreeMap`.
3570 ///
3571 /// The element that was removed is returned. The cursor position is
3572 /// unchanged (before the removed element).
3573 #[unstable(feature = "btree_cursors", issue = "107540")]
3574 pub fn remove_next(&mut self) -> Option<(K, V)> {
3575 let current = self.current.take()?;
3576 if current.reborrow().next_kv().is_err() {
3577 self.current = Some(current);
3578 return None;
3579 }
3580 let mut emptied_internal_root = false;
3581 let (kv, pos) = current
3582 .next_kv()
3583 // This should be unwrap(), but that doesn't work because NodeRef
3584 // doesn't implement Debug. The condition is checked above.
3585 .ok()?
3586 .remove_kv_tracking(|| emptied_internal_root = true, self.alloc.clone());
3587 self.current = Some(pos);
3588 *self.length -= 1;
3589 if emptied_internal_root {
3590 // SAFETY: This is safe since current does not point within the now
3591 // empty root node.
3592 let root = unsafe { self.root.reborrow().as_mut().unwrap() };
3593 root.pop_internal_level(self.alloc.clone());
3594 }
3595 Some(kv)
3596 }
3597
3598 /// Removes the preceding element from the `BTreeMap`.
3599 ///
3600 /// The element that was removed is returned. The cursor position is
3601 /// unchanged (after the removed element).
3602 #[unstable(feature = "btree_cursors", issue = "107540")]
3603 pub fn remove_prev(&mut self) -> Option<(K, V)> {
3604 let current = self.current.take()?;
3605 if current.reborrow().next_back_kv().is_err() {
3606 self.current = Some(current);
3607 return None;
3608 }
3609 let mut emptied_internal_root = false;
3610 let (kv, pos) = current
3611 .next_back_kv()
3612 // This should be unwrap(), but that doesn't work because NodeRef
3613 // doesn't implement Debug. The condition is checked above.
3614 .ok()?
3615 .remove_kv_tracking(|| emptied_internal_root = true, self.alloc.clone());
3616 self.current = Some(pos);
3617 *self.length -= 1;
3618 if emptied_internal_root {
3619 // SAFETY: This is safe since current does not point within the now
3620 // empty root node.
3621 let root = unsafe { self.root.reborrow().as_mut().unwrap() };
3622 root.pop_internal_level(self.alloc.clone());
3623 }
3624 Some(kv)
3625 }
3626}
3627
3628impl<'a, K: Ord, V, A: AllocatorClone> CursorMut<'a, K, V, A> {
3629 /// Inserts a new key-value pair into the map in the gap that the
3630 /// cursor is currently pointing to.
3631 ///
3632 /// After the insertion the cursor will be pointing at the gap after the
3633 /// newly inserted element.
3634 ///
3635 /// # Safety
3636 ///
3637 /// You must ensure that the `BTreeMap` invariants are maintained.
3638 /// Specifically:
3639 ///
3640 /// * The key of the newly inserted element must be unique in the tree.
3641 /// * All keys in the tree must remain in sorted order.
3642 #[unstable(feature = "btree_cursors", issue = "107540")]
3643 pub unsafe fn insert_after_unchecked(&mut self, key: K, value: V) {
3644 unsafe { self.inner.insert_after_unchecked(key, value) }
3645 }
3646
3647 /// Inserts a new key-value pair into the map in the gap that the
3648 /// cursor is currently pointing to.
3649 ///
3650 /// After the insertion the cursor will be pointing at the gap after the
3651 /// newly inserted element.
3652 ///
3653 /// # Safety
3654 ///
3655 /// You must ensure that the `BTreeMap` invariants are maintained.
3656 /// Specifically:
3657 ///
3658 /// * The key of the newly inserted element must be unique in the tree.
3659 /// * All keys in the tree must remain in sorted order.
3660 #[unstable(feature = "btree_cursors", issue = "107540")]
3661 pub unsafe fn insert_before_unchecked(&mut self, key: K, value: V) {
3662 unsafe { self.inner.insert_before_unchecked(key, value) }
3663 }
3664
3665 /// Inserts a new key-value pair into the map in the gap that the
3666 /// cursor is currently pointing to.
3667 ///
3668 /// After the insertion the cursor will be pointing at the gap before the
3669 /// newly inserted element.
3670 ///
3671 /// If the inserted key is not greater than the key before the cursor
3672 /// (if any), or if it not less than the key after the cursor (if any),
3673 /// then an [`UnorderedKeyError`] is returned since this would
3674 /// invalidate the [`Ord`] invariant between the keys of the map.
3675 #[unstable(feature = "btree_cursors", issue = "107540")]
3676 pub fn insert_after(&mut self, key: K, value: V) -> Result<(), UnorderedKeyError> {
3677 self.inner.insert_after(key, value)
3678 }
3679
3680 /// Inserts a new key-value pair into the map in the gap that the
3681 /// cursor is currently pointing to.
3682 ///
3683 /// After the insertion the cursor will be pointing at the gap after the
3684 /// newly inserted element.
3685 ///
3686 /// If the inserted key is not greater than the key before the cursor
3687 /// (if any), or if it not less than the key after the cursor (if any),
3688 /// then an [`UnorderedKeyError`] is returned since this would
3689 /// invalidate the [`Ord`] invariant between the keys of the map.
3690 #[unstable(feature = "btree_cursors", issue = "107540")]
3691 pub fn insert_before(&mut self, key: K, value: V) -> Result<(), UnorderedKeyError> {
3692 self.inner.insert_before(key, value)
3693 }
3694
3695 /// Removes the next element from the `BTreeMap`.
3696 ///
3697 /// The element that was removed is returned. The cursor position is
3698 /// unchanged (before the removed element).
3699 #[unstable(feature = "btree_cursors", issue = "107540")]
3700 pub fn remove_next(&mut self) -> Option<(K, V)> {
3701 self.inner.remove_next()
3702 }
3703
3704 /// Removes the preceding element from the `BTreeMap`.
3705 ///
3706 /// The element that was removed is returned. The cursor position is
3707 /// unchanged (after the removed element).
3708 #[unstable(feature = "btree_cursors", issue = "107540")]
3709 pub fn remove_prev(&mut self) -> Option<(K, V)> {
3710 self.inner.remove_prev()
3711 }
3712}
3713
3714/// Error type returned by [`CursorMut::insert_before`] and
3715/// [`CursorMut::insert_after`] if the key being inserted is not properly
3716/// ordered with regards to adjacent keys.
3717#[derive(Clone, PartialEq, Eq, Debug)]
3718#[unstable(feature = "btree_cursors", issue = "107540")]
3719pub struct UnorderedKeyError {}
3720
3721#[unstable(feature = "btree_cursors", issue = "107540")]
3722impl fmt::Display for UnorderedKeyError {
3723 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3724 write!(f, "key is not properly ordered relative to neighbors")
3725 }
3726}
3727
3728#[unstable(feature = "btree_cursors", issue = "107540")]
3729impl Error for UnorderedKeyError {}
3730
3731#[cfg(test)]
3732mod tests;