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