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