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