]> git.proxmox.com Git - rustc.git/blame - src/liballoc/collections/btree/map.rs
New upstream version 1.44.1+dfsg1
[rustc.git] / src / liballoc / collections / btree / map.rs
CommitLineData
9fa01778 1use core::borrow::Borrow;
1a4d82fc 2use core::cmp::Ordering;
85aaf69f 3use core::fmt::Debug;
1a4d82fc 4use core::hash::{Hash, Hasher};
dfeec247 5use core::iter::{FromIterator, FusedIterator, Peekable};
9cc50fc6 6use core::marker::PhantomData;
ba9703b0 7use core::mem::{self, ManuallyDrop};
0531ce1d 8use core::ops::Bound::{Excluded, Included, Unbounded};
9fa01778 9use core::ops::{Index, RangeBounds};
ba9703b0 10use core::{fmt, ptr};
1a4d82fc 11
dfeec247 12use super::node::{self, marker, ForceResult::*, Handle, InsertResult::*, NodeRef};
9fa01778 13use super::search::{self, SearchResult::*};
74b04a01 14use super::unwrap_unchecked;
9cc50fc6 15
9fa01778 16use Entry::*;
dfeec247 17use UnderflowResult::*;
1a4d82fc 18
1a4d82fc
JJ
19/// A map based on a B-Tree.
20///
21/// B-Trees represent a fundamental compromise between cache-efficiency and actually minimizing
22/// the amount of work performed in a search. In theory, a binary search tree (BST) is the optimal
23/// choice for a sorted map, as a perfectly balanced BST performs the theoretical minimum amount of
24/// comparisons necessary to find an element (log<sub>2</sub>n). However, in practice the way this
25/// is done is *very* inefficient for modern computer architectures. In particular, every element
26/// is stored in its own individually heap-allocated node. This means that every single insertion
27/// triggers a heap-allocation, and every single comparison should be a cache-miss. Since these
28/// are both notably expensive things to do in practice, we are forced to at very least reconsider
29/// the BST strategy.
30///
31/// A B-Tree instead makes each node contain B-1 to 2B-1 elements in a contiguous array. By doing
32/// this, we reduce the number of allocations by a factor of B, and improve cache efficiency in
33/// searches. However, this does mean that searches will have to do *more* comparisons on average.
34/// The precise number of comparisons depends on the node search strategy used. For optimal cache
35/// efficiency, one could search the nodes linearly. For optimal comparisons, one could search
36/// the node using binary search. As a compromise, one could also perform a linear search
37/// that initially only checks every i<sup>th</sup> element for some choice of i.
38///
39/// Currently, our implementation simply performs naive linear search. This provides excellent
40/// performance on *small* nodes of elements which are cheap to compare. However in the future we
41/// would like to further explore choosing the optimal search strategy based on the choice of B,
42/// and possibly other factors. Using linear search, searching for a random element is expected
ba9703b0 43/// to take O(B * log(n)) comparisons, which is generally worse than a BST. In practice,
85aaf69f 44/// however, performance is excellent.
c34b1796
AL
45///
46/// It is a logic error for a key to be modified in such a way that the key's ordering relative to
9e0c209e
SL
47/// any other key, as determined by the [`Ord`] trait, changes while it is in the map. This is
48/// normally only possible through [`Cell`], [`RefCell`], global state, I/O, or unsafe code.
49///
50/// [`Ord`]: ../../std/cmp/trait.Ord.html
51/// [`Cell`]: ../../std/cell/struct.Cell.html
52/// [`RefCell`]: ../../std/cell/struct.RefCell.html
54a0048b
SL
53///
54/// # Examples
55///
56/// ```
57/// use std::collections::BTreeMap;
58///
59/// // type inference lets us omit an explicit type signature (which
60/// // would be `BTreeMap<&str, &str>` in this example).
61/// let mut movie_reviews = BTreeMap::new();
62///
3157f602 63/// // review some movies.
54a0048b
SL
64/// movie_reviews.insert("Office Space", "Deals with real issues in the workplace.");
65/// movie_reviews.insert("Pulp Fiction", "Masterpiece.");
66/// movie_reviews.insert("The Godfather", "Very enjoyable.");
0bf4aa26 67/// movie_reviews.insert("The Blues Brothers", "Eye lyked it a lot.");
54a0048b
SL
68///
69/// // check for a specific one.
70/// if !movie_reviews.contains_key("Les Misérables") {
71/// println!("We've got {} reviews, but Les Misérables ain't one.",
72/// movie_reviews.len());
73/// }
74///
75/// // oops, this review has a lot of spelling mistakes, let's delete it.
76/// movie_reviews.remove("The Blues Brothers");
77///
78/// // look up the values associated with some keys.
79/// let to_find = ["Up!", "Office Space"];
416331ca
XL
80/// for movie in &to_find {
81/// match movie_reviews.get(movie) {
82/// Some(review) => println!("{}: {}", movie, review),
83/// None => println!("{} is unreviewed.", movie)
54a0048b
SL
84/// }
85/// }
86///
0731742a
XL
87/// // Look up the value for a key (will panic if the key is not found).
88/// println!("Movie review: {}", movie_reviews["Office Space"]);
89///
54a0048b
SL
90/// // iterate over everything.
91/// for (movie, review) in &movie_reviews {
92/// println!("{}: \"{}\"", movie, review);
93/// }
94/// ```
95///
96/// `BTreeMap` also implements an [`Entry API`](#method.entry), which allows
97/// for more complex methods of getting, setting, updating and removing keys and
98/// their values:
99///
100/// ```
101/// use std::collections::BTreeMap;
102///
103/// // type inference lets us omit an explicit type signature (which
104/// // would be `BTreeMap<&str, u8>` in this example).
105/// let mut player_stats = BTreeMap::new();
106///
107/// fn random_stat_buff() -> u8 {
108/// // could actually return some random value here - let's just return
109/// // some fixed value for now
110/// 42
111/// }
112///
113/// // insert a key only if it doesn't already exist
114/// player_stats.entry("health").or_insert(100);
115///
116/// // insert a key using a function that provides a new value only if it
117/// // doesn't already exist
118/// player_stats.entry("defence").or_insert_with(random_stat_buff);
119///
120/// // update a key, guarding against the key possibly not being set
121/// let stat = player_stats.entry("attack").or_insert(100);
122/// *stat += random_stat_buff();
123/// ```
85aaf69f 124#[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc 125pub struct BTreeMap<K, V> {
ba9703b0 126 root: Option<node::Root<K, V>>,
3157f602 127 length: usize,
9cc50fc6
SL
128}
129
c30ab7b3 130#[stable(feature = "btree_drop", since = "1.7.0")]
32a655c1 131unsafe impl<#[may_dangle] K, #[may_dangle] V> Drop for BTreeMap<K, V> {
9cc50fc6
SL
132 fn drop(&mut self) {
133 unsafe {
cc61c64b 134 drop(ptr::read(self).into_iter());
9cc50fc6
SL
135 }
136 }
137}
138
c30ab7b3 139#[stable(feature = "rust1", since = "1.0.0")]
9cc50fc6
SL
140impl<K: Clone, V: Clone> Clone for BTreeMap<K, V> {
141 fn clone(&self) -> BTreeMap<K, V> {
8faf50e0 142 fn clone_subtree<'a, K: Clone, V: Clone>(
dfeec247 143 node: node::NodeRef<marker::Immut<'a>, K, V, marker::LeafOrInternal>,
8faf50e0 144 ) -> BTreeMap<K, V>
dfeec247
XL
145 where
146 K: 'a,
147 V: 'a,
8faf50e0 148 {
9cc50fc6
SL
149 match node.force() {
150 Leaf(leaf) => {
ba9703b0 151 let mut out_tree = BTreeMap { root: Some(node::Root::new_leaf()), length: 0 };
9cc50fc6
SL
152
153 {
ba9703b0
XL
154 let root = out_tree.root.as_mut().unwrap();
155 let mut out_node = match root.as_mut().force() {
9cc50fc6 156 Leaf(leaf) => leaf,
3157f602 157 Internal(_) => unreachable!(),
9cc50fc6
SL
158 };
159
160 let mut in_edge = leaf.first_edge();
161 while let Ok(kv) = in_edge.right_kv() {
162 let (k, v) = kv.into_kv();
163 in_edge = kv.right_edge();
164
165 out_node.push(k.clone(), v.clone());
166 out_tree.length += 1;
167 }
168 }
169
170 out_tree
3157f602 171 }
9cc50fc6
SL
172 Internal(internal) => {
173 let mut out_tree = clone_subtree(internal.first_edge().descend());
ba9703b0 174 out_tree.ensure_root_is_owned();
9cc50fc6
SL
175
176 {
ba9703b0
XL
177 // Ideally we'd use the return of ensure_root_is_owned
178 // instead of re-unwrapping here but unfortunately that
179 // borrows all of out_tree and we need access to the
180 // length below.
181 let mut out_node = out_tree.root.as_mut().unwrap().push_level();
9cc50fc6
SL
182 let mut in_edge = internal.first_edge();
183 while let Ok(kv) = in_edge.right_kv() {
184 let (k, v) = kv.into_kv();
185 in_edge = kv.right_edge();
186
187 let k = (*k).clone();
188 let v = (*v).clone();
189 let subtree = clone_subtree(in_edge.descend());
190
191 // We can't destructure subtree directly
192 // because BTreeMap implements Drop
193 let (subroot, sublength) = unsafe {
ba9703b0 194 let subtree = ManuallyDrop::new(subtree);
9cc50fc6
SL
195 let root = ptr::read(&subtree.root);
196 let length = subtree.length;
9cc50fc6
SL
197 (root, length)
198 };
199
ba9703b0 200 out_node.push(k, v, subroot.unwrap_or_else(node::Root::new_leaf));
9cc50fc6
SL
201 out_tree.length += 1 + sublength;
202 }
203 }
204
205 out_tree
206 }
207 }
208 }
209
416331ca 210 if self.is_empty() {
8faf50e0
XL
211 // Ideally we'd call `BTreeMap::new` here, but that has the `K:
212 // Ord` constraint, which this method lacks.
ba9703b0 213 BTreeMap { root: None, length: 0 }
8faf50e0 214 } else {
ba9703b0 215 clone_subtree(self.root.as_ref().unwrap().as_ref())
8faf50e0 216 }
9cc50fc6 217 }
74b04a01
XL
218
219 fn clone_from(&mut self, other: &Self) {
220 BTreeClone::clone_from(self, other);
221 }
222}
223
224trait BTreeClone {
225 fn clone_from(&mut self, other: &Self);
226}
227
228impl<K: Clone, V: Clone> BTreeClone for BTreeMap<K, V> {
229 default fn clone_from(&mut self, other: &Self) {
230 *self = other.clone();
231 }
232}
233
234impl<K: Clone + Ord, V: Clone> BTreeClone for BTreeMap<K, V> {
235 fn clone_from(&mut self, other: &Self) {
236 // This truncates `self` to `other.len()` by calling `split_off` on
237 // the first key after `other.len()` elements if it exists.
238 let split_off_key = if self.len() > other.len() {
239 let diff = self.len() - other.len();
240 if diff <= other.len() {
241 self.iter().nth_back(diff - 1).map(|pair| (*pair.0).clone())
242 } else {
243 self.iter().nth(other.len()).map(|pair| (*pair.0).clone())
244 }
245 } else {
246 None
247 };
248 if let Some(key) = split_off_key {
249 self.split_off(&key);
250 }
251
252 let mut siter = self.range_mut(..);
253 let mut oiter = other.iter();
254 // After truncation, `self` is at most as long as `other` so this loop
255 // replaces every key-value pair in `self`. Since `oiter` is in sorted
256 // order and the structure of the `BTreeMap` stays the same,
257 // the BTree invariants are maintained at the end of the loop.
258 while !siter.is_empty() {
259 if let Some((ok, ov)) = oiter.next() {
260 // SAFETY: This is safe because `siter` is nonempty.
261 let (sk, sv) = unsafe { siter.next_unchecked() };
262 sk.clone_from(ok);
263 sv.clone_from(ov);
264 } else {
265 break;
266 }
267 }
268 // If `other` is longer than `self`, the remaining elements are inserted.
269 self.extend(oiter.map(|(k, v)| ((*k).clone(), (*v).clone())));
270 }
1a4d82fc
JJ
271}
272
9cc50fc6 273impl<K, Q: ?Sized> super::Recover<Q> for BTreeMap<K, ()>
dfeec247
XL
274where
275 K: Borrow<Q> + Ord,
276 Q: Ord,
9cc50fc6
SL
277{
278 type Key = K;
279
280 fn get(&self, key: &Q) -> Option<&K> {
ba9703b0 281 match search::search_tree(self.root.as_ref()?.as_ref(), key) {
9cc50fc6 282 Found(handle) => Some(handle.into_kv().0),
3157f602 283 GoDown(_) => None,
9cc50fc6
SL
284 }
285 }
286
287 fn take(&mut self, key: &Q) -> Option<K> {
ba9703b0 288 match search::search_tree(self.root.as_mut()?.as_mut(), key) {
dfeec247
XL
289 Found(handle) => Some(
290 OccupiedEntry { handle, length: &mut self.length, _marker: PhantomData }
291 .remove_kv()
292 .0,
293 ),
3157f602 294 GoDown(_) => None,
9cc50fc6
SL
295 }
296 }
297
298 fn replace(&mut self, key: K) -> Option<K> {
94b46f34 299 self.ensure_root_is_owned();
ba9703b0 300 match search::search_tree::<marker::Mut<'_>, K, (), K>(self.root.as_mut()?.as_mut(), &key) {
9cc50fc6
SL
301 Found(handle) => Some(mem::replace(handle.into_kv_mut().0, key)),
302 GoDown(handle) => {
dfeec247
XL
303 VacantEntry { key, handle, length: &mut self.length, _marker: PhantomData }
304 .insert(());
9cc50fc6
SL
305 None
306 }
307 }
308 }
1a4d82fc
JJ
309}
310
cc61c64b
XL
311/// An iterator over the entries of a `BTreeMap`.
312///
313/// This `struct` is created by the [`iter`] method on [`BTreeMap`]. See its
314/// documentation for more.
315///
316/// [`iter`]: struct.BTreeMap.html#method.iter
317/// [`BTreeMap`]: struct.BTreeMap.html
85aaf69f 318#[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc 319pub struct Iter<'a, K: 'a, V: 'a> {
9cc50fc6 320 range: Range<'a, K, V>,
3157f602 321 length: usize,
1a4d82fc
JJ
322}
323
8bb4bdeb 324#[stable(feature = "collection_debug", since = "1.17.0")]
9fa01778
XL
325impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for Iter<'_, K, V> {
326 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
8bb4bdeb
XL
327 f.debug_list().entries(self.clone()).finish()
328 }
329}
330
cc61c64b
XL
331/// A mutable iterator over the entries of a `BTreeMap`.
332///
333/// This `struct` is created by the [`iter_mut`] method on [`BTreeMap`]. See its
334/// documentation for more.
335///
336/// [`iter_mut`]: struct.BTreeMap.html#method.iter_mut
337/// [`BTreeMap`]: struct.BTreeMap.html
85aaf69f 338#[stable(feature = "rust1", since = "1.0.0")]
8bb4bdeb 339#[derive(Debug)]
1a4d82fc 340pub struct IterMut<'a, K: 'a, V: 'a> {
9cc50fc6 341 range: RangeMut<'a, K, V>,
3157f602 342 length: usize,
1a4d82fc
JJ
343}
344
cc61c64b
XL
345/// An owning iterator over the entries of a `BTreeMap`.
346///
dfeec247 347/// This `struct` is created by the [`into_iter`] method on [`BTreeMap`]
cc61c64b
XL
348/// (provided by the `IntoIterator` trait). See its documentation for more.
349///
350/// [`into_iter`]: struct.BTreeMap.html#method.into_iter
351/// [`BTreeMap`]: struct.BTreeMap.html
85aaf69f 352#[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc 353pub struct IntoIter<K, V> {
ba9703b0
XL
354 front: Option<Handle<NodeRef<marker::Owned, K, V, marker::Leaf>, marker::Edge>>,
355 back: Option<Handle<NodeRef<marker::Owned, K, V, marker::Leaf>, marker::Edge>>,
3157f602 356 length: usize,
1a4d82fc
JJ
357}
358
8bb4bdeb
XL
359#[stable(feature = "collection_debug", since = "1.17.0")]
360impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for IntoIter<K, V> {
9fa01778 361 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
ba9703b0
XL
362 let range = Range {
363 front: self.front.as_ref().map(|f| f.reborrow()),
364 back: self.back.as_ref().map(|b| b.reborrow()),
365 };
8bb4bdeb
XL
366 f.debug_list().entries(range).finish()
367 }
368}
369
cc61c64b
XL
370/// An iterator over the keys of a `BTreeMap`.
371///
372/// This `struct` is created by the [`keys`] method on [`BTreeMap`]. See its
373/// documentation for more.
374///
375/// [`keys`]: struct.BTreeMap.html#method.keys
376/// [`BTreeMap`]: struct.BTreeMap.html
85aaf69f 377#[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc 378pub struct Keys<'a, K: 'a, V: 'a> {
9cc50fc6 379 inner: Iter<'a, K, V>,
1a4d82fc
JJ
380}
381
8bb4bdeb 382#[stable(feature = "collection_debug", since = "1.17.0")]
9fa01778
XL
383impl<K: fmt::Debug, V> fmt::Debug for Keys<'_, K, V> {
384 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
041b39d2 385 f.debug_list().entries(self.clone()).finish()
8bb4bdeb
XL
386 }
387}
388
cc61c64b
XL
389/// An iterator over the values of a `BTreeMap`.
390///
391/// This `struct` is created by the [`values`] method on [`BTreeMap`]. See its
392/// documentation for more.
393///
394/// [`values`]: struct.BTreeMap.html#method.values
395/// [`BTreeMap`]: struct.BTreeMap.html
85aaf69f 396#[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc 397pub struct Values<'a, K: 'a, V: 'a> {
9cc50fc6 398 inner: Iter<'a, K, V>,
85aaf69f
SL
399}
400
8bb4bdeb 401#[stable(feature = "collection_debug", since = "1.17.0")]
9fa01778
XL
402impl<K, V: fmt::Debug> fmt::Debug for Values<'_, K, V> {
403 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
041b39d2 404 f.debug_list().entries(self.clone()).finish()
8bb4bdeb
XL
405 }
406}
407
cc61c64b
XL
408/// A mutable iterator over the values of a `BTreeMap`.
409///
410/// This `struct` is created by the [`values_mut`] method on [`BTreeMap`]. See its
411/// documentation for more.
412///
413/// [`values_mut`]: struct.BTreeMap.html#method.values_mut
414/// [`BTreeMap`]: struct.BTreeMap.html
a7813a04 415#[stable(feature = "map_values_mut", since = "1.10.0")]
8bb4bdeb 416#[derive(Debug)]
54a0048b
SL
417pub struct ValuesMut<'a, K: 'a, V: 'a> {
418 inner: IterMut<'a, K, V>,
419}
420
cc61c64b
XL
421/// An iterator over a sub-range of entries in a `BTreeMap`.
422///
423/// This `struct` is created by the [`range`] method on [`BTreeMap`]. See its
424/// documentation for more.
425///
426/// [`range`]: struct.BTreeMap.html#method.range
427/// [`BTreeMap`]: struct.BTreeMap.html
8bb4bdeb 428#[stable(feature = "btree_range", since = "1.17.0")]
85aaf69f 429pub struct Range<'a, K: 'a, V: 'a> {
ba9703b0
XL
430 front: Option<Handle<NodeRef<marker::Immut<'a>, K, V, marker::Leaf>, marker::Edge>>,
431 back: Option<Handle<NodeRef<marker::Immut<'a>, K, V, marker::Leaf>, marker::Edge>>,
85aaf69f
SL
432}
433
8bb4bdeb 434#[stable(feature = "collection_debug", since = "1.17.0")]
9fa01778
XL
435impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for Range<'_, K, V> {
436 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
8bb4bdeb
XL
437 f.debug_list().entries(self.clone()).finish()
438 }
439}
440
cc61c64b
XL
441/// A mutable iterator over a sub-range of entries in a `BTreeMap`.
442///
443/// This `struct` is created by the [`range_mut`] method on [`BTreeMap`]. See its
444/// documentation for more.
445///
446/// [`range_mut`]: struct.BTreeMap.html#method.range_mut
447/// [`BTreeMap`]: struct.BTreeMap.html
8bb4bdeb 448#[stable(feature = "btree_range", since = "1.17.0")]
85aaf69f 449pub struct RangeMut<'a, K: 'a, V: 'a> {
ba9703b0
XL
450 front: Option<Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge>>,
451 back: Option<Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge>>,
9cc50fc6
SL
452
453 // Be invariant in `K` and `V`
454 _marker: PhantomData<&'a mut (K, V)>,
1a4d82fc
JJ
455}
456
8bb4bdeb 457#[stable(feature = "collection_debug", since = "1.17.0")]
9fa01778
XL
458impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for RangeMut<'_, K, V> {
459 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
ba9703b0
XL
460 let range = Range {
461 front: self.front.as_ref().map(|f| f.reborrow()),
462 back: self.back.as_ref().map(|b| b.reborrow()),
463 };
8bb4bdeb
XL
464 f.debug_list().entries(range).finish()
465 }
466}
467
1a4d82fc 468/// A view into a single entry in a map, which may either be vacant or occupied.
cc61c64b
XL
469///
470/// This `enum` is constructed from the [`entry`] method on [`BTreeMap`].
5bcae85e
SL
471///
472/// [`BTreeMap`]: struct.BTreeMap.html
473/// [`entry`]: struct.BTreeMap.html#method.entry
c34b1796 474#[stable(feature = "rust1", since = "1.0.0")]
92a42be0 475pub enum Entry<'a, K: 'a, V: 'a> {
cc61c64b 476 /// A vacant entry.
c34b1796 477 #[stable(feature = "rust1", since = "1.0.0")]
dfeec247 478 Vacant(#[stable(feature = "rust1", since = "1.0.0")] VacantEntry<'a, K, V>),
c34b1796 479
cc61c64b 480 /// An occupied entry.
c34b1796 481 #[stable(feature = "rust1", since = "1.0.0")]
dfeec247 482 Occupied(#[stable(feature = "rust1", since = "1.0.0")] OccupiedEntry<'a, K, V>),
1a4d82fc
JJ
483}
484
dfeec247 485#[stable(feature = "debug_btree_map", since = "1.12.0")]
9fa01778
XL
486impl<K: Debug + Ord, V: Debug> Debug for Entry<'_, K, V> {
487 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5bcae85e 488 match *self {
dfeec247
XL
489 Vacant(ref v) => f.debug_tuple("Entry").field(v).finish(),
490 Occupied(ref o) => f.debug_tuple("Entry").field(o).finish(),
5bcae85e
SL
491 }
492 }
493}
494
cc61c64b
XL
495/// A view into a vacant entry in a `BTreeMap`.
496/// It is part of the [`Entry`] enum.
5bcae85e
SL
497///
498/// [`Entry`]: enum.Entry.html
c34b1796 499#[stable(feature = "rust1", since = "1.0.0")]
92a42be0 500pub struct VacantEntry<'a, K: 'a, V: 'a> {
1a4d82fc 501 key: K,
9cc50fc6
SL
502 handle: Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge>,
503 length: &'a mut usize,
504
505 // Be invariant in `K` and `V`
506 _marker: PhantomData<&'a mut (K, V)>,
1a4d82fc
JJ
507}
508
dfeec247 509#[stable(feature = "debug_btree_map", since = "1.12.0")]
9fa01778
XL
510impl<K: Debug + Ord, V> Debug for VacantEntry<'_, K, V> {
511 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
dfeec247 512 f.debug_tuple("VacantEntry").field(self.key()).finish()
5bcae85e
SL
513 }
514}
515
cc61c64b
XL
516/// A view into an occupied entry in a `BTreeMap`.
517/// It is part of the [`Entry`] enum.
5bcae85e
SL
518///
519/// [`Entry`]: enum.Entry.html
c34b1796 520#[stable(feature = "rust1", since = "1.0.0")]
92a42be0 521pub struct OccupiedEntry<'a, K: 'a, V: 'a> {
3157f602 522 handle: Handle<NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal>, marker::KV>,
9cc50fc6
SL
523
524 length: &'a mut usize,
525
526 // Be invariant in `K` and `V`
527 _marker: PhantomData<&'a mut (K, V)>,
1a4d82fc
JJ
528}
529
dfeec247 530#[stable(feature = "debug_btree_map", since = "1.12.0")]
9fa01778
XL
531impl<K: Debug + Ord, V: Debug> Debug for OccupiedEntry<'_, K, V> {
532 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
dfeec247 533 f.debug_struct("OccupiedEntry").field("key", self.key()).field("value", self.get()).finish()
5bcae85e
SL
534 }
535}
536
a7813a04 537// An iterator for merging two sorted sequences into one
3157f602 538struct MergeIter<K, V, I: Iterator<Item = (K, V)>> {
a7813a04
XL
539 left: Peekable<I>,
540 right: Peekable<I>,
541}
542
1a4d82fc
JJ
543impl<K: Ord, V> BTreeMap<K, V> {
544 /// Makes a new empty BTreeMap with a reasonable choice for B.
54a0048b
SL
545 ///
546 /// # Examples
547 ///
548 /// Basic usage:
549 ///
550 /// ```
551 /// use std::collections::BTreeMap;
552 ///
553 /// let mut map = BTreeMap::new();
554 ///
555 /// // entries can now be inserted into the empty map
556 /// map.insert(1, "a");
557 /// ```
85aaf69f 558 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc 559 pub fn new() -> BTreeMap<K, V> {
ba9703b0 560 BTreeMap { root: None, length: 0 }
1a4d82fc
JJ
561 }
562
dfeec247 563 /// Clears the map, removing all elements.
1a4d82fc
JJ
564 ///
565 /// # Examples
566 ///
54a0048b
SL
567 /// Basic usage:
568 ///
1a4d82fc
JJ
569 /// ```
570 /// use std::collections::BTreeMap;
571 ///
572 /// let mut a = BTreeMap::new();
85aaf69f 573 /// a.insert(1, "a");
1a4d82fc
JJ
574 /// a.clear();
575 /// assert!(a.is_empty());
576 /// ```
85aaf69f 577 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc 578 pub fn clear(&mut self) {
9cc50fc6 579 *self = BTreeMap::new();
1a4d82fc
JJ
580 }
581
1a4d82fc
JJ
582 /// Returns a reference to the value corresponding to the key.
583 ///
584 /// The key may be any borrowed form of the map's key type, but the ordering
585 /// on the borrowed form *must* match the ordering on the key type.
586 ///
587 /// # Examples
588 ///
54a0048b
SL
589 /// Basic usage:
590 ///
1a4d82fc
JJ
591 /// ```
592 /// use std::collections::BTreeMap;
593 ///
594 /// let mut map = BTreeMap::new();
85aaf69f 595 /// map.insert(1, "a");
1a4d82fc
JJ
596 /// assert_eq!(map.get(&1), Some(&"a"));
597 /// assert_eq!(map.get(&2), None);
598 /// ```
85aaf69f 599 #[stable(feature = "rust1", since = "1.0.0")]
3157f602 600 pub fn get<Q: ?Sized>(&self, key: &Q) -> Option<&V>
dfeec247
XL
601 where
602 K: Borrow<Q>,
603 Q: Ord,
3157f602 604 {
ba9703b0 605 match search::search_tree(self.root.as_ref()?.as_ref(), key) {
9cc50fc6 606 Found(handle) => Some(handle.into_kv().1),
3157f602 607 GoDown(_) => None,
1a4d82fc
JJ
608 }
609 }
610
0531ce1d
XL
611 /// Returns the key-value pair corresponding to the supplied key.
612 ///
613 /// The supplied key may be any borrowed form of the map's key type, but the ordering
614 /// on the borrowed form *must* match the ordering on the key type.
615 ///
616 /// # Examples
617 ///
618 /// ```
0531ce1d
XL
619 /// use std::collections::BTreeMap;
620 ///
621 /// let mut map = BTreeMap::new();
622 /// map.insert(1, "a");
623 /// assert_eq!(map.get_key_value(&1), Some((&1, &"a")));
624 /// assert_eq!(map.get_key_value(&2), None);
625 /// ```
e74abb32 626 #[stable(feature = "map_get_key_value", since = "1.40.0")]
0531ce1d 627 pub fn get_key_value<Q: ?Sized>(&self, k: &Q) -> Option<(&K, &V)>
dfeec247
XL
628 where
629 K: Borrow<Q>,
630 Q: Ord,
0531ce1d 631 {
ba9703b0 632 match search::search_tree(self.root.as_ref()?.as_ref(), k) {
0531ce1d
XL
633 Found(handle) => Some(handle.into_kv()),
634 GoDown(_) => None,
635 }
636 }
637
60c5eb7d
XL
638 /// Returns the first key-value pair in the map.
639 /// The key in this pair is the minimum key in the map.
640 ///
641 /// # Examples
642 ///
643 /// Basic usage:
644 ///
645 /// ```
646 /// #![feature(map_first_last)]
647 /// use std::collections::BTreeMap;
648 ///
649 /// let mut map = BTreeMap::new();
650 /// assert_eq!(map.first_key_value(), None);
651 /// map.insert(1, "b");
652 /// map.insert(2, "a");
653 /// assert_eq!(map.first_key_value(), Some((&1, &"b")));
654 /// ```
655 #[unstable(feature = "map_first_last", issue = "62924")]
ba9703b0
XL
656 pub fn first_key_value(&self) -> Option<(&K, &V)> {
657 let front = self.root.as_ref()?.as_ref().first_leaf_edge();
60c5eb7d
XL
658 front.right_kv().ok().map(Handle::into_kv)
659 }
660
661 /// Returns the first entry in the map for in-place manipulation.
662 /// The key of this entry is the minimum key in the map.
663 ///
664 /// # Examples
665 ///
ba9703b0
XL
666 /// ```
667 /// #![feature(map_first_last)]
668 /// use std::collections::BTreeMap;
669 ///
670 /// let mut map = BTreeMap::new();
671 /// map.insert(1, "a");
672 /// map.insert(2, "b");
673 /// if let Some(mut entry) = map.first_entry() {
674 /// if *entry.key() > 0 {
675 /// entry.insert("first");
676 /// }
677 /// }
678 /// assert_eq!(*map.get(&1).unwrap(), "first");
679 /// assert_eq!(*map.get(&2).unwrap(), "b");
680 /// ```
681 #[unstable(feature = "map_first_last", issue = "62924")]
682 pub fn first_entry(&mut self) -> Option<OccupiedEntry<'_, K, V>> {
683 let front = self.root.as_mut()?.as_mut().first_leaf_edge();
684 let kv = front.right_kv().ok()?;
685 Some(OccupiedEntry {
686 handle: kv.forget_node_type(),
687 length: &mut self.length,
688 _marker: PhantomData,
689 })
690 }
691
692 /// Removes and returns the first element in the map.
693 /// The key of this element is the minimum key that was in the map.
694 ///
695 /// # Examples
696 ///
697 /// Draining elements in ascending order, while keeping a usable map each iteration.
60c5eb7d
XL
698 ///
699 /// ```
700 /// #![feature(map_first_last)]
701 /// use std::collections::BTreeMap;
702 ///
703 /// let mut map = BTreeMap::new();
704 /// map.insert(1, "a");
705 /// map.insert(2, "b");
ba9703b0
XL
706 /// while let Some((key, _val)) = map.pop_first() {
707 /// assert!(map.iter().all(|(k, _v)| *k > key));
60c5eb7d 708 /// }
ba9703b0 709 /// assert!(map.is_empty());
60c5eb7d
XL
710 /// ```
711 #[unstable(feature = "map_first_last", issue = "62924")]
ba9703b0
XL
712 pub fn pop_first(&mut self) -> Option<(K, V)> {
713 self.first_entry().map(|entry| entry.remove_entry())
60c5eb7d
XL
714 }
715
716 /// Returns the last key-value pair in the map.
717 /// The key in this pair is the maximum key in the map.
718 ///
719 /// # Examples
720 ///
721 /// Basic usage:
722 ///
723 /// ```
724 /// #![feature(map_first_last)]
725 /// use std::collections::BTreeMap;
726 ///
727 /// let mut map = BTreeMap::new();
728 /// map.insert(1, "b");
729 /// map.insert(2, "a");
730 /// assert_eq!(map.last_key_value(), Some((&2, &"a")));
731 /// ```
732 #[unstable(feature = "map_first_last", issue = "62924")]
ba9703b0
XL
733 pub fn last_key_value(&self) -> Option<(&K, &V)> {
734 let back = self.root.as_ref()?.as_ref().last_leaf_edge();
60c5eb7d
XL
735 back.left_kv().ok().map(Handle::into_kv)
736 }
737
738 /// Returns the last entry in the map for in-place manipulation.
739 /// The key of this entry is the maximum key in the map.
740 ///
741 /// # Examples
742 ///
ba9703b0
XL
743 /// ```
744 /// #![feature(map_first_last)]
745 /// use std::collections::BTreeMap;
746 ///
747 /// let mut map = BTreeMap::new();
748 /// map.insert(1, "a");
749 /// map.insert(2, "b");
750 /// if let Some(mut entry) = map.last_entry() {
751 /// if *entry.key() > 0 {
752 /// entry.insert("last");
753 /// }
754 /// }
755 /// assert_eq!(*map.get(&1).unwrap(), "a");
756 /// assert_eq!(*map.get(&2).unwrap(), "last");
757 /// ```
758 #[unstable(feature = "map_first_last", issue = "62924")]
759 pub fn last_entry(&mut self) -> Option<OccupiedEntry<'_, K, V>> {
760 let back = self.root.as_mut()?.as_mut().last_leaf_edge();
761 let kv = back.left_kv().ok()?;
762 Some(OccupiedEntry {
763 handle: kv.forget_node_type(),
764 length: &mut self.length,
765 _marker: PhantomData,
766 })
767 }
768
769 /// Removes and returns the last element in the map.
770 /// The key of this element is the maximum key that was in the map.
771 ///
772 /// # Examples
773 ///
774 /// Draining elements in descending order, while keeping a usable map each iteration.
60c5eb7d
XL
775 ///
776 /// ```
777 /// #![feature(map_first_last)]
778 /// use std::collections::BTreeMap;
779 ///
780 /// let mut map = BTreeMap::new();
781 /// map.insert(1, "a");
782 /// map.insert(2, "b");
ba9703b0
XL
783 /// while let Some((key, _val)) = map.pop_last() {
784 /// assert!(map.iter().all(|(k, _v)| *k < key));
60c5eb7d 785 /// }
ba9703b0 786 /// assert!(map.is_empty());
60c5eb7d
XL
787 /// ```
788 #[unstable(feature = "map_first_last", issue = "62924")]
ba9703b0
XL
789 pub fn pop_last(&mut self) -> Option<(K, V)> {
790 self.last_entry().map(|entry| entry.remove_entry())
60c5eb7d
XL
791 }
792
cc61c64b 793 /// Returns `true` if the map contains a value for the specified key.
1a4d82fc
JJ
794 ///
795 /// The key may be any borrowed form of the map's key type, but the ordering
796 /// on the borrowed form *must* match the ordering on the key type.
797 ///
798 /// # Examples
799 ///
54a0048b
SL
800 /// Basic usage:
801 ///
1a4d82fc
JJ
802 /// ```
803 /// use std::collections::BTreeMap;
804 ///
805 /// let mut map = BTreeMap::new();
85aaf69f 806 /// map.insert(1, "a");
1a4d82fc
JJ
807 /// assert_eq!(map.contains_key(&1), true);
808 /// assert_eq!(map.contains_key(&2), false);
809 /// ```
85aaf69f 810 #[stable(feature = "rust1", since = "1.0.0")]
3157f602 811 pub fn contains_key<Q: ?Sized>(&self, key: &Q) -> bool
dfeec247
XL
812 where
813 K: Borrow<Q>,
814 Q: Ord,
3157f602 815 {
1a4d82fc
JJ
816 self.get(key).is_some()
817 }
818
819 /// Returns a mutable reference to the value corresponding to the key.
820 ///
821 /// The key may be any borrowed form of the map's key type, but the ordering
822 /// on the borrowed form *must* match the ordering on the key type.
823 ///
824 /// # Examples
825 ///
54a0048b
SL
826 /// Basic usage:
827 ///
1a4d82fc
JJ
828 /// ```
829 /// use std::collections::BTreeMap;
830 ///
831 /// let mut map = BTreeMap::new();
85aaf69f 832 /// map.insert(1, "a");
9346a6ac
AL
833 /// if let Some(x) = map.get_mut(&1) {
834 /// *x = "b";
1a4d82fc 835 /// }
c34b1796 836 /// assert_eq!(map[&1], "b");
1a4d82fc
JJ
837 /// ```
838 // See `get` for implementation notes, this is basically a copy-paste with mut's added
85aaf69f 839 #[stable(feature = "rust1", since = "1.0.0")]
3157f602 840 pub fn get_mut<Q: ?Sized>(&mut self, key: &Q) -> Option<&mut V>
dfeec247
XL
841 where
842 K: Borrow<Q>,
843 Q: Ord,
3157f602 844 {
ba9703b0 845 match search::search_tree(self.root.as_mut()?.as_mut(), key) {
9cc50fc6 846 Found(handle) => Some(handle.into_kv_mut().1),
3157f602 847 GoDown(_) => None,
1a4d82fc
JJ
848 }
849 }
850
b039eaaf
SL
851 /// Inserts a key-value pair into the map.
852 ///
853 /// If the map did not have this key present, `None` is returned.
854 ///
7453a54e
SL
855 /// If the map did have this key present, the value is updated, and the old
856 /// value is returned. The key is not updated, though; this matters for
857 /// types that can be `==` without being identical. See the [module-level
858 /// documentation] for more.
b039eaaf
SL
859 ///
860 /// [module-level documentation]: index.html#insert-and-complex-keys
1a4d82fc
JJ
861 ///
862 /// # Examples
863 ///
54a0048b
SL
864 /// Basic usage:
865 ///
1a4d82fc
JJ
866 /// ```
867 /// use std::collections::BTreeMap;
868 ///
869 /// let mut map = BTreeMap::new();
85aaf69f 870 /// assert_eq!(map.insert(37, "a"), None);
1a4d82fc
JJ
871 /// assert_eq!(map.is_empty(), false);
872 ///
873 /// map.insert(37, "b");
874 /// assert_eq!(map.insert(37, "c"), Some("b"));
c34b1796 875 /// assert_eq!(map[&37], "c");
1a4d82fc 876 /// ```
85aaf69f 877 #[stable(feature = "rust1", since = "1.0.0")]
9cc50fc6
SL
878 pub fn insert(&mut self, key: K, value: V) -> Option<V> {
879 match self.entry(key) {
880 Occupied(mut entry) => Some(entry.insert(value)),
881 Vacant(entry) => {
882 entry.insert(value);
883 None
1a4d82fc
JJ
884 }
885 }
886 }
887
1a4d82fc
JJ
888 /// Removes a key from the map, returning the value at the key if the key
889 /// was previously in the map.
890 ///
891 /// The key may be any borrowed form of the map's key type, but the ordering
892 /// on the borrowed form *must* match the ordering on the key type.
893 ///
894 /// # Examples
895 ///
54a0048b
SL
896 /// Basic usage:
897 ///
1a4d82fc
JJ
898 /// ```
899 /// use std::collections::BTreeMap;
900 ///
901 /// let mut map = BTreeMap::new();
85aaf69f 902 /// map.insert(1, "a");
1a4d82fc
JJ
903 /// assert_eq!(map.remove(&1), Some("a"));
904 /// assert_eq!(map.remove(&1), None);
905 /// ```
85aaf69f 906 #[stable(feature = "rust1", since = "1.0.0")]
3157f602 907 pub fn remove<Q: ?Sized>(&mut self, key: &Q) -> Option<V>
74b04a01
XL
908 where
909 K: Borrow<Q>,
910 Q: Ord,
911 {
912 self.remove_entry(key).map(|(_, v)| v)
913 }
914
915 /// Removes a key from the map, returning the stored key and value if the key
916 /// was previously in the map.
917 ///
918 /// The key may be any borrowed form of the map's key type, but the ordering
919 /// on the borrowed form *must* match the ordering on the key type.
920 ///
921 /// # Examples
922 ///
923 /// Basic usage:
924 ///
925 /// ```
926 /// #![feature(btreemap_remove_entry)]
927 /// use std::collections::BTreeMap;
928 ///
929 /// let mut map = BTreeMap::new();
930 /// map.insert(1, "a");
931 /// assert_eq!(map.remove_entry(&1), Some((1, "a")));
932 /// assert_eq!(map.remove_entry(&1), None);
933 /// ```
934 #[unstable(feature = "btreemap_remove_entry", issue = "66714")]
935 pub fn remove_entry<Q: ?Sized>(&mut self, key: &Q) -> Option<(K, V)>
dfeec247
XL
936 where
937 K: Borrow<Q>,
938 Q: Ord,
3157f602 939 {
ba9703b0 940 match search::search_tree(self.root.as_mut()?.as_mut(), key) {
dfeec247 941 Found(handle) => Some(
74b04a01
XL
942 OccupiedEntry { handle, length: &mut self.length, _marker: PhantomData }
943 .remove_entry(),
dfeec247 944 ),
3157f602 945 GoDown(_) => None,
1a4d82fc
JJ
946 }
947 }
85aaf69f 948
a7813a04
XL
949 /// Moves all elements from `other` into `Self`, leaving `other` empty.
950 ///
951 /// # Examples
952 ///
953 /// ```
a7813a04
XL
954 /// use std::collections::BTreeMap;
955 ///
956 /// let mut a = BTreeMap::new();
957 /// a.insert(1, "a");
958 /// a.insert(2, "b");
959 /// a.insert(3, "c");
960 ///
961 /// let mut b = BTreeMap::new();
962 /// b.insert(3, "d");
963 /// b.insert(4, "e");
964 /// b.insert(5, "f");
965 ///
966 /// a.append(&mut b);
967 ///
968 /// assert_eq!(a.len(), 5);
969 /// assert_eq!(b.len(), 0);
970 ///
971 /// assert_eq!(a[&1], "a");
972 /// assert_eq!(a[&2], "b");
973 /// assert_eq!(a[&3], "d");
974 /// assert_eq!(a[&4], "e");
975 /// assert_eq!(a[&5], "f");
976 /// ```
3157f602 977 #[stable(feature = "btree_append", since = "1.11.0")]
a7813a04
XL
978 pub fn append(&mut self, other: &mut Self) {
979 // Do we have to append anything at all?
416331ca 980 if other.is_empty() {
a7813a04
XL
981 return;
982 }
983
984 // We can just swap `self` and `other` if `self` is empty.
416331ca 985 if self.is_empty() {
a7813a04
XL
986 mem::swap(self, other);
987 return;
988 }
989
990 // First, we merge `self` and `other` into a sorted sequence in linear time.
416331ca
XL
991 let self_iter = mem::take(self).into_iter();
992 let other_iter = mem::take(other).into_iter();
dfeec247 993 let iter = MergeIter { left: self_iter.peekable(), right: other_iter.peekable() };
a7813a04
XL
994
995 // Second, we build a tree from the sorted sequence in linear time.
996 self.from_sorted_iter(iter);
997 self.fix_right_edge();
998 }
999
32a655c1
SL
1000 /// Constructs a double-ended iterator over a sub-range of elements in the map.
1001 /// The simplest way is to use the range syntax `min..max`, thus `range(min..max)` will
1002 /// yield elements from min (inclusive) to max (exclusive).
1003 /// The range may also be entered as `(Bound<T>, Bound<T>)`, so for example
1004 /// `range((Excluded(4), Included(10)))` will yield a left-exclusive, right-inclusive
1005 /// range from 4 to 10.
9346a6ac 1006 ///
8bb4bdeb
XL
1007 /// # Panics
1008 ///
1009 /// Panics if range `start > end`.
1010 /// Panics if range `start == end` and both bounds are `Excluded`.
1011 ///
9346a6ac
AL
1012 /// # Examples
1013 ///
54a0048b
SL
1014 /// Basic usage:
1015 ///
9346a6ac
AL
1016 /// ```
1017 /// use std::collections::BTreeMap;
0531ce1d 1018 /// use std::ops::Bound::Included;
9346a6ac
AL
1019 ///
1020 /// let mut map = BTreeMap::new();
9cc50fc6
SL
1021 /// map.insert(3, "a");
1022 /// map.insert(5, "b");
1023 /// map.insert(8, "c");
32a655c1 1024 /// for (&key, &value) in map.range((Included(&4), Included(&8))) {
9346a6ac
AL
1025 /// println!("{}: {}", key, value);
1026 /// }
32a655c1 1027 /// assert_eq!(Some((&5, &"b")), map.range(4..).next());
9346a6ac 1028 /// ```
8bb4bdeb 1029 #[stable(feature = "btree_range", since = "1.17.0")]
9fa01778 1030 pub fn range<T: ?Sized, R>(&self, range: R) -> Range<'_, K, V>
dfeec247
XL
1031 where
1032 T: Ord,
1033 K: Borrow<T>,
1034 R: RangeBounds<T>,
9cc50fc6 1035 {
ba9703b0
XL
1036 if let Some(root) = &self.root {
1037 let root1 = root.as_ref();
1038 let root2 = root.as_ref();
1039 let (f, b) = range_search(root1, root2, range);
9cc50fc6 1040
ba9703b0
XL
1041 Range { front: Some(f), back: Some(b) }
1042 } else {
1043 Range { front: None, back: None }
1044 }
9cc50fc6
SL
1045 }
1046
32a655c1
SL
1047 /// Constructs a mutable double-ended iterator over a sub-range of elements in the map.
1048 /// The simplest way is to use the range syntax `min..max`, thus `range(min..max)` will
1049 /// yield elements from min (inclusive) to max (exclusive).
1050 /// The range may also be entered as `(Bound<T>, Bound<T>)`, so for example
1051 /// `range((Excluded(4), Included(10)))` will yield a left-exclusive, right-inclusive
1052 /// range from 4 to 10.
9cc50fc6 1053 ///
8bb4bdeb
XL
1054 /// # Panics
1055 ///
1056 /// Panics if range `start > end`.
1057 /// Panics if range `start == end` and both bounds are `Excluded`.
1058 ///
9cc50fc6
SL
1059 /// # Examples
1060 ///
54a0048b
SL
1061 /// Basic usage:
1062 ///
9cc50fc6 1063 /// ```
9cc50fc6 1064 /// use std::collections::BTreeMap;
9cc50fc6 1065 ///
a1dfa0c6
XL
1066 /// let mut map: BTreeMap<&str, i32> = ["Alice", "Bob", "Carol", "Cheryl"]
1067 /// .iter()
1068 /// .map(|&s| (s, 0))
1069 /// .collect();
32a655c1 1070 /// for (_, balance) in map.range_mut("B".."Cheryl") {
9cc50fc6
SL
1071 /// *balance += 100;
1072 /// }
1073 /// for (name, balance) in &map {
1074 /// println!("{} => {}", name, balance);
1075 /// }
1076 /// ```
8bb4bdeb 1077 #[stable(feature = "btree_range", since = "1.17.0")]
9fa01778 1078 pub fn range_mut<T: ?Sized, R>(&mut self, range: R) -> RangeMut<'_, K, V>
dfeec247
XL
1079 where
1080 T: Ord,
1081 K: Borrow<T>,
1082 R: RangeBounds<T>,
9cc50fc6 1083 {
ba9703b0
XL
1084 if let Some(root) = &mut self.root {
1085 let root1 = root.as_mut();
1086 let root2 = unsafe { ptr::read(&root1) };
1087 let (f, b) = range_search(root1, root2, range);
9cc50fc6 1088
ba9703b0
XL
1089 RangeMut { front: Some(f), back: Some(b), _marker: PhantomData }
1090 } else {
1091 RangeMut { front: None, back: None, _marker: PhantomData }
1092 }
9cc50fc6
SL
1093 }
1094
1095 /// Gets the given key's corresponding entry in the map for in-place manipulation.
1096 ///
1097 /// # Examples
1098 ///
54a0048b
SL
1099 /// Basic usage:
1100 ///
9cc50fc6
SL
1101 /// ```
1102 /// use std::collections::BTreeMap;
1103 ///
1104 /// let mut count: BTreeMap<&str, usize> = BTreeMap::new();
1105 ///
1106 /// // count the number of occurrences of letters in the vec
1107 /// for x in vec!["a","b","a","c","a","b"] {
1108 /// *count.entry(x).or_insert(0) += 1;
1109 /// }
1110 ///
1111 /// assert_eq!(count["a"], 3);
1112 /// ```
1113 #[stable(feature = "rust1", since = "1.0.0")]
9fa01778 1114 pub fn entry(&mut self, key: K) -> Entry<'_, K, V> {
94b46f34
XL
1115 // FIXME(@porglezomp) Avoid allocating if we don't insert
1116 self.ensure_root_is_owned();
ba9703b0 1117 match search::search_tree(self.root.as_mut().unwrap().as_mut(), &key) {
3157f602 1118 Found(handle) => {
dfeec247 1119 Occupied(OccupiedEntry { handle, length: &mut self.length, _marker: PhantomData })
3157f602
XL
1120 }
1121 GoDown(handle) => {
dfeec247 1122 Vacant(VacantEntry { key, handle, length: &mut self.length, _marker: PhantomData })
3157f602 1123 }
9346a6ac 1124 }
85aaf69f 1125 }
a7813a04 1126
3157f602 1127 fn from_sorted_iter<I: Iterator<Item = (K, V)>>(&mut self, iter: I) {
94b46f34 1128 self.ensure_root_is_owned();
ba9703b0 1129 let mut cur_node = self.root.as_mut().unwrap().as_mut().last_leaf_edge().into_node();
a7813a04
XL
1130 // Iterate through all key-value pairs, pushing them into nodes at the right level.
1131 for (key, value) in iter {
1132 // Try to push key-value pair into the current leaf node.
1133 if cur_node.len() < node::CAPACITY {
1134 cur_node.push(key, value);
1135 } else {
1136 // No space left, go up and push there.
1137 let mut open_node;
1138 let mut test_node = cur_node.forget_type();
1139 loop {
1140 match test_node.ascend() {
1141 Ok(parent) => {
1142 let parent = parent.into_node();
1143 if parent.len() < node::CAPACITY {
1144 // Found a node with space left, push here.
1145 open_node = parent;
1146 break;
1147 } else {
1148 // Go up again.
1149 test_node = parent.forget_type();
1150 }
3157f602 1151 }
a7813a04
XL
1152 Err(node) => {
1153 // We are at the top, create a new root node and push there.
1154 open_node = node.into_root_mut().push_level();
1155 break;
3157f602 1156 }
a7813a04
XL
1157 }
1158 }
1159
1160 // Push key-value pair and new right subtree.
1161 let tree_height = open_node.height() - 1;
1162 let mut right_tree = node::Root::new_leaf();
1163 for _ in 0..tree_height {
1164 right_tree.push_level();
1165 }
1166 open_node.push(key, value, right_tree);
1167
1168 // Go down to the right-most leaf again.
74b04a01 1169 cur_node = open_node.forget_type().last_leaf_edge().into_node();
a7813a04
XL
1170 }
1171
1172 self.length += 1;
1173 }
1174 }
1175
1176 fn fix_right_edge(&mut self) {
1177 // Handle underfull nodes, start from the top.
ba9703b0 1178 let mut cur_node = self.root.as_mut().unwrap().as_mut();
a7813a04
XL
1179 while let Internal(internal) = cur_node.force() {
1180 // Check if right-most child is underfull.
1181 let mut last_edge = internal.last_edge();
1182 let right_child_len = last_edge.reborrow().descend().len();
3157f602 1183 if right_child_len < node::MIN_LEN {
a7813a04
XL
1184 // We need to steal.
1185 let mut last_kv = match last_edge.left_kv() {
1186 Ok(left) => left,
1187 Err(_) => unreachable!(),
1188 };
3157f602 1189 last_kv.bulk_steal_left(node::MIN_LEN - right_child_len);
a7813a04
XL
1190 last_edge = last_kv.right_edge();
1191 }
1192
1193 // Go further down.
1194 cur_node = last_edge.descend();
1195 }
1196 }
3157f602
XL
1197
1198 /// Splits the collection into two at the given key. Returns everything after the given key,
1199 /// including the key.
1200 ///
1201 /// # Examples
1202 ///
1203 /// Basic usage:
1204 ///
1205 /// ```
1206 /// use std::collections::BTreeMap;
1207 ///
1208 /// let mut a = BTreeMap::new();
1209 /// a.insert(1, "a");
1210 /// a.insert(2, "b");
1211 /// a.insert(3, "c");
1212 /// a.insert(17, "d");
1213 /// a.insert(41, "e");
1214 ///
1215 /// let b = a.split_off(&3);
1216 ///
1217 /// assert_eq!(a.len(), 2);
1218 /// assert_eq!(b.len(), 3);
1219 ///
1220 /// assert_eq!(a[&1], "a");
1221 /// assert_eq!(a[&2], "b");
1222 ///
1223 /// assert_eq!(b[&3], "c");
1224 /// assert_eq!(b[&17], "d");
1225 /// assert_eq!(b[&41], "e");
1226 /// ```
1227 #[stable(feature = "btree_split_off", since = "1.11.0")]
1228 pub fn split_off<Q: ?Sized + Ord>(&mut self, key: &Q) -> Self
dfeec247
XL
1229 where
1230 K: Borrow<Q>,
3157f602
XL
1231 {
1232 if self.is_empty() {
1233 return Self::new();
1234 }
1235
1236 let total_num = self.len();
1237
1238 let mut right = Self::new();
ba9703b0
XL
1239 let right_root = right.ensure_root_is_owned();
1240 for _ in 0..(self.root.as_ref().unwrap().as_ref().height()) {
1241 right_root.push_level();
3157f602
XL
1242 }
1243
1244 {
ba9703b0
XL
1245 let mut left_node = self.root.as_mut().unwrap().as_mut();
1246 let mut right_node = right.root.as_mut().unwrap().as_mut();
3157f602
XL
1247
1248 loop {
1249 let mut split_edge = match search::search_node(left_node, key) {
1250 // key is going to the right tree
1251 Found(handle) => handle.left_edge(),
1252 GoDown(handle) => handle,
1253 };
1254
1255 split_edge.move_suffix(&mut right_node);
1256
1257 match (split_edge.force(), right_node.force()) {
1258 (Internal(edge), Internal(node)) => {
1259 left_node = edge.descend();
1260 right_node = node.first_edge().descend();
1261 }
1262 (Leaf(_), Leaf(_)) => {
1263 break;
1264 }
1265 _ => {
1266 unreachable!();
1267 }
1268 }
1269 }
1270 }
1271
1272 self.fix_right_border();
1273 right.fix_left_border();
1274
ba9703b0
XL
1275 if self.root.as_ref().unwrap().as_ref().height()
1276 < right.root.as_ref().unwrap().as_ref().height()
1277 {
3157f602
XL
1278 self.recalc_length();
1279 right.length = total_num - self.len();
1280 } else {
1281 right.recalc_length();
1282 self.length = total_num - right.len();
1283 }
1284
1285 right
1286 }
1287
ba9703b0
XL
1288 /// Creates an iterator which uses a closure to determine if an element should be removed.
1289 ///
1290 /// If the closure returns true, the element is removed from the map and yielded.
1291 /// If the closure returns false, or panics, the element remains in the map and will not be
1292 /// yielded.
1293 ///
1294 /// Note that `drain_filter` lets you mutate every value in the filter closure, regardless of
1295 /// whether you choose to keep or remove it.
1296 ///
1297 /// If the iterator is only partially consumed or not consumed at all, each of the remaining
1298 /// elements will still be subjected to the closure and removed and dropped if it returns true.
1299 ///
1300 /// It is unspecified how many more elements will be subjected to the closure
1301 /// if a panic occurs in the closure, or a panic occurs while dropping an element,
1302 /// or if the `DrainFilter` value is leaked.
1303 ///
1304 /// # Examples
1305 ///
1306 /// Splitting a map into even and odd keys, reusing the original map:
1307 ///
1308 /// ```
1309 /// #![feature(btree_drain_filter)]
1310 /// use std::collections::BTreeMap;
1311 ///
1312 /// let mut map: BTreeMap<i32, i32> = (0..8).map(|x| (x, x)).collect();
1313 /// let evens: BTreeMap<_, _> = map.drain_filter(|k, _v| k % 2 == 0).collect();
1314 /// let odds = map;
1315 /// assert_eq!(evens.keys().copied().collect::<Vec<_>>(), vec![0, 2, 4, 6]);
1316 /// assert_eq!(odds.keys().copied().collect::<Vec<_>>(), vec![1, 3, 5, 7]);
1317 /// ```
1318 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1319 pub fn drain_filter<F>(&mut self, pred: F) -> DrainFilter<'_, K, V, F>
1320 where
1321 F: FnMut(&K, &mut V) -> bool,
1322 {
1323 DrainFilter { pred, inner: self.drain_filter_inner() }
1324 }
1325 pub(super) fn drain_filter_inner(&mut self) -> DrainFilterInner<'_, K, V> {
1326 let front = self.root.as_mut().map(|r| r.as_mut().first_leaf_edge());
1327 DrainFilterInner { length: &mut self.length, cur_leaf_edge: front }
1328 }
1329
3157f602
XL
1330 /// Calculates the number of elements if it is incorrect.
1331 fn recalc_length(&mut self) {
dfeec247
XL
1332 fn dfs<'a, K, V>(node: NodeRef<marker::Immut<'a>, K, V, marker::LeafOrInternal>) -> usize
1333 where
1334 K: 'a,
1335 V: 'a,
8faf50e0 1336 {
3157f602
XL
1337 let mut res = node.len();
1338
1339 if let Internal(node) = node.force() {
1340 let mut edge = node.first_edge();
1341 loop {
1342 res += dfs(edge.reborrow().descend());
1343 match edge.right_kv() {
1344 Ok(right_kv) => {
1345 edge = right_kv.right_edge();
1346 }
1347 Err(_) => {
1348 break;
1349 }
1350 }
1351 }
1352 }
1353
1354 res
1355 }
1356
ba9703b0 1357 self.length = dfs(self.root.as_ref().unwrap().as_ref());
3157f602
XL
1358 }
1359
1360 /// Removes empty levels on the top.
1361 fn fix_top(&mut self) {
1362 loop {
1363 {
ba9703b0 1364 let node = self.root.as_ref().unwrap().as_ref();
3157f602
XL
1365 if node.height() == 0 || node.len() > 0 {
1366 break;
1367 }
1368 }
ba9703b0 1369 self.root.as_mut().unwrap().pop_level();
3157f602
XL
1370 }
1371 }
1372
1373 fn fix_right_border(&mut self) {
1374 self.fix_top();
1375
1376 {
ba9703b0 1377 let mut cur_node = self.root.as_mut().unwrap().as_mut();
3157f602
XL
1378
1379 while let Internal(node) = cur_node.force() {
1380 let mut last_kv = node.last_kv();
1381
1382 if last_kv.can_merge() {
1383 cur_node = last_kv.merge().descend();
1384 } else {
1385 let right_len = last_kv.reborrow().right_edge().descend().len();
1386 // `MINLEN + 1` to avoid readjust if merge happens on the next level.
1387 if right_len < node::MIN_LEN + 1 {
1388 last_kv.bulk_steal_left(node::MIN_LEN + 1 - right_len);
1389 }
1390 cur_node = last_kv.right_edge().descend();
1391 }
1392 }
1393 }
1394
1395 self.fix_top();
1396 }
1397
1398 /// The symmetric clone of `fix_right_border`.
1399 fn fix_left_border(&mut self) {
1400 self.fix_top();
1401
1402 {
ba9703b0 1403 let mut cur_node = self.root.as_mut().unwrap().as_mut();
3157f602
XL
1404
1405 while let Internal(node) = cur_node.force() {
1406 let mut first_kv = node.first_kv();
1407
1408 if first_kv.can_merge() {
1409 cur_node = first_kv.merge().descend();
1410 } else {
1411 let left_len = first_kv.reborrow().left_edge().descend().len();
1412 if left_len < node::MIN_LEN + 1 {
1413 first_kv.bulk_steal_right(node::MIN_LEN + 1 - left_len);
1414 }
1415 cur_node = first_kv.left_edge().descend();
1416 }
1417 }
1418 }
1419
1420 self.fix_top();
1421 }
85aaf69f
SL
1422}
1423
c30ab7b3 1424#[stable(feature = "rust1", since = "1.0.0")]
9cc50fc6 1425impl<'a, K: 'a, V: 'a> IntoIterator for &'a BTreeMap<K, V> {
85aaf69f
SL
1426 type Item = (&'a K, &'a V);
1427 type IntoIter = Iter<'a, K, V>;
1428
1429 fn into_iter(self) -> Iter<'a, K, V> {
1430 self.iter()
1431 }
1432}
1433
c30ab7b3 1434#[stable(feature = "rust1", since = "1.0.0")]
9cc50fc6
SL
1435impl<'a, K: 'a, V: 'a> Iterator for Iter<'a, K, V> {
1436 type Item = (&'a K, &'a V);
85aaf69f 1437
9cc50fc6
SL
1438 fn next(&mut self) -> Option<(&'a K, &'a V)> {
1439 if self.length == 0 {
1440 None
1441 } else {
1442 self.length -= 1;
1443 unsafe { Some(self.range.next_unchecked()) }
1444 }
85aaf69f 1445 }
85aaf69f 1446
9cc50fc6
SL
1447 fn size_hint(&self) -> (usize, Option<usize>) {
1448 (self.length, Some(self.length))
1449 }
416331ca
XL
1450
1451 fn last(mut self) -> Option<(&'a K, &'a V)> {
1452 self.next_back()
1453 }
1a4d82fc
JJ
1454}
1455
0531ce1d 1456#[stable(feature = "fused", since = "1.26.0")]
9fa01778 1457impl<K, V> FusedIterator for Iter<'_, K, V> {}
9e0c209e 1458
c30ab7b3 1459#[stable(feature = "rust1", since = "1.0.0")]
9cc50fc6
SL
1460impl<'a, K: 'a, V: 'a> DoubleEndedIterator for Iter<'a, K, V> {
1461 fn next_back(&mut self) -> Option<(&'a K, &'a V)> {
1462 if self.length == 0 {
1463 None
1464 } else {
1465 self.length -= 1;
1466 unsafe { Some(self.range.next_back_unchecked()) }
85aaf69f
SL
1467 }
1468 }
9cc50fc6 1469}
85aaf69f 1470
c30ab7b3 1471#[stable(feature = "rust1", since = "1.0.0")]
9fa01778 1472impl<K, V> ExactSizeIterator for Iter<'_, K, V> {
3157f602
XL
1473 fn len(&self) -> usize {
1474 self.length
1475 }
9cc50fc6 1476}
1a4d82fc 1477
c30ab7b3 1478#[stable(feature = "rust1", since = "1.0.0")]
9fa01778
XL
1479impl<K, V> Clone for Iter<'_, K, V> {
1480 fn clone(&self) -> Self {
dfeec247 1481 Iter { range: self.range.clone(), length: self.length }
1a4d82fc 1482 }
9cc50fc6 1483}
1a4d82fc 1484
c30ab7b3 1485#[stable(feature = "rust1", since = "1.0.0")]
9cc50fc6
SL
1486impl<'a, K: 'a, V: 'a> IntoIterator for &'a mut BTreeMap<K, V> {
1487 type Item = (&'a K, &'a mut V);
1488 type IntoIter = IterMut<'a, K, V>;
1489
1490 fn into_iter(self) -> IterMut<'a, K, V> {
1491 self.iter_mut()
1a4d82fc 1492 }
9cc50fc6 1493}
1a4d82fc 1494
c30ab7b3 1495#[stable(feature = "rust1", since = "1.0.0")]
9cc50fc6
SL
1496impl<'a, K: 'a, V: 'a> Iterator for IterMut<'a, K, V> {
1497 type Item = (&'a K, &'a mut V);
1a4d82fc 1498
9cc50fc6
SL
1499 fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
1500 if self.length == 0 {
1501 None
1502 } else {
1503 self.length -= 1;
74b04a01
XL
1504 let (k, v) = unsafe { self.range.next_unchecked() };
1505 Some((k, v)) // coerce k from `&mut K` to `&K`
9cc50fc6 1506 }
1a4d82fc
JJ
1507 }
1508
9cc50fc6
SL
1509 fn size_hint(&self) -> (usize, Option<usize>) {
1510 (self.length, Some(self.length))
1a4d82fc 1511 }
416331ca
XL
1512
1513 fn last(mut self) -> Option<(&'a K, &'a mut V)> {
1514 self.next_back()
1515 }
9cc50fc6 1516}
1a4d82fc 1517
c30ab7b3 1518#[stable(feature = "rust1", since = "1.0.0")]
9cc50fc6
SL
1519impl<'a, K: 'a, V: 'a> DoubleEndedIterator for IterMut<'a, K, V> {
1520 fn next_back(&mut self) -> Option<(&'a K, &'a mut V)> {
1521 if self.length == 0 {
1522 None
1523 } else {
1524 self.length -= 1;
74b04a01
XL
1525 let (k, v) = unsafe { self.range.next_back_unchecked() };
1526 Some((k, v)) // coerce k from `&mut K` to `&K`
9cc50fc6 1527 }
1a4d82fc 1528 }
9cc50fc6 1529}
1a4d82fc 1530
c30ab7b3 1531#[stable(feature = "rust1", since = "1.0.0")]
9fa01778 1532impl<K, V> ExactSizeIterator for IterMut<'_, K, V> {
3157f602
XL
1533 fn len(&self) -> usize {
1534 self.length
1535 }
9cc50fc6 1536}
1a4d82fc 1537
0531ce1d 1538#[stable(feature = "fused", since = "1.26.0")]
9fa01778 1539impl<K, V> FusedIterator for IterMut<'_, K, V> {}
9e0c209e 1540
c30ab7b3 1541#[stable(feature = "rust1", since = "1.0.0")]
9cc50fc6
SL
1542impl<K, V> IntoIterator for BTreeMap<K, V> {
1543 type Item = (K, V);
1544 type IntoIter = IntoIter<K, V>;
1a4d82fc 1545
9cc50fc6 1546 fn into_iter(self) -> IntoIter<K, V> {
ba9703b0
XL
1547 let mut me = ManuallyDrop::new(self);
1548 if let Some(root) = me.root.as_mut() {
1549 let root1 = unsafe { ptr::read(root).into_ref() };
1550 let root2 = unsafe { ptr::read(root).into_ref() };
1551 let len = me.length;
1552
1553 IntoIter {
1554 front: Some(root1.first_leaf_edge()),
1555 back: Some(root2.last_leaf_edge()),
1556 length: len,
1557 }
1558 } else {
1559 IntoIter { front: None, back: None, length: 0 }
1560 }
1a4d82fc 1561 }
9cc50fc6 1562}
1a4d82fc 1563
c30ab7b3 1564#[stable(feature = "btree_drop", since = "1.7.0")]
9cc50fc6
SL
1565impl<K, V> Drop for IntoIter<K, V> {
1566 fn drop(&mut self) {
74b04a01
XL
1567 struct DropGuard<'a, K, V>(&'a mut IntoIter<K, V>);
1568
1569 impl<'a, K, V> Drop for DropGuard<'a, K, V> {
1570 fn drop(&mut self) {
1571 // Continue the same loop we perform below. This only runs when unwinding, so we
1572 // don't have to care about panics this time (they'll abort).
1573 while let Some(_) = self.0.next() {}
1574
74b04a01 1575 unsafe {
ba9703b0
XL
1576 let mut node =
1577 unwrap_unchecked(ptr::read(&self.0.front)).into_node().forget_type();
74b04a01
XL
1578 while let Some(parent) = node.deallocate_and_ascend() {
1579 node = parent.into_node().forget_type();
1580 }
1581 }
1582 }
1583 }
1584
1585 while let Some(pair) = self.next() {
1586 let guard = DropGuard(self);
1587 drop(pair);
1588 mem::forget(guard);
1589 }
1590
9cc50fc6 1591 unsafe {
ba9703b0
XL
1592 if let Some(front) = ptr::read(&self.front) {
1593 let mut node = front.into_node().forget_type();
1594 // Most of the nodes have been deallocated while traversing
1595 // but one pile from a leaf up to the root is left standing.
1596 while let Some(parent) = node.deallocate_and_ascend() {
1597 node = parent.into_node().forget_type();
1598 }
1a4d82fc
JJ
1599 }
1600 }
1601 }
9cc50fc6 1602}
1a4d82fc 1603
c30ab7b3 1604#[stable(feature = "rust1", since = "1.0.0")]
9cc50fc6
SL
1605impl<K, V> Iterator for IntoIter<K, V> {
1606 type Item = (K, V);
1a4d82fc 1607
9cc50fc6
SL
1608 fn next(&mut self) -> Option<(K, V)> {
1609 if self.length == 0 {
74b04a01 1610 None
9cc50fc6
SL
1611 } else {
1612 self.length -= 1;
ba9703b0 1613 Some(unsafe { self.front.as_mut().unwrap().next_unchecked() })
1a4d82fc
JJ
1614 }
1615 }
1616
9cc50fc6
SL
1617 fn size_hint(&self) -> (usize, Option<usize>) {
1618 (self.length, Some(self.length))
1619 }
1620}
1621
c30ab7b3 1622#[stable(feature = "rust1", since = "1.0.0")]
9cc50fc6
SL
1623impl<K, V> DoubleEndedIterator for IntoIter<K, V> {
1624 fn next_back(&mut self) -> Option<(K, V)> {
1625 if self.length == 0 {
74b04a01 1626 None
9cc50fc6
SL
1627 } else {
1628 self.length -= 1;
ba9703b0 1629 Some(unsafe { self.back.as_mut().unwrap().next_back_unchecked() })
1a4d82fc
JJ
1630 }
1631 }
1632}
1633
c30ab7b3 1634#[stable(feature = "rust1", since = "1.0.0")]
9cc50fc6 1635impl<K, V> ExactSizeIterator for IntoIter<K, V> {
3157f602
XL
1636 fn len(&self) -> usize {
1637 self.length
1638 }
1a4d82fc
JJ
1639}
1640
0531ce1d 1641#[stable(feature = "fused", since = "1.26.0")]
9e0c209e
SL
1642impl<K, V> FusedIterator for IntoIter<K, V> {}
1643
c30ab7b3 1644#[stable(feature = "rust1", since = "1.0.0")]
9cc50fc6
SL
1645impl<'a, K, V> Iterator for Keys<'a, K, V> {
1646 type Item = &'a K;
1647
1648 fn next(&mut self) -> Option<&'a K> {
1649 self.inner.next().map(|(k, _)| k)
1a4d82fc 1650 }
1a4d82fc 1651
9cc50fc6
SL
1652 fn size_hint(&self) -> (usize, Option<usize>) {
1653 self.inner.size_hint()
62682a34 1654 }
416331ca
XL
1655
1656 fn last(mut self) -> Option<&'a K> {
1657 self.next_back()
1658 }
62682a34
SL
1659}
1660
c30ab7b3 1661#[stable(feature = "rust1", since = "1.0.0")]
9cc50fc6
SL
1662impl<'a, K, V> DoubleEndedIterator for Keys<'a, K, V> {
1663 fn next_back(&mut self) -> Option<&'a K> {
1664 self.inner.next_back().map(|(k, _)| k)
1a4d82fc
JJ
1665 }
1666}
1667
c30ab7b3 1668#[stable(feature = "rust1", since = "1.0.0")]
9fa01778 1669impl<K, V> ExactSizeIterator for Keys<'_, K, V> {
9cc50fc6
SL
1670 fn len(&self) -> usize {
1671 self.inner.len()
1a4d82fc
JJ
1672 }
1673}
1674
0531ce1d 1675#[stable(feature = "fused", since = "1.26.0")]
9fa01778 1676impl<K, V> FusedIterator for Keys<'_, K, V> {}
9e0c209e 1677
c30ab7b3 1678#[stable(feature = "rust1", since = "1.0.0")]
9fa01778
XL
1679impl<K, V> Clone for Keys<'_, K, V> {
1680 fn clone(&self) -> Self {
3157f602 1681 Keys { inner: self.inner.clone() }
1a4d82fc
JJ
1682 }
1683}
1684
c30ab7b3 1685#[stable(feature = "rust1", since = "1.0.0")]
9cc50fc6
SL
1686impl<'a, K, V> Iterator for Values<'a, K, V> {
1687 type Item = &'a V;
1a4d82fc 1688
9cc50fc6
SL
1689 fn next(&mut self) -> Option<&'a V> {
1690 self.inner.next().map(|(_, v)| v)
1a4d82fc 1691 }
1a4d82fc 1692
9cc50fc6
SL
1693 fn size_hint(&self) -> (usize, Option<usize>) {
1694 self.inner.size_hint()
1a4d82fc 1695 }
416331ca
XL
1696
1697 fn last(mut self) -> Option<&'a V> {
1698 self.next_back()
1699 }
1a4d82fc
JJ
1700}
1701
c30ab7b3 1702#[stable(feature = "rust1", since = "1.0.0")]
9cc50fc6
SL
1703impl<'a, K, V> DoubleEndedIterator for Values<'a, K, V> {
1704 fn next_back(&mut self) -> Option<&'a V> {
1705 self.inner.next_back().map(|(_, v)| v)
1a4d82fc
JJ
1706 }
1707}
1708
c30ab7b3 1709#[stable(feature = "rust1", since = "1.0.0")]
9fa01778 1710impl<K, V> ExactSizeIterator for Values<'_, K, V> {
9cc50fc6
SL
1711 fn len(&self) -> usize {
1712 self.inner.len()
1a4d82fc
JJ
1713 }
1714}
1715
0531ce1d 1716#[stable(feature = "fused", since = "1.26.0")]
9fa01778 1717impl<K, V> FusedIterator for Values<'_, K, V> {}
9e0c209e 1718
c30ab7b3 1719#[stable(feature = "rust1", since = "1.0.0")]
9fa01778
XL
1720impl<K, V> Clone for Values<'_, K, V> {
1721 fn clone(&self) -> Self {
3157f602 1722 Values { inner: self.inner.clone() }
1a4d82fc
JJ
1723 }
1724}
1725
ba9703b0
XL
1726/// An iterator produced by calling `drain_filter` on BTreeMap.
1727#[unstable(feature = "btree_drain_filter", issue = "70530")]
1728pub struct DrainFilter<'a, K, V, F>
1729where
1730 K: 'a,
1731 V: 'a,
1732 F: 'a + FnMut(&K, &mut V) -> bool,
1733{
1734 pred: F,
1735 inner: DrainFilterInner<'a, K, V>,
1736}
1737pub(super) struct DrainFilterInner<'a, K: 'a, V: 'a> {
1738 length: &'a mut usize,
1739 cur_leaf_edge: Option<Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge>>,
1740}
1741
1742#[unstable(feature = "btree_drain_filter", issue = "70530")]
1743impl<K, V, F> Drop for DrainFilter<'_, K, V, F>
1744where
1745 F: FnMut(&K, &mut V) -> bool,
1746{
1747 fn drop(&mut self) {
1748 self.for_each(drop);
1749 }
1750}
1751
1752#[unstable(feature = "btree_drain_filter", issue = "70530")]
1753impl<K, V, F> fmt::Debug for DrainFilter<'_, K, V, F>
1754where
1755 K: fmt::Debug,
1756 V: fmt::Debug,
1757 F: FnMut(&K, &mut V) -> bool,
1758{
1759 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1760 f.debug_tuple("DrainFilter").field(&self.inner.peek()).finish()
1761 }
1762}
1763
1764#[unstable(feature = "btree_drain_filter", issue = "70530")]
1765impl<K, V, F> Iterator for DrainFilter<'_, K, V, F>
1766where
1767 F: FnMut(&K, &mut V) -> bool,
1768{
1769 type Item = (K, V);
1770
1771 fn next(&mut self) -> Option<(K, V)> {
1772 self.inner.next(&mut self.pred)
1773 }
1774
1775 fn size_hint(&self) -> (usize, Option<usize>) {
1776 self.inner.size_hint()
1777 }
1778}
1779
1780impl<'a, K: 'a, V: 'a> DrainFilterInner<'a, K, V> {
1781 /// Allow Debug implementations to predict the next element.
1782 pub(super) fn peek(&self) -> Option<(&K, &V)> {
1783 let edge = self.cur_leaf_edge.as_ref()?;
1784 edge.reborrow().next_kv().ok().map(|kv| kv.into_kv())
1785 }
1786
1787 unsafe fn next_kv(
1788 &mut self,
1789 ) -> Option<Handle<NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal>, marker::KV>> {
1790 let edge = self.cur_leaf_edge.as_ref()?;
1791 ptr::read(edge).next_kv().ok()
1792 }
1793
1794 /// Implementation of a typical `DrainFilter::next` method, given the predicate.
1795 pub(super) fn next<F>(&mut self, pred: &mut F) -> Option<(K, V)>
1796 where
1797 F: FnMut(&K, &mut V) -> bool,
1798 {
1799 while let Some(mut kv) = unsafe { self.next_kv() } {
1800 let (k, v) = kv.kv_mut();
1801 if pred(k, v) {
1802 *self.length -= 1;
1803 let (k, v, leaf_edge_location) = kv.remove_kv_tracking();
1804 self.cur_leaf_edge = Some(leaf_edge_location);
1805 return Some((k, v));
1806 }
1807 self.cur_leaf_edge = Some(kv.next_leaf_edge());
1808 }
1809 None
1810 }
1811
1812 /// Implementation of a typical `DrainFilter::size_hint` method.
1813 pub(super) fn size_hint(&self) -> (usize, Option<usize>) {
1814 (0, Some(*self.length))
1815 }
1816}
1817
1818#[unstable(feature = "btree_drain_filter", issue = "70530")]
1819impl<K, V, F> FusedIterator for DrainFilter<'_, K, V, F> where F: FnMut(&K, &mut V) -> bool {}
1820
cc61c64b 1821#[stable(feature = "btree_range", since = "1.17.0")]
9cc50fc6
SL
1822impl<'a, K, V> Iterator for Range<'a, K, V> {
1823 type Item = (&'a K, &'a V);
1a4d82fc 1824
9cc50fc6 1825 fn next(&mut self) -> Option<(&'a K, &'a V)> {
74b04a01 1826 if self.is_empty() { None } else { unsafe { Some(self.next_unchecked()) } }
1a4d82fc 1827 }
416331ca
XL
1828
1829 fn last(mut self) -> Option<(&'a K, &'a V)> {
1830 self.next_back()
1831 }
1a4d82fc
JJ
1832}
1833
a7813a04 1834#[stable(feature = "map_values_mut", since = "1.10.0")]
54a0048b
SL
1835impl<'a, K, V> Iterator for ValuesMut<'a, K, V> {
1836 type Item = &'a mut V;
1837
1838 fn next(&mut self) -> Option<&'a mut V> {
1839 self.inner.next().map(|(_, v)| v)
1840 }
1841
1842 fn size_hint(&self) -> (usize, Option<usize>) {
1843 self.inner.size_hint()
1844 }
416331ca
XL
1845
1846 fn last(mut self) -> Option<&'a mut V> {
1847 self.next_back()
1848 }
54a0048b
SL
1849}
1850
a7813a04 1851#[stable(feature = "map_values_mut", since = "1.10.0")]
54a0048b
SL
1852impl<'a, K, V> DoubleEndedIterator for ValuesMut<'a, K, V> {
1853 fn next_back(&mut self) -> Option<&'a mut V> {
1854 self.inner.next_back().map(|(_, v)| v)
1855 }
1856}
1857
a7813a04 1858#[stable(feature = "map_values_mut", since = "1.10.0")]
9fa01778 1859impl<K, V> ExactSizeIterator for ValuesMut<'_, K, V> {
54a0048b
SL
1860 fn len(&self) -> usize {
1861 self.inner.len()
1862 }
1863}
1864
0531ce1d 1865#[stable(feature = "fused", since = "1.26.0")]
9fa01778 1866impl<K, V> FusedIterator for ValuesMut<'_, K, V> {}
9e0c209e 1867
9cc50fc6 1868impl<'a, K, V> Range<'a, K, V> {
74b04a01
XL
1869 fn is_empty(&self) -> bool {
1870 self.front == self.back
1871 }
1a4d82fc 1872
74b04a01 1873 unsafe fn next_unchecked(&mut self) -> (&'a K, &'a V) {
ba9703b0 1874 unwrap_unchecked(self.front.as_mut()).next_unchecked()
1a4d82fc 1875 }
9cc50fc6 1876}
1a4d82fc 1877
cc61c64b 1878#[stable(feature = "btree_range", since = "1.17.0")]
9cc50fc6
SL
1879impl<'a, K, V> DoubleEndedIterator for Range<'a, K, V> {
1880 fn next_back(&mut self) -> Option<(&'a K, &'a V)> {
74b04a01 1881 if self.is_empty() { None } else { Some(unsafe { self.next_back_unchecked() }) }
1a4d82fc
JJ
1882 }
1883}
1884
9cc50fc6
SL
1885impl<'a, K, V> Range<'a, K, V> {
1886 unsafe fn next_back_unchecked(&mut self) -> (&'a K, &'a V) {
ba9703b0 1887 unwrap_unchecked(self.back.as_mut()).next_back_unchecked()
1a4d82fc
JJ
1888 }
1889}
1890
0531ce1d 1891#[stable(feature = "fused", since = "1.26.0")]
9fa01778 1892impl<K, V> FusedIterator for Range<'_, K, V> {}
9e0c209e 1893
cc61c64b 1894#[stable(feature = "btree_range", since = "1.17.0")]
9fa01778
XL
1895impl<K, V> Clone for Range<'_, K, V> {
1896 fn clone(&self) -> Self {
dfeec247 1897 Range { front: self.front, back: self.back }
92a42be0 1898 }
1a4d82fc 1899}
1a4d82fc 1900
cc61c64b 1901#[stable(feature = "btree_range", since = "1.17.0")]
9cc50fc6 1902impl<'a, K, V> Iterator for RangeMut<'a, K, V> {
1a4d82fc
JJ
1903 type Item = (&'a K, &'a mut V);
1904
92a42be0 1905 fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
74b04a01
XL
1906 if self.is_empty() {
1907 None
1908 } else {
1909 let (k, v) = unsafe { self.next_unchecked() };
1910 Some((k, v)) // coerce k from `&mut K` to `&K`
1911 }
92a42be0 1912 }
416331ca
XL
1913
1914 fn last(mut self) -> Option<(&'a K, &'a mut V)> {
1915 self.next_back()
1916 }
1a4d82fc 1917}
1a4d82fc 1918
9cc50fc6 1919impl<'a, K, V> RangeMut<'a, K, V> {
74b04a01
XL
1920 fn is_empty(&self) -> bool {
1921 self.front == self.back
1922 }
1a4d82fc 1923
74b04a01 1924 unsafe fn next_unchecked(&mut self) -> (&'a mut K, &'a mut V) {
ba9703b0 1925 unwrap_unchecked(self.front.as_mut()).next_unchecked()
92a42be0 1926 }
c34b1796 1927}
1a4d82fc 1928
cc61c64b 1929#[stable(feature = "btree_range", since = "1.17.0")]
9cc50fc6
SL
1930impl<'a, K, V> DoubleEndedIterator for RangeMut<'a, K, V> {
1931 fn next_back(&mut self) -> Option<(&'a K, &'a mut V)> {
74b04a01
XL
1932 if self.is_empty() {
1933 None
1934 } else {
1935 let (k, v) = unsafe { self.next_back_unchecked() };
1936 Some((k, v)) // coerce k from `&mut K` to `&K`
1937 }
92a42be0 1938 }
1a4d82fc 1939}
1a4d82fc 1940
0531ce1d 1941#[stable(feature = "fused", since = "1.26.0")]
9fa01778 1942impl<K, V> FusedIterator for RangeMut<'_, K, V> {}
9e0c209e 1943
9cc50fc6 1944impl<'a, K, V> RangeMut<'a, K, V> {
74b04a01 1945 unsafe fn next_back_unchecked(&mut self) -> (&'a mut K, &'a mut V) {
ba9703b0 1946 unwrap_unchecked(self.back.as_mut()).next_back_unchecked()
92a42be0 1947 }
1a4d82fc 1948}
9cc50fc6 1949
c30ab7b3 1950#[stable(feature = "rust1", since = "1.0.0")]
9cc50fc6 1951impl<K: Ord, V> FromIterator<(K, V)> for BTreeMap<K, V> {
3157f602 1952 fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> BTreeMap<K, V> {
9cc50fc6
SL
1953 let mut map = BTreeMap::new();
1954 map.extend(iter);
1955 map
92a42be0 1956 }
1a4d82fc 1957}
1a4d82fc 1958
c30ab7b3 1959#[stable(feature = "rust1", since = "1.0.0")]
9cc50fc6
SL
1960impl<K: Ord, V> Extend<(K, V)> for BTreeMap<K, V> {
1961 #[inline]
3157f602 1962 fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) {
532ac7d7 1963 iter.into_iter().for_each(move |(k, v)| {
9cc50fc6 1964 self.insert(k, v);
532ac7d7 1965 });
92a42be0 1966 }
c34b1796 1967}
85aaf69f 1968
c30ab7b3 1969#[stable(feature = "extend_ref", since = "1.2.0")]
9cc50fc6 1970impl<'a, K: Ord + Copy, V: Copy> Extend<(&'a K, &'a V)> for BTreeMap<K, V> {
3157f602 1971 fn extend<I: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: I) {
9cc50fc6 1972 self.extend(iter.into_iter().map(|(&key, &value)| (key, value)));
92a42be0 1973 }
85aaf69f 1974}
9cc50fc6 1975
c30ab7b3 1976#[stable(feature = "rust1", since = "1.0.0")]
9cc50fc6
SL
1977impl<K: Hash, V: Hash> Hash for BTreeMap<K, V> {
1978 fn hash<H: Hasher>(&self, state: &mut H) {
1979 for elt in self {
1980 elt.hash(state);
1981 }
92a42be0 1982 }
85aaf69f
SL
1983}
1984
c30ab7b3 1985#[stable(feature = "rust1", since = "1.0.0")]
9cc50fc6 1986impl<K: Ord, V> Default for BTreeMap<K, V> {
9e0c209e 1987 /// Creates an empty `BTreeMap<K, V>`.
9cc50fc6
SL
1988 fn default() -> BTreeMap<K, V> {
1989 BTreeMap::new()
92a42be0 1990 }
85aaf69f 1991}
9cc50fc6 1992
c30ab7b3 1993#[stable(feature = "rust1", since = "1.0.0")]
9cc50fc6
SL
1994impl<K: PartialEq, V: PartialEq> PartialEq for BTreeMap<K, V> {
1995 fn eq(&self, other: &BTreeMap<K, V>) -> bool {
3157f602 1996 self.len() == other.len() && self.iter().zip(other).all(|(a, b)| a == b)
92a42be0 1997 }
85aaf69f
SL
1998}
1999
c30ab7b3 2000#[stable(feature = "rust1", since = "1.0.0")]
9cc50fc6 2001impl<K: Eq, V: Eq> Eq for BTreeMap<K, V> {}
c34b1796 2002
c30ab7b3 2003#[stable(feature = "rust1", since = "1.0.0")]
9cc50fc6
SL
2004impl<K: PartialOrd, V: PartialOrd> PartialOrd for BTreeMap<K, V> {
2005 #[inline]
2006 fn partial_cmp(&self, other: &BTreeMap<K, V>) -> Option<Ordering> {
2007 self.iter().partial_cmp(other.iter())
c34b1796 2008 }
1a4d82fc
JJ
2009}
2010
c30ab7b3 2011#[stable(feature = "rust1", since = "1.0.0")]
9cc50fc6
SL
2012impl<K: Ord, V: Ord> Ord for BTreeMap<K, V> {
2013 #[inline]
2014 fn cmp(&self, other: &BTreeMap<K, V>) -> Ordering {
2015 self.iter().cmp(other.iter())
1a4d82fc
JJ
2016 }
2017}
2018
c30ab7b3 2019#[stable(feature = "rust1", since = "1.0.0")]
9cc50fc6 2020impl<K: Debug, V: Debug> Debug for BTreeMap<K, V> {
9fa01778 2021 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
9cc50fc6 2022 f.debug_map().entries(self.iter()).finish()
1a4d82fc 2023 }
9cc50fc6 2024}
1a4d82fc 2025
c30ab7b3 2026#[stable(feature = "rust1", since = "1.0.0")]
9fa01778 2027impl<K: Ord, Q: ?Sized, V> Index<&Q> for BTreeMap<K, V>
dfeec247
XL
2028where
2029 K: Borrow<Q>,
2030 Q: Ord,
9cc50fc6
SL
2031{
2032 type Output = V;
1a4d82fc 2033
2c00a5a8
XL
2034 /// Returns a reference to the value corresponding to the supplied key.
2035 ///
2036 /// # Panics
2037 ///
2038 /// Panics if the key is not present in the `BTreeMap`.
9cc50fc6
SL
2039 #[inline]
2040 fn index(&self, key: &Q) -> &V {
2041 self.get(key).expect("no entry found for key")
1a4d82fc 2042 }
9cc50fc6 2043}
1a4d82fc 2044
0531ce1d 2045fn range_search<BorrowType, K, V, Q: ?Sized, R: RangeBounds<Q>>(
8bb4bdeb
XL
2046 root1: NodeRef<BorrowType, K, V, marker::LeafOrInternal>,
2047 root2: NodeRef<BorrowType, K, V, marker::LeafOrInternal>,
dfeec247
XL
2048 range: R,
2049) -> (
2050 Handle<NodeRef<BorrowType, K, V, marker::Leaf>, marker::Edge>,
2051 Handle<NodeRef<BorrowType, K, V, marker::Leaf>, marker::Edge>,
2052)
2053where
2054 Q: Ord,
2055 K: Borrow<Q>,
8bb4bdeb 2056{
94b46f34 2057 match (range.start_bound(), range.end_bound()) {
dfeec247
XL
2058 (Excluded(s), Excluded(e)) if s == e => {
2059 panic!("range start and end are equal and excluded in BTreeMap")
2060 }
ba9703b0 2061 (Included(s) | Excluded(s), Included(e) | Excluded(e)) if s > e => {
dfeec247
XL
2062 panic!("range start is greater than range end in BTreeMap")
2063 }
2064 _ => {}
8bb4bdeb
XL
2065 };
2066
2067 let mut min_node = root1;
2068 let mut max_node = root2;
2069 let mut min_found = false;
2070 let mut max_found = false;
8bb4bdeb
XL
2071
2072 loop {
74b04a01
XL
2073 let front = match (min_found, range.start_bound()) {
2074 (false, Included(key)) => match search::search_node(min_node, key) {
2075 Found(kv) => {
dfeec247 2076 min_found = true;
74b04a01 2077 kv.left_edge()
dfeec247 2078 }
74b04a01 2079 GoDown(edge) => edge,
8bb4bdeb 2080 },
74b04a01
XL
2081 (false, Excluded(key)) => match search::search_node(min_node, key) {
2082 Found(kv) => {
dfeec247 2083 min_found = true;
74b04a01 2084 kv.right_edge()
dfeec247 2085 }
74b04a01 2086 GoDown(edge) => edge,
8bb4bdeb 2087 },
74b04a01
XL
2088 (true, Included(_)) => min_node.last_edge(),
2089 (true, Excluded(_)) => min_node.first_edge(),
2090 (_, Unbounded) => min_node.first_edge(),
8bb4bdeb
XL
2091 };
2092
74b04a01
XL
2093 let back = match (max_found, range.end_bound()) {
2094 (false, Included(key)) => match search::search_node(max_node, key) {
2095 Found(kv) => {
dfeec247 2096 max_found = true;
74b04a01 2097 kv.right_edge()
dfeec247 2098 }
74b04a01 2099 GoDown(edge) => edge,
8bb4bdeb 2100 },
74b04a01
XL
2101 (false, Excluded(key)) => match search::search_node(max_node, key) {
2102 Found(kv) => {
dfeec247 2103 max_found = true;
74b04a01 2104 kv.left_edge()
dfeec247 2105 }
74b04a01 2106 GoDown(edge) => edge,
8bb4bdeb 2107 },
74b04a01
XL
2108 (true, Included(_)) => max_node.first_edge(),
2109 (true, Excluded(_)) => max_node.last_edge(),
2110 (_, Unbounded) => max_node.last_edge(),
8bb4bdeb
XL
2111 };
2112
74b04a01
XL
2113 if front.partial_cmp(&back) == Some(Ordering::Greater) {
2114 panic!("Ord is ill-defined in BTreeMap range");
8bb4bdeb 2115 }
8bb4bdeb
XL
2116 match (front.force(), back.force()) {
2117 (Leaf(f), Leaf(b)) => {
2118 return (f, b);
dfeec247 2119 }
8bb4bdeb
XL
2120 (Internal(min_int), Internal(max_int)) => {
2121 min_node = min_int.descend();
2122 max_node = max_int.descend();
dfeec247 2123 }
8bb4bdeb
XL
2124 _ => unreachable!("BTreeMap has different depths"),
2125 };
2126 }
2127}
2128
1a4d82fc 2129impl<K, V> BTreeMap<K, V> {
7453a54e 2130 /// Gets an iterator over the entries of the map, sorted by key.
1a4d82fc 2131 ///
c34b1796 2132 /// # Examples
1a4d82fc 2133 ///
54a0048b
SL
2134 /// Basic usage:
2135 ///
1a4d82fc
JJ
2136 /// ```
2137 /// use std::collections::BTreeMap;
2138 ///
2139 /// let mut map = BTreeMap::new();
85aaf69f 2140 /// map.insert(3, "c");
7453a54e
SL
2141 /// map.insert(2, "b");
2142 /// map.insert(1, "a");
1a4d82fc
JJ
2143 ///
2144 /// for (key, value) in map.iter() {
2145 /// println!("{}: {}", key, value);
2146 /// }
2147 ///
2148 /// let (first_key, first_value) = map.iter().next().unwrap();
85aaf69f 2149 /// assert_eq!((*first_key, *first_value), (1, "a"));
1a4d82fc 2150 /// ```
85aaf69f 2151 #[stable(feature = "rust1", since = "1.0.0")]
9fa01778 2152 pub fn iter(&self) -> Iter<'_, K, V> {
1a4d82fc 2153 Iter {
9cc50fc6 2154 range: Range {
ba9703b0
XL
2155 front: self.root.as_ref().map(|r| r.as_ref().first_leaf_edge()),
2156 back: self.root.as_ref().map(|r| r.as_ref().last_leaf_edge()),
92a42be0 2157 },
3157f602 2158 length: self.length,
1a4d82fc
JJ
2159 }
2160 }
2161
7453a54e 2162 /// Gets a mutable iterator over the entries of the map, sorted by key.
1a4d82fc
JJ
2163 ///
2164 /// # Examples
2165 ///
54a0048b
SL
2166 /// Basic usage:
2167 ///
1a4d82fc
JJ
2168 /// ```
2169 /// use std::collections::BTreeMap;
2170 ///
2171 /// let mut map = BTreeMap::new();
85aaf69f
SL
2172 /// map.insert("a", 1);
2173 /// map.insert("b", 2);
2174 /// map.insert("c", 3);
1a4d82fc
JJ
2175 ///
2176 /// // add 10 to the value if the key isn't "a"
2177 /// for (key, value) in map.iter_mut() {
2178 /// if key != &"a" {
2179 /// *value += 10;
2180 /// }
2181 /// }
2182 /// ```
85aaf69f 2183 #[stable(feature = "rust1", since = "1.0.0")]
9fa01778 2184 pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {
1a4d82fc 2185 IterMut {
ba9703b0
XL
2186 range: if let Some(root) = &mut self.root {
2187 let root1 = root.as_mut();
2188 let root2 = unsafe { ptr::read(&root1) };
2189 RangeMut {
2190 front: Some(root1.first_leaf_edge()),
2191 back: Some(root2.last_leaf_edge()),
2192 _marker: PhantomData,
2193 }
2194 } else {
2195 RangeMut { front: None, back: None, _marker: PhantomData }
92a42be0 2196 },
3157f602 2197 length: self.length,
1a4d82fc
JJ
2198 }
2199 }
2200
7453a54e 2201 /// Gets an iterator over the keys of the map, in sorted order.
1a4d82fc
JJ
2202 ///
2203 /// # Examples
2204 ///
54a0048b
SL
2205 /// Basic usage:
2206 ///
1a4d82fc
JJ
2207 /// ```
2208 /// use std::collections::BTreeMap;
2209 ///
2210 /// let mut a = BTreeMap::new();
85aaf69f 2211 /// a.insert(2, "b");
7453a54e 2212 /// a.insert(1, "a");
1a4d82fc 2213 ///
62682a34 2214 /// let keys: Vec<_> = a.keys().cloned().collect();
c34b1796 2215 /// assert_eq!(keys, [1, 2]);
1a4d82fc 2216 /// ```
85aaf69f 2217 #[stable(feature = "rust1", since = "1.0.0")]
416331ca 2218 pub fn keys(&self) -> Keys<'_, K, V> {
9cc50fc6 2219 Keys { inner: self.iter() }
1a4d82fc
JJ
2220 }
2221
7453a54e 2222 /// Gets an iterator over the values of the map, in order by key.
1a4d82fc
JJ
2223 ///
2224 /// # Examples
2225 ///
54a0048b
SL
2226 /// Basic usage:
2227 ///
1a4d82fc
JJ
2228 /// ```
2229 /// use std::collections::BTreeMap;
2230 ///
2231 /// let mut a = BTreeMap::new();
7453a54e
SL
2232 /// a.insert(1, "hello");
2233 /// a.insert(2, "goodbye");
1a4d82fc
JJ
2234 ///
2235 /// let values: Vec<&str> = a.values().cloned().collect();
7453a54e 2236 /// assert_eq!(values, ["hello", "goodbye"]);
1a4d82fc 2237 /// ```
85aaf69f 2238 #[stable(feature = "rust1", since = "1.0.0")]
416331ca 2239 pub fn values(&self) -> Values<'_, K, V> {
9cc50fc6 2240 Values { inner: self.iter() }
1a4d82fc
JJ
2241 }
2242
54a0048b
SL
2243 /// Gets a mutable iterator over the values of the map, in order by key.
2244 ///
2245 /// # Examples
2246 ///
2247 /// Basic usage:
2248 ///
2249 /// ```
54a0048b
SL
2250 /// use std::collections::BTreeMap;
2251 ///
2252 /// let mut a = BTreeMap::new();
2253 /// a.insert(1, String::from("hello"));
2254 /// a.insert(2, String::from("goodbye"));
2255 ///
2256 /// for value in a.values_mut() {
2257 /// value.push_str("!");
2258 /// }
2259 ///
2260 /// let values: Vec<String> = a.values().cloned().collect();
2261 /// assert_eq!(values, [String::from("hello!"),
2262 /// String::from("goodbye!")]);
2263 /// ```
a7813a04 2264 #[stable(feature = "map_values_mut", since = "1.10.0")]
9fa01778 2265 pub fn values_mut(&mut self) -> ValuesMut<'_, K, V> {
54a0048b
SL
2266 ValuesMut { inner: self.iter_mut() }
2267 }
2268
9346a6ac 2269 /// Returns the number of elements in the map.
1a4d82fc
JJ
2270 ///
2271 /// # Examples
2272 ///
54a0048b
SL
2273 /// Basic usage:
2274 ///
1a4d82fc
JJ
2275 /// ```
2276 /// use std::collections::BTreeMap;
2277 ///
2278 /// let mut a = BTreeMap::new();
2279 /// assert_eq!(a.len(), 0);
85aaf69f 2280 /// a.insert(1, "a");
1a4d82fc
JJ
2281 /// assert_eq!(a.len(), 1);
2282 /// ```
85aaf69f 2283 #[stable(feature = "rust1", since = "1.0.0")]
92a42be0
SL
2284 pub fn len(&self) -> usize {
2285 self.length
2286 }
1a4d82fc 2287
cc61c64b 2288 /// Returns `true` if the map contains no elements.
1a4d82fc
JJ
2289 ///
2290 /// # Examples
2291 ///
54a0048b
SL
2292 /// Basic usage:
2293 ///
1a4d82fc
JJ
2294 /// ```
2295 /// use std::collections::BTreeMap;
2296 ///
2297 /// let mut a = BTreeMap::new();
2298 /// assert!(a.is_empty());
85aaf69f 2299 /// a.insert(1, "a");
1a4d82fc
JJ
2300 /// assert!(!a.is_empty());
2301 /// ```
85aaf69f 2302 #[stable(feature = "rust1", since = "1.0.0")]
92a42be0
SL
2303 pub fn is_empty(&self) -> bool {
2304 self.len() == 0
2305 }
ba9703b0
XL
2306
2307 /// If the root node is the empty (non-allocated) root node, allocate our
2308 /// own node.
2309 fn ensure_root_is_owned(&mut self) -> &mut node::Root<K, V> {
2310 self.root.get_or_insert_with(node::Root::new_leaf)
2311 }
1a4d82fc
JJ
2312}
2313
9cc50fc6
SL
2314impl<'a, K: Ord, V> Entry<'a, K, V> {
2315 /// Ensures a value is in the entry by inserting the default if empty, and returns
2316 /// a mutable reference to the value in the entry.
5bcae85e
SL
2317 ///
2318 /// # Examples
2319 ///
2320 /// ```
2321 /// use std::collections::BTreeMap;
2322 ///
2323 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2324 /// map.entry("poneyland").or_insert(12);
2325 ///
2326 /// assert_eq!(map["poneyland"], 12);
2327 /// ```
9cc50fc6
SL
2328 #[stable(feature = "rust1", since = "1.0.0")]
2329 pub fn or_insert(self, default: V) -> &'a mut V {
2330 match self {
2331 Occupied(entry) => entry.into_mut(),
2332 Vacant(entry) => entry.insert(default),
2333 }
2334 }
85aaf69f 2335
9cc50fc6
SL
2336 /// Ensures a value is in the entry by inserting the result of the default function if empty,
2337 /// and returns a mutable reference to the value in the entry.
5bcae85e
SL
2338 ///
2339 /// # Examples
2340 ///
2341 /// ```
2342 /// use std::collections::BTreeMap;
2343 ///
2344 /// let mut map: BTreeMap<&str, String> = BTreeMap::new();
32a655c1 2345 /// let s = "hoho".to_string();
5bcae85e
SL
2346 ///
2347 /// map.entry("poneyland").or_insert_with(|| s);
2348 ///
32a655c1 2349 /// assert_eq!(map["poneyland"], "hoho".to_string());
5bcae85e 2350 /// ```
9cc50fc6
SL
2351 #[stable(feature = "rust1", since = "1.0.0")]
2352 pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V {
2353 match self {
2354 Occupied(entry) => entry.into_mut(),
2355 Vacant(entry) => entry.insert(default()),
2356 }
2357 }
a7813a04 2358
ba9703b0
XL
2359 #[unstable(feature = "or_insert_with_key", issue = "71024")]
2360 /// Ensures a value is in the entry by inserting, if empty, the result of the default function,
2361 /// which takes the key as its argument, and returns a mutable reference to the value in the
2362 /// entry.
2363 ///
2364 /// # Examples
2365 ///
2366 /// ```
2367 /// #![feature(or_insert_with_key)]
2368 /// use std::collections::BTreeMap;
2369 ///
2370 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2371 ///
2372 /// map.entry("poneyland").or_insert_with_key(|key| key.chars().count());
2373 ///
2374 /// assert_eq!(map["poneyland"], 9);
2375 /// ```
2376 #[inline]
2377 pub fn or_insert_with_key<F: FnOnce(&K) -> V>(self, default: F) -> &'a mut V {
2378 match self {
2379 Occupied(entry) => entry.into_mut(),
2380 Vacant(entry) => {
2381 let value = default(entry.key());
2382 entry.insert(value)
2383 }
2384 }
2385 }
2386
a7813a04 2387 /// Returns a reference to this entry's key.
5bcae85e
SL
2388 ///
2389 /// # Examples
2390 ///
2391 /// ```
2392 /// use std::collections::BTreeMap;
2393 ///
2394 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2395 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2396 /// ```
a7813a04
XL
2397 #[stable(feature = "map_entry_keys", since = "1.10.0")]
2398 pub fn key(&self) -> &K {
2399 match *self {
2400 Occupied(ref entry) => entry.key(),
2401 Vacant(ref entry) => entry.key(),
2402 }
2403 }
ea8adc8c
XL
2404
2405 /// Provides in-place mutable access to an occupied entry before any
2406 /// potential inserts into the map.
2407 ///
2408 /// # Examples
2409 ///
2410 /// ```
ea8adc8c
XL
2411 /// use std::collections::BTreeMap;
2412 ///
2413 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2414 ///
2415 /// map.entry("poneyland")
2416 /// .and_modify(|e| { *e += 1 })
2417 /// .or_insert(42);
2418 /// assert_eq!(map["poneyland"], 42);
2419 ///
2420 /// map.entry("poneyland")
2421 /// .and_modify(|e| { *e += 1 })
2422 /// .or_insert(42);
2423 /// assert_eq!(map["poneyland"], 43);
2424 /// ```
0531ce1d
XL
2425 #[stable(feature = "entry_and_modify", since = "1.26.0")]
2426 pub fn and_modify<F>(self, f: F) -> Self
dfeec247
XL
2427 where
2428 F: FnOnce(&mut V),
ea8adc8c
XL
2429 {
2430 match self {
2431 Occupied(mut entry) => {
2432 f(entry.get_mut());
2433 Occupied(entry)
dfeec247 2434 }
ea8adc8c
XL
2435 Vacant(entry) => Vacant(entry),
2436 }
2437 }
2438}
2439
2440impl<'a, K: Ord, V: Default> Entry<'a, K, V> {
94b46f34 2441 #[stable(feature = "entry_or_default", since = "1.28.0")]
ea8adc8c
XL
2442 /// Ensures a value is in the entry by inserting the default value if empty,
2443 /// and returns a mutable reference to the value in the entry.
2444 ///
2445 /// # Examples
2446 ///
2447 /// ```
ea8adc8c
XL
2448 /// use std::collections::BTreeMap;
2449 ///
2450 /// let mut map: BTreeMap<&str, Option<usize>> = BTreeMap::new();
2451 /// map.entry("poneyland").or_default();
2452 ///
2453 /// assert_eq!(map["poneyland"], None);
ea8adc8c
XL
2454 /// ```
2455 pub fn or_default(self) -> &'a mut V {
2456 match self {
2457 Occupied(entry) => entry.into_mut(),
2458 Vacant(entry) => entry.insert(Default::default()),
2459 }
2460 }
9cc50fc6 2461}
85aaf69f 2462
9cc50fc6 2463impl<'a, K: Ord, V> VacantEntry<'a, K, V> {
54a0048b
SL
2464 /// Gets a reference to the key that would be used when inserting a value
2465 /// through the VacantEntry.
5bcae85e
SL
2466 ///
2467 /// # Examples
2468 ///
2469 /// ```
2470 /// use std::collections::BTreeMap;
2471 ///
2472 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2473 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2474 /// ```
a7813a04 2475 #[stable(feature = "map_entry_keys", since = "1.10.0")]
54a0048b
SL
2476 pub fn key(&self) -> &K {
2477 &self.key
2478 }
2479
3157f602 2480 /// Take ownership of the key.
5bcae85e
SL
2481 ///
2482 /// # Examples
2483 ///
2484 /// ```
2485 /// use std::collections::BTreeMap;
2486 /// use std::collections::btree_map::Entry;
2487 ///
2488 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2489 ///
2490 /// if let Entry::Vacant(v) = map.entry("poneyland") {
2491 /// v.into_key();
2492 /// }
2493 /// ```
2494 #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")]
3157f602
XL
2495 pub fn into_key(self) -> K {
2496 self.key
2497 }
2498
9e0c209e 2499 /// Sets the value of the entry with the `VacantEntry`'s key,
9cc50fc6 2500 /// and returns a mutable reference to it.
5bcae85e
SL
2501 ///
2502 /// # Examples
2503 ///
2504 /// ```
2505 /// use std::collections::BTreeMap;
2506 ///
2507 /// let mut count: BTreeMap<&str, usize> = BTreeMap::new();
2508 ///
2509 /// // count the number of occurrences of letters in the vec
2510 /// for x in vec!["a","b","a","c","a","b"] {
2511 /// *count.entry(x).or_insert(0) += 1;
2512 /// }
2513 ///
2514 /// assert_eq!(count["a"], 3);
2515 /// ```
9cc50fc6
SL
2516 #[stable(feature = "rust1", since = "1.0.0")]
2517 pub fn insert(self, value: V) -> &'a mut V {
2518 *self.length += 1;
2519
2520 let out_ptr;
2521
2522 let mut ins_k;
2523 let mut ins_v;
2524 let mut ins_edge;
2525
2526 let mut cur_parent = match self.handle.insert(self.key, value) {
2527 (Fit(handle), _) => return handle.into_kv_mut().1,
2528 (Split(left, k, v, right), ptr) => {
2529 ins_k = k;
2530 ins_v = v;
2531 ins_edge = right;
2532 out_ptr = ptr;
2533 left.ascend().map_err(|n| n.into_root_mut())
85aaf69f 2534 }
9cc50fc6 2535 };
85aaf69f 2536
9cc50fc6
SL
2537 loop {
2538 match cur_parent {
dfeec247
XL
2539 Ok(parent) => match parent.insert(ins_k, ins_v, ins_edge) {
2540 Fit(_) => return unsafe { &mut *out_ptr },
2541 Split(left, k, v, right) => {
2542 ins_k = k;
2543 ins_v = v;
2544 ins_edge = right;
2545 cur_parent = left.ascend().map_err(|n| n.into_root_mut());
9cc50fc6 2546 }
dfeec247 2547 },
9cc50fc6
SL
2548 Err(root) => {
2549 root.push_level().push(ins_k, ins_v, ins_edge);
2550 return unsafe { &mut *out_ptr };
85aaf69f
SL
2551 }
2552 }
2553 }
9cc50fc6 2554 }
85aaf69f
SL
2555}
2556
9cc50fc6 2557impl<'a, K: Ord, V> OccupiedEntry<'a, K, V> {
54a0048b 2558 /// Gets a reference to the key in the entry.
5bcae85e
SL
2559 ///
2560 /// # Examples
2561 ///
2562 /// ```
2563 /// use std::collections::BTreeMap;
2564 ///
2565 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2566 /// map.entry("poneyland").or_insert(12);
2567 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2568 /// ```
a7813a04 2569 #[stable(feature = "map_entry_keys", since = "1.10.0")]
54a0048b
SL
2570 pub fn key(&self) -> &K {
2571 self.handle.reborrow().into_kv().0
2572 }
2573
5bcae85e
SL
2574 /// Take ownership of the key and value from the map.
2575 ///
2576 /// # Examples
2577 ///
2578 /// ```
2579 /// use std::collections::BTreeMap;
2580 /// use std::collections::btree_map::Entry;
2581 ///
2582 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2583 /// map.entry("poneyland").or_insert(12);
2584 ///
2585 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2586 /// // We delete the entry from the map.
2587 /// o.remove_entry();
2588 /// }
2589 ///
2590 /// // If now try to get the value, it will panic:
2591 /// // println!("{}", map["poneyland"]);
2592 /// ```
2593 #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")]
2594 pub fn remove_entry(self) -> (K, V) {
3157f602
XL
2595 self.remove_kv()
2596 }
2597
9cc50fc6 2598 /// Gets a reference to the value in the entry.
5bcae85e
SL
2599 ///
2600 /// # Examples
2601 ///
2602 /// ```
2603 /// use std::collections::BTreeMap;
2604 /// use std::collections::btree_map::Entry;
2605 ///
2606 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2607 /// map.entry("poneyland").or_insert(12);
2608 ///
2609 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2610 /// assert_eq!(o.get(), &12);
2611 /// }
2612 /// ```
9cc50fc6
SL
2613 #[stable(feature = "rust1", since = "1.0.0")]
2614 pub fn get(&self) -> &V {
2615 self.handle.reborrow().into_kv().1
85aaf69f
SL
2616 }
2617
9cc50fc6 2618 /// Gets a mutable reference to the value in the entry.
5bcae85e 2619 ///
9fa01778 2620 /// If you need a reference to the `OccupiedEntry` that may outlive the
94b46f34
XL
2621 /// destruction of the `Entry` value, see [`into_mut`].
2622 ///
2623 /// [`into_mut`]: #method.into_mut
2624 ///
5bcae85e
SL
2625 /// # Examples
2626 ///
2627 /// ```
2628 /// use std::collections::BTreeMap;
2629 /// use std::collections::btree_map::Entry;
2630 ///
2631 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2632 /// map.entry("poneyland").or_insert(12);
2633 ///
2634 /// assert_eq!(map["poneyland"], 12);
2635 /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
94b46f34
XL
2636 /// *o.get_mut() += 10;
2637 /// assert_eq!(*o.get(), 22);
2638 ///
2639 /// // We can use the same Entry multiple times.
2640 /// *o.get_mut() += 2;
5bcae85e 2641 /// }
94b46f34 2642 /// assert_eq!(map["poneyland"], 24);
5bcae85e 2643 /// ```
9cc50fc6
SL
2644 #[stable(feature = "rust1", since = "1.0.0")]
2645 pub fn get_mut(&mut self) -> &mut V {
2646 self.handle.kv_mut().1
85aaf69f
SL
2647 }
2648
9cc50fc6 2649 /// Converts the entry into a mutable reference to its value.
5bcae85e 2650 ///
94b46f34
XL
2651 /// If you need multiple references to the `OccupiedEntry`, see [`get_mut`].
2652 ///
2653 /// [`get_mut`]: #method.get_mut
2654 ///
5bcae85e
SL
2655 /// # Examples
2656 ///
2657 /// ```
2658 /// use std::collections::BTreeMap;
2659 /// use std::collections::btree_map::Entry;
2660 ///
2661 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2662 /// map.entry("poneyland").or_insert(12);
2663 ///
2664 /// assert_eq!(map["poneyland"], 12);
2665 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2666 /// *o.into_mut() += 10;
2667 /// }
2668 /// assert_eq!(map["poneyland"], 22);
2669 /// ```
85aaf69f 2670 #[stable(feature = "rust1", since = "1.0.0")]
9cc50fc6
SL
2671 pub fn into_mut(self) -> &'a mut V {
2672 self.handle.into_kv_mut().1
1a4d82fc 2673 }
e9174d1e 2674
9e0c209e 2675 /// Sets the value of the entry with the `OccupiedEntry`'s key,
9cc50fc6 2676 /// and returns the entry's old value.
5bcae85e
SL
2677 ///
2678 /// # Examples
2679 ///
2680 /// ```
2681 /// use std::collections::BTreeMap;
2682 /// use std::collections::btree_map::Entry;
2683 ///
2684 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2685 /// map.entry("poneyland").or_insert(12);
2686 ///
2687 /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
2688 /// assert_eq!(o.insert(15), 12);
2689 /// }
2690 /// assert_eq!(map["poneyland"], 15);
2691 /// ```
9cc50fc6
SL
2692 #[stable(feature = "rust1", since = "1.0.0")]
2693 pub fn insert(&mut self, value: V) -> V {
2694 mem::replace(self.get_mut(), value)
2695 }
e9174d1e 2696
9cc50fc6 2697 /// Takes the value of the entry out of the map, and returns it.
5bcae85e
SL
2698 ///
2699 /// # Examples
2700 ///
2701 /// ```
2702 /// use std::collections::BTreeMap;
2703 /// use std::collections::btree_map::Entry;
2704 ///
2705 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2706 /// map.entry("poneyland").or_insert(12);
2707 ///
2708 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2709 /// assert_eq!(o.remove(), 12);
2710 /// }
2711 /// // If we try to get "poneyland"'s value, it'll panic:
2712 /// // println!("{}", map["poneyland"]);
2713 /// ```
9cc50fc6
SL
2714 #[stable(feature = "rust1", since = "1.0.0")]
2715 pub fn remove(self) -> V {
2716 self.remove_kv().1
e9174d1e
SL
2717 }
2718
9cc50fc6
SL
2719 fn remove_kv(self) -> (K, V) {
2720 *self.length -= 1;
e9174d1e 2721
ba9703b0
XL
2722 let (old_key, old_val, _) = self.handle.remove_kv_tracking();
2723 (old_key, old_val)
2724 }
2725}
2726
2727impl<'a, K: 'a, V: 'a> Handle<NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal>, marker::KV> {
2728 /// Removes a key/value-pair from the map, and returns that pair, as well as
2729 /// the leaf edge corresponding to that former pair.
2730 fn remove_kv_tracking(
2731 self,
2732 ) -> (K, V, Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge>) {
2733 let (mut pos, old_key, old_val, was_internal) = match self.force() {
9cc50fc6
SL
2734 Leaf(leaf) => {
2735 let (hole, old_key, old_val) = leaf.remove();
ba9703b0 2736 (hole, old_key, old_val, false)
3157f602 2737 }
9cc50fc6 2738 Internal(mut internal) => {
ba9703b0
XL
2739 // Replace the location freed in the internal node with the next KV,
2740 // and remove that next KV from its leaf.
2741
9cc50fc6
SL
2742 let key_loc = internal.kv_mut().0 as *mut K;
2743 let val_loc = internal.kv_mut().1 as *mut V;
2744
ba9703b0
XL
2745 // Deleting from the left side is typically faster since we can
2746 // just pop an element from the end of the KV array without
2747 // needing to shift the other values.
2748 let to_remove = internal.left_edge().descend().last_leaf_edge().left_kv().ok();
9cc50fc6
SL
2749 let to_remove = unsafe { unwrap_unchecked(to_remove) };
2750
2751 let (hole, key, val) = to_remove.remove();
2752
3157f602
XL
2753 let old_key = unsafe { mem::replace(&mut *key_loc, key) };
2754 let old_val = unsafe { mem::replace(&mut *val_loc, val) };
9cc50fc6 2755
ba9703b0 2756 (hole, old_key, old_val, true)
9cc50fc6
SL
2757 }
2758 };
2759
2760 // Handle underflow
ba9703b0
XL
2761 let mut cur_node = unsafe { ptr::read(&pos).into_node().forget_type() };
2762 let mut at_leaf = true;
dfeec247 2763 while cur_node.len() < node::MIN_LEN {
9cc50fc6
SL
2764 match handle_underfull_node(cur_node) {
2765 AtRoot => break,
ba9703b0
XL
2766 Merged(edge, merged_with_left, offset) => {
2767 // If we merged with our right sibling then our tracked
2768 // position has not changed. However if we merged with our
2769 // left sibling then our tracked position is now dangling.
2770 if at_leaf && merged_with_left {
2771 let idx = pos.idx() + offset;
2772 let node = match unsafe { ptr::read(&edge).descend().force() } {
2773 Leaf(leaf) => leaf,
2774 Internal(_) => unreachable!(),
2775 };
2776 pos = unsafe { Handle::new_edge(node, idx) };
2777 }
2778
2779 let parent = edge.into_node();
3157f602
XL
2780 if parent.len() == 0 {
2781 // We must be at the root
2782 parent.into_root_mut().pop_level();
2783 break;
2784 } else {
2785 cur_node = parent.forget_type();
ba9703b0 2786 at_leaf = false;
3157f602
XL
2787 }
2788 }
ba9703b0
XL
2789 Stole(stole_from_left) => {
2790 // Adjust the tracked position if we stole from a left sibling
2791 if stole_from_left && at_leaf {
2792 // SAFETY: This is safe since we just added an element to our node.
2793 unsafe {
2794 pos.next_unchecked();
2795 }
2796 }
2797 break;
2798 }
e9174d1e
SL
2799 }
2800 }
9cc50fc6 2801
ba9703b0
XL
2802 // If we deleted from an internal node then we need to compensate for
2803 // the earlier swap and adjust the tracked position to point to the
2804 // next element.
2805 if was_internal {
2806 pos = unsafe { unwrap_unchecked(pos.next_kv().ok()).next_leaf_edge() };
2807 }
2808
2809 (old_key, old_val, pos)
e9174d1e 2810 }
9cc50fc6 2811}
e9174d1e 2812
9cc50fc6
SL
2813enum UnderflowResult<'a, K, V> {
2814 AtRoot,
ba9703b0
XL
2815 Merged(Handle<NodeRef<marker::Mut<'a>, K, V, marker::Internal>, marker::Edge>, bool, usize),
2816 Stole(bool),
9cc50fc6
SL
2817}
2818
dfeec247
XL
2819fn handle_underfull_node<K, V>(
2820 node: NodeRef<marker::Mut<'_>, K, V, marker::LeafOrInternal>,
2821) -> UnderflowResult<'_, K, V> {
ba9703b0
XL
2822 let parent = match node.ascend() {
2823 Ok(parent) => parent,
2824 Err(_) => return AtRoot,
9cc50fc6
SL
2825 };
2826
2827 let (is_left, mut handle) = match parent.left_kv() {
2828 Ok(left) => (true, left),
ba9703b0
XL
2829 Err(parent) => {
2830 let right = unsafe { unwrap_unchecked(parent.right_kv().ok()) };
2831 (false, right)
2832 }
9cc50fc6
SL
2833 };
2834
2835 if handle.can_merge() {
ba9703b0
XL
2836 let offset = if is_left { handle.reborrow().left_edge().descend().len() + 1 } else { 0 };
2837 Merged(handle.merge(), is_left, offset)
9cc50fc6 2838 } else {
a7813a04
XL
2839 if is_left {
2840 handle.steal_left();
2841 } else {
2842 handle.steal_right();
2843 }
ba9703b0 2844 Stole(is_left)
a7813a04
XL
2845 }
2846}
e9174d1e 2847
3157f602 2848impl<K: Ord, V, I: Iterator<Item = (K, V)>> Iterator for MergeIter<K, V, I> {
a7813a04 2849 type Item = (K, V);
e9174d1e 2850
a7813a04
XL
2851 fn next(&mut self) -> Option<(K, V)> {
2852 let res = match (self.left.peek(), self.right.peek()) {
2853 (Some(&(ref left_key, _)), Some(&(ref right_key, _))) => left_key.cmp(right_key),
2854 (Some(_), None) => Ordering::Less,
2855 (None, Some(_)) => Ordering::Greater,
2856 (None, None) => return None,
2857 };
9cc50fc6 2858
a7813a04
XL
2859 // Check which elements comes first and only advance the corresponding iterator.
2860 // If two keys are equal, take the value from `right`.
2861 match res {
3157f602
XL
2862 Ordering::Less => self.left.next(),
2863 Ordering::Greater => self.right.next(),
a7813a04
XL
2864 Ordering::Equal => {
2865 self.left.next();
2866 self.right.next()
3157f602 2867 }
a7813a04 2868 }
e9174d1e
SL
2869 }
2870}