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