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