1 use core::borrow::Borrow;
2 use core::cmp::Ordering;
4 use core::hash::{Hash, Hasher};
5 use core::iter::{FromIterator, FusedIterator, Peekable};
6 use core::marker::PhantomData;
7 use core::ops::Bound::{Excluded, Included, Unbounded};
8 use core::ops::{Index, RangeBounds};
9 use core::{fmt, mem, ptr};
11 use super::node::{self, marker, ForceResult::*, Handle, InsertResult::*, NodeRef};
12 use super::search::{self, SearchResult::*};
13 use super::unwrap_unchecked;
16 use UnderflowResult::*;
18 /// A map based on a B-Tree.
20 /// B-Trees represent a fundamental compromise between cache-efficiency and actually minimizing
21 /// the amount of work performed in a search. In theory, a binary search tree (BST) is the optimal
22 /// choice for a sorted map, as a perfectly balanced BST performs the theoretical minimum amount of
23 /// comparisons necessary to find an element (log<sub>2</sub>n). However, in practice the way this
24 /// is done is *very* inefficient for modern computer architectures. In particular, every element
25 /// is stored in its own individually heap-allocated node. This means that every single insertion
26 /// triggers a heap-allocation, and every single comparison should be a cache-miss. Since these
27 /// are both notably expensive things to do in practice, we are forced to at very least reconsider
30 /// A B-Tree instead makes each node contain B-1 to 2B-1 elements in a contiguous array. By doing
31 /// this, we reduce the number of allocations by a factor of B, and improve cache efficiency in
32 /// searches. However, this does mean that searches will have to do *more* comparisons on average.
33 /// The precise number of comparisons depends on the node search strategy used. For optimal cache
34 /// efficiency, one could search the nodes linearly. For optimal comparisons, one could search
35 /// the node using binary search. As a compromise, one could also perform a linear search
36 /// that initially only checks every i<sup>th</sup> element for some choice of i.
38 /// Currently, our implementation simply performs naive linear search. This provides excellent
39 /// performance on *small* nodes of elements which are cheap to compare. However in the future we
40 /// would like to further explore choosing the optimal search strategy based on the choice of B,
41 /// and possibly other factors. Using linear search, searching for a random element is expected
42 /// to take O(B log<sub>B</sub>n) comparisons, which is generally worse than a BST. In practice,
43 /// however, performance is excellent.
45 /// It is a logic error for a key to be modified in such a way that the key's ordering relative to
46 /// any other key, as determined by the [`Ord`] trait, changes while it is in the map. This is
47 /// normally only possible through [`Cell`], [`RefCell`], global state, I/O, or unsafe code.
49 /// [`Ord`]: ../../std/cmp/trait.Ord.html
50 /// [`Cell`]: ../../std/cell/struct.Cell.html
51 /// [`RefCell`]: ../../std/cell/struct.RefCell.html
56 /// use std::collections::BTreeMap;
58 /// // type inference lets us omit an explicit type signature (which
59 /// // would be `BTreeMap<&str, &str>` in this example).
60 /// let mut movie_reviews = BTreeMap::new();
62 /// // review some movies.
63 /// movie_reviews.insert("Office Space", "Deals with real issues in the workplace.");
64 /// movie_reviews.insert("Pulp Fiction", "Masterpiece.");
65 /// movie_reviews.insert("The Godfather", "Very enjoyable.");
66 /// movie_reviews.insert("The Blues Brothers", "Eye lyked it a lot.");
68 /// // check for a specific one.
69 /// if !movie_reviews.contains_key("Les Misérables") {
70 /// println!("We've got {} reviews, but Les Misérables ain't one.",
71 /// movie_reviews.len());
74 /// // oops, this review has a lot of spelling mistakes, let's delete it.
75 /// movie_reviews.remove("The Blues Brothers");
77 /// // look up the values associated with some keys.
78 /// let to_find = ["Up!", "Office Space"];
79 /// for movie in &to_find {
80 /// match movie_reviews.get(movie) {
81 /// Some(review) => println!("{}: {}", movie, review),
82 /// None => println!("{} is unreviewed.", movie)
86 /// // Look up the value for a key (will panic if the key is not found).
87 /// println!("Movie review: {}", movie_reviews["Office Space"]);
89 /// // iterate over everything.
90 /// for (movie, review) in &movie_reviews {
91 /// println!("{}: \"{}\"", movie, review);
95 /// `BTreeMap` also implements an [`Entry API`](#method.entry), which allows
96 /// for more complex methods of getting, setting, updating and removing keys and
100 /// use std::collections::BTreeMap;
102 /// // type inference lets us omit an explicit type signature (which
103 /// // would be `BTreeMap<&str, u8>` in this example).
104 /// let mut player_stats = BTreeMap::new();
106 /// fn random_stat_buff() -> u8 {
107 /// // could actually return some random value here - let's just return
108 /// // some fixed value for now
112 /// // insert a key only if it doesn't already exist
113 /// player_stats.entry("health").or_insert(100);
115 /// // insert a key using a function that provides a new value only if it
116 /// // doesn't already exist
117 /// player_stats.entry("defence").or_insert_with(random_stat_buff);
119 /// // update a key, guarding against the key possibly not being set
120 /// let stat = player_stats.entry("attack").or_insert(100);
121 /// *stat += random_stat_buff();
123 #[stable(feature = "rust1", since = "1.0.0")]
124 pub struct BTreeMap<K, V> {
125 root: Option<node::Root<K, V>>,
129 #[stable(feature = "btree_drop", since = "1.7.0")]
130 unsafe impl<#[may_dangle] K, #[may_dangle] V> Drop for BTreeMap<K, V> {
133 drop(ptr::read(self).into_iter());
138 #[stable(feature = "rust1", since = "1.0.0")]
139 impl<K: Clone, V: Clone> Clone for BTreeMap<K, V> {
140 fn clone(&self) -> BTreeMap<K, V> {
141 fn clone_subtree<'a, K: Clone, V: Clone>(
142 node: node::NodeRef<marker::Immut<'a>, K, V, marker::LeafOrInternal>,
150 let mut out_tree = BTreeMap { root: Some(node::Root::new_leaf()), length: 0 };
153 let root = out_tree.root.as_mut().unwrap();
154 let mut out_node = match root.as_mut().force() {
156 Internal(_) => unreachable!(),
159 let mut in_edge = leaf.first_edge();
160 while let Ok(kv) = in_edge.right_kv() {
161 let (k, v) = kv.into_kv();
162 in_edge = kv.right_edge();
164 out_node.push(k.clone(), v.clone());
165 out_tree.length += 1;
171 Internal(internal) => {
172 let mut out_tree = clone_subtree(internal.first_edge().descend());
174 // Cannot call ensure_root_is_owned() because lacking K: Ord
175 if out_tree.root.is_none() {
176 out_tree.root = Some(node::Root::new_leaf());
180 let mut out_node = out_tree.root.as_mut().unwrap().push_level();
181 let mut in_edge = internal.first_edge();
182 while let Ok(kv) = in_edge.right_kv() {
183 let (k, v) = kv.into_kv();
184 in_edge = kv.right_edge();
186 let k = (*k).clone();
187 let v = (*v).clone();
188 let subtree = clone_subtree(in_edge.descend());
190 // We can't destructure subtree directly
191 // because BTreeMap implements Drop
192 let (subroot, sublength) = unsafe {
193 let root = ptr::read(&subtree.root);
194 let length = subtree.length;
195 mem::forget(subtree);
199 out_node.push(k, v, subroot.unwrap_or_else(|| node::Root::new_leaf()));
200 out_tree.length += 1 + sublength;
210 // Ideally we'd call `BTreeMap::new` here, but that has the `K:
211 // Ord` constraint, which this method lacks.
212 BTreeMap { root: None, length: 0 }
214 clone_subtree(self.root.as_ref().unwrap().as_ref())
218 fn clone_from(&mut self, other: &Self) {
219 BTreeClone::clone_from(self, other);
224 fn clone_from(&mut self, other: &Self);
227 impl<K: Clone, V: Clone> BTreeClone for BTreeMap<K, V> {
228 default fn clone_from(&mut self, other: &Self) {
229 *self = other.clone();
233 impl<K: Clone + Ord, V: Clone> BTreeClone for BTreeMap<K, V> {
234 fn clone_from(&mut self, other: &Self) {
235 // This truncates `self` to `other.len()` by calling `split_off` on
236 // the first key after `other.len()` elements if it exists.
237 let split_off_key = if self.len() > other.len() {
238 let diff = self.len() - other.len();
239 if diff <= other.len() {
240 self.iter().nth_back(diff - 1).map(|pair| (*pair.0).clone())
242 self.iter().nth(other.len()).map(|pair| (*pair.0).clone())
247 if let Some(key) = split_off_key {
248 self.split_off(&key);
251 let mut siter = self.range_mut(..);
252 let mut oiter = other.iter();
253 // After truncation, `self` is at most as long as `other` so this loop
254 // replaces every key-value pair in `self`. Since `oiter` is in sorted
255 // order and the structure of the `BTreeMap` stays the same,
256 // the BTree invariants are maintained at the end of the loop.
257 while !siter.is_empty() {
258 if let Some((ok, ov)) = oiter.next() {
259 // SAFETY: This is safe because `siter` is nonempty.
260 let (sk, sv) = unsafe { siter.next_unchecked() };
267 // If `other` is longer than `self`, the remaining elements are inserted.
268 self.extend(oiter.map(|(k, v)| ((*k).clone(), (*v).clone())));
272 impl<K, Q: ?Sized> super::Recover<Q> for BTreeMap<K, ()>
279 fn get(&self, key: &Q) -> Option<&K> {
280 match search::search_tree(self.root.as_ref()?.as_ref(), key) {
281 Found(handle) => Some(handle.into_kv().0),
286 fn take(&mut self, key: &Q) -> Option<K> {
287 match search::search_tree(self.root.as_mut()?.as_mut(), key) {
288 Found(handle) => Some(
289 OccupiedEntry { handle, length: &mut self.length, _marker: PhantomData }
297 fn replace(&mut self, key: K) -> Option<K> {
298 self.ensure_root_is_owned();
299 match search::search_tree::<marker::Mut<'_>, K, (), K>(self.root.as_mut()?.as_mut(), &key) {
300 Found(handle) => Some(mem::replace(handle.into_kv_mut().0, key)),
302 VacantEntry { key, handle, length: &mut self.length, _marker: PhantomData }
310 /// An iterator over the entries of a `BTreeMap`.
312 /// This `struct` is created by the [`iter`] method on [`BTreeMap`]. See its
313 /// documentation for more.
315 /// [`iter`]: struct.BTreeMap.html#method.iter
316 /// [`BTreeMap`]: struct.BTreeMap.html
317 #[stable(feature = "rust1", since = "1.0.0")]
318 pub struct Iter<'a, K: 'a, V: 'a> {
319 range: Range<'a, K, V>,
323 #[stable(feature = "collection_debug", since = "1.17.0")]
324 impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for Iter<'_, K, V> {
325 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
326 f.debug_list().entries(self.clone()).finish()
330 /// A mutable iterator over the entries of a `BTreeMap`.
332 /// This `struct` is created by the [`iter_mut`] method on [`BTreeMap`]. See its
333 /// documentation for more.
335 /// [`iter_mut`]: struct.BTreeMap.html#method.iter_mut
336 /// [`BTreeMap`]: struct.BTreeMap.html
337 #[stable(feature = "rust1", since = "1.0.0")]
339 pub struct IterMut<'a, K: 'a, V: 'a> {
340 range: RangeMut<'a, K, V>,
344 /// An owning iterator over the entries of a `BTreeMap`.
346 /// This `struct` is created by the [`into_iter`] method on [`BTreeMap`]
347 /// (provided by the `IntoIterator` trait). See its documentation for more.
349 /// [`into_iter`]: struct.BTreeMap.html#method.into_iter
350 /// [`BTreeMap`]: struct.BTreeMap.html
351 #[stable(feature = "rust1", since = "1.0.0")]
352 pub struct IntoIter<K, V> {
353 front: Option<Handle<NodeRef<marker::Owned, K, V, marker::Leaf>, marker::Edge>>,
354 back: Option<Handle<NodeRef<marker::Owned, K, V, marker::Leaf>, marker::Edge>>,
358 #[stable(feature = "collection_debug", since = "1.17.0")]
359 impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for IntoIter<K, V> {
360 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
362 front: self.front.as_ref().map(|f| f.reborrow()),
363 back: self.back.as_ref().map(|b| b.reborrow()),
365 f.debug_list().entries(range).finish()
369 /// An iterator over the keys of a `BTreeMap`.
371 /// This `struct` is created by the [`keys`] method on [`BTreeMap`]. See its
372 /// documentation for more.
374 /// [`keys`]: struct.BTreeMap.html#method.keys
375 /// [`BTreeMap`]: struct.BTreeMap.html
376 #[stable(feature = "rust1", since = "1.0.0")]
377 pub struct Keys<'a, K: 'a, V: 'a> {
378 inner: Iter<'a, K, V>,
381 #[stable(feature = "collection_debug", since = "1.17.0")]
382 impl<K: fmt::Debug, V> fmt::Debug for Keys<'_, K, V> {
383 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
384 f.debug_list().entries(self.clone()).finish()
388 /// An iterator over the values of a `BTreeMap`.
390 /// This `struct` is created by the [`values`] method on [`BTreeMap`]. See its
391 /// documentation for more.
393 /// [`values`]: struct.BTreeMap.html#method.values
394 /// [`BTreeMap`]: struct.BTreeMap.html
395 #[stable(feature = "rust1", since = "1.0.0")]
396 pub struct Values<'a, K: 'a, V: 'a> {
397 inner: Iter<'a, K, V>,
400 #[stable(feature = "collection_debug", since = "1.17.0")]
401 impl<K, V: fmt::Debug> fmt::Debug for Values<'_, K, V> {
402 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
403 f.debug_list().entries(self.clone()).finish()
407 /// A mutable iterator over the values of a `BTreeMap`.
409 /// This `struct` is created by the [`values_mut`] method on [`BTreeMap`]. See its
410 /// documentation for more.
412 /// [`values_mut`]: struct.BTreeMap.html#method.values_mut
413 /// [`BTreeMap`]: struct.BTreeMap.html
414 #[stable(feature = "map_values_mut", since = "1.10.0")]
416 pub struct ValuesMut<'a, K: 'a, V: 'a> {
417 inner: IterMut<'a, K, V>,
420 /// An iterator over a sub-range of entries in a `BTreeMap`.
422 /// This `struct` is created by the [`range`] method on [`BTreeMap`]. See its
423 /// documentation for more.
425 /// [`range`]: struct.BTreeMap.html#method.range
426 /// [`BTreeMap`]: struct.BTreeMap.html
427 #[stable(feature = "btree_range", since = "1.17.0")]
428 pub struct Range<'a, K: 'a, V: 'a> {
429 front: Option<Handle<NodeRef<marker::Immut<'a>, K, V, marker::Leaf>, marker::Edge>>,
430 back: Option<Handle<NodeRef<marker::Immut<'a>, K, V, marker::Leaf>, marker::Edge>>,
433 #[stable(feature = "collection_debug", since = "1.17.0")]
434 impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for Range<'_, K, V> {
435 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
436 f.debug_list().entries(self.clone()).finish()
440 /// A mutable iterator over a sub-range of entries in a `BTreeMap`.
442 /// This `struct` is created by the [`range_mut`] method on [`BTreeMap`]. See its
443 /// documentation for more.
445 /// [`range_mut`]: struct.BTreeMap.html#method.range_mut
446 /// [`BTreeMap`]: struct.BTreeMap.html
447 #[stable(feature = "btree_range", since = "1.17.0")]
448 pub struct RangeMut<'a, K: 'a, V: 'a> {
449 front: Option<Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge>>,
450 back: Option<Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge>>,
452 // Be invariant in `K` and `V`
453 _marker: PhantomData<&'a mut (K, V)>,
456 #[stable(feature = "collection_debug", since = "1.17.0")]
457 impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for RangeMut<'_, K, V> {
458 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
460 front: self.front.as_ref().map(|f| f.reborrow()),
461 back: self.back.as_ref().map(|b| b.reborrow()),
463 f.debug_list().entries(range).finish()
467 /// A view into a single entry in a map, which may either be vacant or occupied.
469 /// This `enum` is constructed from the [`entry`] method on [`BTreeMap`].
471 /// [`BTreeMap`]: struct.BTreeMap.html
472 /// [`entry`]: struct.BTreeMap.html#method.entry
473 #[stable(feature = "rust1", since = "1.0.0")]
474 pub enum Entry<'a, K: 'a, V: 'a> {
476 #[stable(feature = "rust1", since = "1.0.0")]
477 Vacant(#[stable(feature = "rust1", since = "1.0.0")] VacantEntry<'a, K, V>),
479 /// An occupied entry.
480 #[stable(feature = "rust1", since = "1.0.0")]
481 Occupied(#[stable(feature = "rust1", since = "1.0.0")] OccupiedEntry<'a, K, V>),
484 #[stable(feature = "debug_btree_map", since = "1.12.0")]
485 impl<K: Debug + Ord, V: Debug> Debug for Entry<'_, K, V> {
486 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
488 Vacant(ref v) => f.debug_tuple("Entry").field(v).finish(),
489 Occupied(ref o) => f.debug_tuple("Entry").field(o).finish(),
494 /// A view into a vacant entry in a `BTreeMap`.
495 /// It is part of the [`Entry`] enum.
497 /// [`Entry`]: enum.Entry.html
498 #[stable(feature = "rust1", since = "1.0.0")]
499 pub struct VacantEntry<'a, K: 'a, V: 'a> {
501 handle: Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge>,
502 length: &'a mut usize,
504 // Be invariant in `K` and `V`
505 _marker: PhantomData<&'a mut (K, V)>,
508 #[stable(feature = "debug_btree_map", since = "1.12.0")]
509 impl<K: Debug + Ord, V> Debug for VacantEntry<'_, K, V> {
510 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
511 f.debug_tuple("VacantEntry").field(self.key()).finish()
515 /// A view into an occupied entry in a `BTreeMap`.
516 /// It is part of the [`Entry`] enum.
518 /// [`Entry`]: enum.Entry.html
519 #[stable(feature = "rust1", since = "1.0.0")]
520 pub struct OccupiedEntry<'a, K: 'a, V: 'a> {
521 handle: Handle<NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal>, marker::KV>,
523 length: &'a mut usize,
525 // Be invariant in `K` and `V`
526 _marker: PhantomData<&'a mut (K, V)>,
529 #[stable(feature = "debug_btree_map", since = "1.12.0")]
530 impl<K: Debug + Ord, V: Debug> Debug for OccupiedEntry<'_, K, V> {
531 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
532 f.debug_struct("OccupiedEntry").field("key", self.key()).field("value", self.get()).finish()
536 // An iterator for merging two sorted sequences into one
537 struct MergeIter<K, V, I: Iterator<Item = (K, V)>> {
542 impl<K: Ord, V> BTreeMap<K, V> {
543 /// Makes a new empty BTreeMap with a reasonable choice for B.
550 /// use std::collections::BTreeMap;
552 /// let mut map = BTreeMap::new();
554 /// // entries can now be inserted into the empty map
555 /// map.insert(1, "a");
557 #[stable(feature = "rust1", since = "1.0.0")]
558 pub fn new() -> BTreeMap<K, V> {
559 BTreeMap { root: None, length: 0 }
562 /// Clears the map, removing all elements.
569 /// use std::collections::BTreeMap;
571 /// let mut a = BTreeMap::new();
572 /// a.insert(1, "a");
574 /// assert!(a.is_empty());
576 #[stable(feature = "rust1", since = "1.0.0")]
577 pub fn clear(&mut self) {
578 *self = BTreeMap::new();
581 /// Returns a reference to the value corresponding to the key.
583 /// The key may be any borrowed form of the map's key type, but the ordering
584 /// on the borrowed form *must* match the ordering on the key type.
591 /// use std::collections::BTreeMap;
593 /// let mut map = BTreeMap::new();
594 /// map.insert(1, "a");
595 /// assert_eq!(map.get(&1), Some(&"a"));
596 /// assert_eq!(map.get(&2), None);
598 #[stable(feature = "rust1", since = "1.0.0")]
599 pub fn get<Q: ?Sized>(&self, key: &Q) -> Option<&V>
604 match search::search_tree(self.root.as_ref()?.as_ref(), key) {
605 Found(handle) => Some(handle.into_kv().1),
610 /// Returns the key-value pair corresponding to the supplied key.
612 /// The supplied key may be any borrowed form of the map's key type, but the ordering
613 /// on the borrowed form *must* match the ordering on the key type.
618 /// use std::collections::BTreeMap;
620 /// let mut map = BTreeMap::new();
621 /// map.insert(1, "a");
622 /// assert_eq!(map.get_key_value(&1), Some((&1, &"a")));
623 /// assert_eq!(map.get_key_value(&2), None);
625 #[stable(feature = "map_get_key_value", since = "1.40.0")]
626 pub fn get_key_value<Q: ?Sized>(&self, k: &Q) -> Option<(&K, &V)>
631 match search::search_tree(self.root.as_ref()?.as_ref(), k) {
632 Found(handle) => Some(handle.into_kv()),
637 /// Returns the first key-value pair in the map.
638 /// The key in this pair is the minimum key in the map.
645 /// #![feature(map_first_last)]
646 /// use std::collections::BTreeMap;
648 /// let mut map = BTreeMap::new();
649 /// assert_eq!(map.first_key_value(), None);
650 /// map.insert(1, "b");
651 /// map.insert(2, "a");
652 /// assert_eq!(map.first_key_value(), Some((&1, &"b")));
654 #[unstable(feature = "map_first_last", issue = "62924")]
655 pub fn first_key_value<T: ?Sized>(&self) -> Option<(&K, &V)>
660 let front = self.root.as_ref()?.as_ref().first_leaf_edge();
661 front.right_kv().ok().map(Handle::into_kv)
664 /// Returns the first entry in the map for in-place manipulation.
665 /// The key of this entry is the minimum key in the map.
669 /// Contrived way to `clear` a map:
672 /// #![feature(map_first_last)]
673 /// use std::collections::BTreeMap;
675 /// let mut map = BTreeMap::new();
676 /// map.insert(1, "a");
677 /// map.insert(2, "b");
678 /// while let Some(entry) = map.first_entry() {
679 /// let (key, val) = entry.remove_entry();
680 /// assert!(!map.contains_key(&key));
683 #[unstable(feature = "map_first_last", issue = "62924")]
684 pub fn first_entry<T: ?Sized>(&mut self) -> Option<OccupiedEntry<'_, K, V>>
689 let front = self.root.as_mut()?.as_mut().first_leaf_edge();
690 if let Ok(kv) = front.right_kv() {
692 handle: kv.forget_node_type(),
693 length: &mut self.length,
694 _marker: PhantomData,
701 /// Returns the last key-value pair in the map.
702 /// The key in this pair is the maximum key in the map.
709 /// #![feature(map_first_last)]
710 /// use std::collections::BTreeMap;
712 /// let mut map = BTreeMap::new();
713 /// map.insert(1, "b");
714 /// map.insert(2, "a");
715 /// assert_eq!(map.last_key_value(), Some((&2, &"a")));
717 #[unstable(feature = "map_first_last", issue = "62924")]
718 pub fn last_key_value<T: ?Sized>(&self) -> Option<(&K, &V)>
723 let back = self.root.as_ref()?.as_ref().last_leaf_edge();
724 back.left_kv().ok().map(Handle::into_kv)
727 /// Returns the last entry in the map for in-place manipulation.
728 /// The key of this entry is the maximum key in the map.
732 /// Contrived way to `clear` a map:
735 /// #![feature(map_first_last)]
736 /// use std::collections::BTreeMap;
738 /// let mut map = BTreeMap::new();
739 /// map.insert(1, "a");
740 /// map.insert(2, "b");
741 /// while let Some(entry) = map.last_entry() {
742 /// let (key, val) = entry.remove_entry();
743 /// assert!(!map.contains_key(&key));
746 #[unstable(feature = "map_first_last", issue = "62924")]
747 pub fn last_entry<T: ?Sized>(&mut self) -> Option<OccupiedEntry<'_, K, V>>
752 let back = self.root.as_mut()?.as_mut().last_leaf_edge();
753 if let Ok(kv) = back.left_kv() {
755 handle: kv.forget_node_type(),
756 length: &mut self.length,
757 _marker: PhantomData,
764 /// Returns `true` if the map contains a value for the specified key.
766 /// The key may be any borrowed form of the map's key type, but the ordering
767 /// on the borrowed form *must* match the ordering on the key type.
774 /// use std::collections::BTreeMap;
776 /// let mut map = BTreeMap::new();
777 /// map.insert(1, "a");
778 /// assert_eq!(map.contains_key(&1), true);
779 /// assert_eq!(map.contains_key(&2), false);
781 #[stable(feature = "rust1", since = "1.0.0")]
782 pub fn contains_key<Q: ?Sized>(&self, key: &Q) -> bool
787 self.get(key).is_some()
790 /// Returns a mutable reference to the value corresponding to the key.
792 /// The key may be any borrowed form of the map's key type, but the ordering
793 /// on the borrowed form *must* match the ordering on the key type.
800 /// use std::collections::BTreeMap;
802 /// let mut map = BTreeMap::new();
803 /// map.insert(1, "a");
804 /// if let Some(x) = map.get_mut(&1) {
807 /// assert_eq!(map[&1], "b");
809 // See `get` for implementation notes, this is basically a copy-paste with mut's added
810 #[stable(feature = "rust1", since = "1.0.0")]
811 pub fn get_mut<Q: ?Sized>(&mut self, key: &Q) -> Option<&mut V>
816 match search::search_tree(self.root.as_mut()?.as_mut(), key) {
817 Found(handle) => Some(handle.into_kv_mut().1),
822 /// Inserts a key-value pair into the map.
824 /// If the map did not have this key present, `None` is returned.
826 /// If the map did have this key present, the value is updated, and the old
827 /// value is returned. The key is not updated, though; this matters for
828 /// types that can be `==` without being identical. See the [module-level
829 /// documentation] for more.
831 /// [module-level documentation]: index.html#insert-and-complex-keys
838 /// use std::collections::BTreeMap;
840 /// let mut map = BTreeMap::new();
841 /// assert_eq!(map.insert(37, "a"), None);
842 /// assert_eq!(map.is_empty(), false);
844 /// map.insert(37, "b");
845 /// assert_eq!(map.insert(37, "c"), Some("b"));
846 /// assert_eq!(map[&37], "c");
848 #[stable(feature = "rust1", since = "1.0.0")]
849 pub fn insert(&mut self, key: K, value: V) -> Option<V> {
850 match self.entry(key) {
851 Occupied(mut entry) => Some(entry.insert(value)),
859 /// Removes a key from the map, returning the value at the key if the key
860 /// was previously in the map.
862 /// The key may be any borrowed form of the map's key type, but the ordering
863 /// on the borrowed form *must* match the ordering on the key type.
870 /// use std::collections::BTreeMap;
872 /// let mut map = BTreeMap::new();
873 /// map.insert(1, "a");
874 /// assert_eq!(map.remove(&1), Some("a"));
875 /// assert_eq!(map.remove(&1), None);
877 #[stable(feature = "rust1", since = "1.0.0")]
878 pub fn remove<Q: ?Sized>(&mut self, key: &Q) -> Option<V>
883 self.remove_entry(key).map(|(_, v)| v)
886 /// Removes a key from the map, returning the stored key and value if the key
887 /// was previously in the map.
889 /// The key may be any borrowed form of the map's key type, but the ordering
890 /// on the borrowed form *must* match the ordering on the key type.
897 /// #![feature(btreemap_remove_entry)]
898 /// use std::collections::BTreeMap;
900 /// let mut map = BTreeMap::new();
901 /// map.insert(1, "a");
902 /// assert_eq!(map.remove_entry(&1), Some((1, "a")));
903 /// assert_eq!(map.remove_entry(&1), None);
905 #[unstable(feature = "btreemap_remove_entry", issue = "66714")]
906 pub fn remove_entry<Q: ?Sized>(&mut self, key: &Q) -> Option<(K, V)>
911 match search::search_tree(self.root.as_mut()?.as_mut(), key) {
912 Found(handle) => Some(
913 OccupiedEntry { handle, length: &mut self.length, _marker: PhantomData }
920 /// Moves all elements from `other` into `Self`, leaving `other` empty.
925 /// use std::collections::BTreeMap;
927 /// let mut a = BTreeMap::new();
928 /// a.insert(1, "a");
929 /// a.insert(2, "b");
930 /// a.insert(3, "c");
932 /// let mut b = BTreeMap::new();
933 /// b.insert(3, "d");
934 /// b.insert(4, "e");
935 /// b.insert(5, "f");
937 /// a.append(&mut b);
939 /// assert_eq!(a.len(), 5);
940 /// assert_eq!(b.len(), 0);
942 /// assert_eq!(a[&1], "a");
943 /// assert_eq!(a[&2], "b");
944 /// assert_eq!(a[&3], "d");
945 /// assert_eq!(a[&4], "e");
946 /// assert_eq!(a[&5], "f");
948 #[stable(feature = "btree_append", since = "1.11.0")]
949 pub fn append(&mut self, other: &mut Self) {
950 // Do we have to append anything at all?
951 if other.is_empty() {
955 // We can just swap `self` and `other` if `self` is empty.
957 mem::swap(self, other);
961 // First, we merge `self` and `other` into a sorted sequence in linear time.
962 let self_iter = mem::take(self).into_iter();
963 let other_iter = mem::take(other).into_iter();
964 let iter = MergeIter { left: self_iter.peekable(), right: other_iter.peekable() };
966 // Second, we build a tree from the sorted sequence in linear time.
967 self.from_sorted_iter(iter);
968 self.fix_right_edge();
971 /// Constructs a double-ended iterator over a sub-range of elements in the map.
972 /// The simplest way is to use the range syntax `min..max`, thus `range(min..max)` will
973 /// yield elements from min (inclusive) to max (exclusive).
974 /// The range may also be entered as `(Bound<T>, Bound<T>)`, so for example
975 /// `range((Excluded(4), Included(10)))` will yield a left-exclusive, right-inclusive
976 /// range from 4 to 10.
980 /// Panics if range `start > end`.
981 /// Panics if range `start == end` and both bounds are `Excluded`.
988 /// use std::collections::BTreeMap;
989 /// use std::ops::Bound::Included;
991 /// let mut map = BTreeMap::new();
992 /// map.insert(3, "a");
993 /// map.insert(5, "b");
994 /// map.insert(8, "c");
995 /// for (&key, &value) in map.range((Included(&4), Included(&8))) {
996 /// println!("{}: {}", key, value);
998 /// assert_eq!(Some((&5, &"b")), map.range(4..).next());
1000 #[stable(feature = "btree_range", since = "1.17.0")]
1001 pub fn range<T: ?Sized, R>(&self, range: R) -> Range<'_, K, V>
1007 if let Some(root) = &self.root {
1008 let root1 = root.as_ref();
1009 let root2 = root.as_ref();
1010 let (f, b) = range_search(root1, root2, range);
1012 Range { front: Some(f), back: Some(b) }
1014 Range { front: None, back: None }
1018 /// Constructs a mutable double-ended iterator over a sub-range of elements in the map.
1019 /// The simplest way is to use the range syntax `min..max`, thus `range(min..max)` will
1020 /// yield elements from min (inclusive) to max (exclusive).
1021 /// The range may also be entered as `(Bound<T>, Bound<T>)`, so for example
1022 /// `range((Excluded(4), Included(10)))` will yield a left-exclusive, right-inclusive
1023 /// range from 4 to 10.
1027 /// Panics if range `start > end`.
1028 /// Panics if range `start == end` and both bounds are `Excluded`.
1035 /// use std::collections::BTreeMap;
1037 /// let mut map: BTreeMap<&str, i32> = ["Alice", "Bob", "Carol", "Cheryl"]
1039 /// .map(|&s| (s, 0))
1041 /// for (_, balance) in map.range_mut("B".."Cheryl") {
1042 /// *balance += 100;
1044 /// for (name, balance) in &map {
1045 /// println!("{} => {}", name, balance);
1048 #[stable(feature = "btree_range", since = "1.17.0")]
1049 pub fn range_mut<T: ?Sized, R>(&mut self, range: R) -> RangeMut<'_, K, V>
1055 if let Some(root) = &mut self.root {
1056 let root1 = root.as_mut();
1057 let root2 = unsafe { ptr::read(&root1) };
1058 let (f, b) = range_search(root1, root2, range);
1060 RangeMut { front: Some(f), back: Some(b), _marker: PhantomData }
1062 RangeMut { front: None, back: None, _marker: PhantomData }
1066 /// Gets the given key's corresponding entry in the map for in-place manipulation.
1073 /// use std::collections::BTreeMap;
1075 /// let mut count: BTreeMap<&str, usize> = BTreeMap::new();
1077 /// // count the number of occurrences of letters in the vec
1078 /// for x in vec!["a","b","a","c","a","b"] {
1079 /// *count.entry(x).or_insert(0) += 1;
1082 /// assert_eq!(count["a"], 3);
1084 #[stable(feature = "rust1", since = "1.0.0")]
1085 pub fn entry(&mut self, key: K) -> Entry<'_, K, V> {
1086 // FIXME(@porglezomp) Avoid allocating if we don't insert
1087 self.ensure_root_is_owned();
1088 match search::search_tree(self.root.as_mut().unwrap().as_mut(), &key) {
1090 Occupied(OccupiedEntry { handle, length: &mut self.length, _marker: PhantomData })
1093 Vacant(VacantEntry { key, handle, length: &mut self.length, _marker: PhantomData })
1098 fn from_sorted_iter<I: Iterator<Item = (K, V)>>(&mut self, iter: I) {
1099 self.ensure_root_is_owned();
1100 let mut cur_node = self.root.as_mut().unwrap().as_mut().last_leaf_edge().into_node();
1101 // Iterate through all key-value pairs, pushing them into nodes at the right level.
1102 for (key, value) in iter {
1103 // Try to push key-value pair into the current leaf node.
1104 if cur_node.len() < node::CAPACITY {
1105 cur_node.push(key, value);
1107 // No space left, go up and push there.
1109 let mut test_node = cur_node.forget_type();
1111 match test_node.ascend() {
1113 let parent = parent.into_node();
1114 if parent.len() < node::CAPACITY {
1115 // Found a node with space left, push here.
1120 test_node = parent.forget_type();
1124 // We are at the top, create a new root node and push there.
1125 open_node = node.into_root_mut().push_level();
1131 // Push key-value pair and new right subtree.
1132 let tree_height = open_node.height() - 1;
1133 let mut right_tree = node::Root::new_leaf();
1134 for _ in 0..tree_height {
1135 right_tree.push_level();
1137 open_node.push(key, value, right_tree);
1139 // Go down to the right-most leaf again.
1140 cur_node = open_node.forget_type().last_leaf_edge().into_node();
1147 fn fix_right_edge(&mut self) {
1148 // Handle underfull nodes, start from the top.
1149 let mut cur_node = self.root.as_mut().unwrap().as_mut();
1150 while let Internal(internal) = cur_node.force() {
1151 // Check if right-most child is underfull.
1152 let mut last_edge = internal.last_edge();
1153 let right_child_len = last_edge.reborrow().descend().len();
1154 if right_child_len < node::MIN_LEN {
1155 // We need to steal.
1156 let mut last_kv = match last_edge.left_kv() {
1158 Err(_) => unreachable!(),
1160 last_kv.bulk_steal_left(node::MIN_LEN - right_child_len);
1161 last_edge = last_kv.right_edge();
1165 cur_node = last_edge.descend();
1169 /// Splits the collection into two at the given key. Returns everything after the given key,
1170 /// including the key.
1177 /// use std::collections::BTreeMap;
1179 /// let mut a = BTreeMap::new();
1180 /// a.insert(1, "a");
1181 /// a.insert(2, "b");
1182 /// a.insert(3, "c");
1183 /// a.insert(17, "d");
1184 /// a.insert(41, "e");
1186 /// let b = a.split_off(&3);
1188 /// assert_eq!(a.len(), 2);
1189 /// assert_eq!(b.len(), 3);
1191 /// assert_eq!(a[&1], "a");
1192 /// assert_eq!(a[&2], "b");
1194 /// assert_eq!(b[&3], "c");
1195 /// assert_eq!(b[&17], "d");
1196 /// assert_eq!(b[&41], "e");
1198 #[stable(feature = "btree_split_off", since = "1.11.0")]
1199 pub fn split_off<Q: ?Sized + Ord>(&mut self, key: &Q) -> Self
1203 if self.is_empty() {
1207 let total_num = self.len();
1209 let mut right = Self::new();
1210 right.root = Some(node::Root::new_leaf());
1211 for _ in 0..(self.root.as_ref().unwrap().as_ref().height()) {
1212 right.root.as_mut().unwrap().push_level();
1216 let mut left_node = self.root.as_mut().unwrap().as_mut();
1217 let mut right_node = right.root.as_mut().unwrap().as_mut();
1220 let mut split_edge = match search::search_node(left_node, key) {
1221 // key is going to the right tree
1222 Found(handle) => handle.left_edge(),
1223 GoDown(handle) => handle,
1226 split_edge.move_suffix(&mut right_node);
1228 match (split_edge.force(), right_node.force()) {
1229 (Internal(edge), Internal(node)) => {
1230 left_node = edge.descend();
1231 right_node = node.first_edge().descend();
1233 (Leaf(_), Leaf(_)) => {
1243 self.fix_right_border();
1244 right.fix_left_border();
1246 if self.root.as_ref().unwrap().as_ref().height()
1247 < right.root.as_ref().unwrap().as_ref().height()
1249 self.recalc_length();
1250 right.length = total_num - self.len();
1252 right.recalc_length();
1253 self.length = total_num - right.len();
1259 /// Calculates the number of elements if it is incorrect.
1260 fn recalc_length(&mut self) {
1261 fn dfs<'a, K, V>(node: NodeRef<marker::Immut<'a>, K, V, marker::LeafOrInternal>) -> usize
1266 let mut res = node.len();
1268 if let Internal(node) = node.force() {
1269 let mut edge = node.first_edge();
1271 res += dfs(edge.reborrow().descend());
1272 match edge.right_kv() {
1274 edge = right_kv.right_edge();
1286 self.length = dfs(self.root.as_ref().unwrap().as_ref());
1289 /// Removes empty levels on the top.
1290 fn fix_top(&mut self) {
1293 let node = self.root.as_ref().unwrap().as_ref();
1294 if node.height() == 0 || node.len() > 0 {
1298 self.root.as_mut().unwrap().pop_level();
1302 fn fix_right_border(&mut self) {
1306 let mut cur_node = self.root.as_mut().unwrap().as_mut();
1308 while let Internal(node) = cur_node.force() {
1309 let mut last_kv = node.last_kv();
1311 if last_kv.can_merge() {
1312 cur_node = last_kv.merge().descend();
1314 let right_len = last_kv.reborrow().right_edge().descend().len();
1315 // `MINLEN + 1` to avoid readjust if merge happens on the next level.
1316 if right_len < node::MIN_LEN + 1 {
1317 last_kv.bulk_steal_left(node::MIN_LEN + 1 - right_len);
1319 cur_node = last_kv.right_edge().descend();
1327 /// The symmetric clone of `fix_right_border`.
1328 fn fix_left_border(&mut self) {
1332 let mut cur_node = self.root.as_mut().unwrap().as_mut();
1334 while let Internal(node) = cur_node.force() {
1335 let mut first_kv = node.first_kv();
1337 if first_kv.can_merge() {
1338 cur_node = first_kv.merge().descend();
1340 let left_len = first_kv.reborrow().left_edge().descend().len();
1341 if left_len < node::MIN_LEN + 1 {
1342 first_kv.bulk_steal_right(node::MIN_LEN + 1 - left_len);
1344 cur_node = first_kv.left_edge().descend();
1352 /// If the root node is the empty (non-allocated) root node, allocate our
1354 fn ensure_root_is_owned(&mut self) {
1355 if self.root.is_none() {
1356 self.root = Some(node::Root::new_leaf());
1361 #[stable(feature = "rust1", since = "1.0.0")]
1362 impl<'a, K: 'a, V: 'a> IntoIterator for &'a BTreeMap<K, V> {
1363 type Item = (&'a K, &'a V);
1364 type IntoIter = Iter<'a, K, V>;
1366 fn into_iter(self) -> Iter<'a, K, V> {
1371 #[stable(feature = "rust1", since = "1.0.0")]
1372 impl<'a, K: 'a, V: 'a> Iterator for Iter<'a, K, V> {
1373 type Item = (&'a K, &'a V);
1375 fn next(&mut self) -> Option<(&'a K, &'a V)> {
1376 if self.length == 0 {
1380 unsafe { Some(self.range.next_unchecked()) }
1384 fn size_hint(&self) -> (usize, Option<usize>) {
1385 (self.length, Some(self.length))
1388 fn last(mut self) -> Option<(&'a K, &'a V)> {
1393 #[stable(feature = "fused", since = "1.26.0")]
1394 impl<K, V> FusedIterator for Iter<'_, K, V> {}
1396 #[stable(feature = "rust1", since = "1.0.0")]
1397 impl<'a, K: 'a, V: 'a> DoubleEndedIterator for Iter<'a, K, V> {
1398 fn next_back(&mut self) -> Option<(&'a K, &'a V)> {
1399 if self.length == 0 {
1403 unsafe { Some(self.range.next_back_unchecked()) }
1408 #[stable(feature = "rust1", since = "1.0.0")]
1409 impl<K, V> ExactSizeIterator for Iter<'_, K, V> {
1410 fn len(&self) -> usize {
1415 #[stable(feature = "rust1", since = "1.0.0")]
1416 impl<K, V> Clone for Iter<'_, K, V> {
1417 fn clone(&self) -> Self {
1418 Iter { range: self.range.clone(), length: self.length }
1422 #[stable(feature = "rust1", since = "1.0.0")]
1423 impl<'a, K: 'a, V: 'a> IntoIterator for &'a mut BTreeMap<K, V> {
1424 type Item = (&'a K, &'a mut V);
1425 type IntoIter = IterMut<'a, K, V>;
1427 fn into_iter(self) -> IterMut<'a, K, V> {
1432 #[stable(feature = "rust1", since = "1.0.0")]
1433 impl<'a, K: 'a, V: 'a> Iterator for IterMut<'a, K, V> {
1434 type Item = (&'a K, &'a mut V);
1436 fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
1437 if self.length == 0 {
1441 let (k, v) = unsafe { self.range.next_unchecked() };
1442 Some((k, v)) // coerce k from `&mut K` to `&K`
1446 fn size_hint(&self) -> (usize, Option<usize>) {
1447 (self.length, Some(self.length))
1450 fn last(mut self) -> Option<(&'a K, &'a mut V)> {
1455 #[stable(feature = "rust1", since = "1.0.0")]
1456 impl<'a, K: 'a, V: 'a> DoubleEndedIterator for IterMut<'a, K, V> {
1457 fn next_back(&mut self) -> Option<(&'a K, &'a mut V)> {
1458 if self.length == 0 {
1462 let (k, v) = unsafe { self.range.next_back_unchecked() };
1463 Some((k, v)) // coerce k from `&mut K` to `&K`
1468 #[stable(feature = "rust1", since = "1.0.0")]
1469 impl<K, V> ExactSizeIterator for IterMut<'_, K, V> {
1470 fn len(&self) -> usize {
1475 #[stable(feature = "fused", since = "1.26.0")]
1476 impl<K, V> FusedIterator for IterMut<'_, K, V> {}
1478 #[stable(feature = "rust1", since = "1.0.0")]
1479 impl<K, V> IntoIterator for BTreeMap<K, V> {
1481 type IntoIter = IntoIter<K, V>;
1483 fn into_iter(self) -> IntoIter<K, V> {
1484 if self.root.is_none() {
1486 return IntoIter { front: None, back: None, length: 0 };
1489 let root1 = unsafe { unwrap_unchecked(ptr::read(&self.root)).into_ref() };
1490 let root2 = unsafe { unwrap_unchecked(ptr::read(&self.root)).into_ref() };
1491 let len = self.length;
1495 front: Some(root1.first_leaf_edge()),
1496 back: Some(root2.last_leaf_edge()),
1502 #[stable(feature = "btree_drop", since = "1.7.0")]
1503 impl<K, V> Drop for IntoIter<K, V> {
1504 fn drop(&mut self) {
1505 struct DropGuard<'a, K, V>(&'a mut IntoIter<K, V>);
1507 impl<'a, K, V> Drop for DropGuard<'a, K, V> {
1508 fn drop(&mut self) {
1509 // Continue the same loop we perform below. This only runs when unwinding, so we
1510 // don't have to care about panics this time (they'll abort).
1511 while let Some(_) = self.0.next() {}
1515 unwrap_unchecked(ptr::read(&self.0.front)).into_node().forget_type();
1516 while let Some(parent) = node.deallocate_and_ascend() {
1517 node = parent.into_node().forget_type();
1523 while let Some(pair) = self.next() {
1524 let guard = DropGuard(self);
1530 if let Some(front) = ptr::read(&self.front) {
1531 let mut node = front.into_node().forget_type();
1532 // Most of the nodes have been deallocated while traversing
1533 // but one pile from a leaf up to the root is left standing.
1534 while let Some(parent) = node.deallocate_and_ascend() {
1535 node = parent.into_node().forget_type();
1542 #[stable(feature = "rust1", since = "1.0.0")]
1543 impl<K, V> Iterator for IntoIter<K, V> {
1546 fn next(&mut self) -> Option<(K, V)> {
1547 if self.length == 0 {
1551 Some(unsafe { self.front.as_mut().unwrap().next_unchecked() })
1555 fn size_hint(&self) -> (usize, Option<usize>) {
1556 (self.length, Some(self.length))
1560 #[stable(feature = "rust1", since = "1.0.0")]
1561 impl<K, V> DoubleEndedIterator for IntoIter<K, V> {
1562 fn next_back(&mut self) -> Option<(K, V)> {
1563 if self.length == 0 {
1567 Some(unsafe { self.back.as_mut().unwrap().next_back_unchecked() })
1572 #[stable(feature = "rust1", since = "1.0.0")]
1573 impl<K, V> ExactSizeIterator for IntoIter<K, V> {
1574 fn len(&self) -> usize {
1579 #[stable(feature = "fused", since = "1.26.0")]
1580 impl<K, V> FusedIterator for IntoIter<K, V> {}
1582 #[stable(feature = "rust1", since = "1.0.0")]
1583 impl<'a, K, V> Iterator for Keys<'a, K, V> {
1586 fn next(&mut self) -> Option<&'a K> {
1587 self.inner.next().map(|(k, _)| k)
1590 fn size_hint(&self) -> (usize, Option<usize>) {
1591 self.inner.size_hint()
1594 fn last(mut self) -> Option<&'a K> {
1599 #[stable(feature = "rust1", since = "1.0.0")]
1600 impl<'a, K, V> DoubleEndedIterator for Keys<'a, K, V> {
1601 fn next_back(&mut self) -> Option<&'a K> {
1602 self.inner.next_back().map(|(k, _)| k)
1606 #[stable(feature = "rust1", since = "1.0.0")]
1607 impl<K, V> ExactSizeIterator for Keys<'_, K, V> {
1608 fn len(&self) -> usize {
1613 #[stable(feature = "fused", since = "1.26.0")]
1614 impl<K, V> FusedIterator for Keys<'_, K, V> {}
1616 #[stable(feature = "rust1", since = "1.0.0")]
1617 impl<K, V> Clone for Keys<'_, K, V> {
1618 fn clone(&self) -> Self {
1619 Keys { inner: self.inner.clone() }
1623 #[stable(feature = "rust1", since = "1.0.0")]
1624 impl<'a, K, V> Iterator for Values<'a, K, V> {
1627 fn next(&mut self) -> Option<&'a V> {
1628 self.inner.next().map(|(_, v)| v)
1631 fn size_hint(&self) -> (usize, Option<usize>) {
1632 self.inner.size_hint()
1635 fn last(mut self) -> Option<&'a V> {
1640 #[stable(feature = "rust1", since = "1.0.0")]
1641 impl<'a, K, V> DoubleEndedIterator for Values<'a, K, V> {
1642 fn next_back(&mut self) -> Option<&'a V> {
1643 self.inner.next_back().map(|(_, v)| v)
1647 #[stable(feature = "rust1", since = "1.0.0")]
1648 impl<K, V> ExactSizeIterator for Values<'_, K, V> {
1649 fn len(&self) -> usize {
1654 #[stable(feature = "fused", since = "1.26.0")]
1655 impl<K, V> FusedIterator for Values<'_, K, V> {}
1657 #[stable(feature = "rust1", since = "1.0.0")]
1658 impl<K, V> Clone for Values<'_, K, V> {
1659 fn clone(&self) -> Self {
1660 Values { inner: self.inner.clone() }
1664 #[stable(feature = "btree_range", since = "1.17.0")]
1665 impl<'a, K, V> Iterator for Range<'a, K, V> {
1666 type Item = (&'a K, &'a V);
1668 fn next(&mut self) -> Option<(&'a K, &'a V)> {
1669 if self.is_empty() { None } else { unsafe { Some(self.next_unchecked()) } }
1672 fn last(mut self) -> Option<(&'a K, &'a V)> {
1677 #[stable(feature = "map_values_mut", since = "1.10.0")]
1678 impl<'a, K, V> Iterator for ValuesMut<'a, K, V> {
1679 type Item = &'a mut V;
1681 fn next(&mut self) -> Option<&'a mut V> {
1682 self.inner.next().map(|(_, v)| v)
1685 fn size_hint(&self) -> (usize, Option<usize>) {
1686 self.inner.size_hint()
1689 fn last(mut self) -> Option<&'a mut V> {
1694 #[stable(feature = "map_values_mut", since = "1.10.0")]
1695 impl<'a, K, V> DoubleEndedIterator for ValuesMut<'a, K, V> {
1696 fn next_back(&mut self) -> Option<&'a mut V> {
1697 self.inner.next_back().map(|(_, v)| v)
1701 #[stable(feature = "map_values_mut", since = "1.10.0")]
1702 impl<K, V> ExactSizeIterator for ValuesMut<'_, K, V> {
1703 fn len(&self) -> usize {
1708 #[stable(feature = "fused", since = "1.26.0")]
1709 impl<K, V> FusedIterator for ValuesMut<'_, K, V> {}
1711 impl<'a, K, V> Range<'a, K, V> {
1712 fn is_empty(&self) -> bool {
1713 self.front == self.back
1716 unsafe fn next_unchecked(&mut self) -> (&'a K, &'a V) {
1717 unwrap_unchecked(self.front.as_mut()).next_unchecked()
1721 #[stable(feature = "btree_range", since = "1.17.0")]
1722 impl<'a, K, V> DoubleEndedIterator for Range<'a, K, V> {
1723 fn next_back(&mut self) -> Option<(&'a K, &'a V)> {
1724 if self.is_empty() { None } else { Some(unsafe { self.next_back_unchecked() }) }
1728 impl<'a, K, V> Range<'a, K, V> {
1729 unsafe fn next_back_unchecked(&mut self) -> (&'a K, &'a V) {
1730 unwrap_unchecked(self.back.as_mut()).next_back_unchecked()
1734 #[stable(feature = "fused", since = "1.26.0")]
1735 impl<K, V> FusedIterator for Range<'_, K, V> {}
1737 #[stable(feature = "btree_range", since = "1.17.0")]
1738 impl<K, V> Clone for Range<'_, K, V> {
1739 fn clone(&self) -> Self {
1740 Range { front: self.front, back: self.back }
1744 #[stable(feature = "btree_range", since = "1.17.0")]
1745 impl<'a, K, V> Iterator for RangeMut<'a, K, V> {
1746 type Item = (&'a K, &'a mut V);
1748 fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
1749 if self.is_empty() {
1752 let (k, v) = unsafe { self.next_unchecked() };
1753 Some((k, v)) // coerce k from `&mut K` to `&K`
1757 fn last(mut self) -> Option<(&'a K, &'a mut V)> {
1762 impl<'a, K, V> RangeMut<'a, K, V> {
1763 fn is_empty(&self) -> bool {
1764 self.front == self.back
1767 unsafe fn next_unchecked(&mut self) -> (&'a mut K, &'a mut V) {
1768 unwrap_unchecked(self.front.as_mut()).next_unchecked()
1772 #[stable(feature = "btree_range", since = "1.17.0")]
1773 impl<'a, K, V> DoubleEndedIterator for RangeMut<'a, K, V> {
1774 fn next_back(&mut self) -> Option<(&'a K, &'a mut V)> {
1775 if self.is_empty() {
1778 let (k, v) = unsafe { self.next_back_unchecked() };
1779 Some((k, v)) // coerce k from `&mut K` to `&K`
1784 #[stable(feature = "fused", since = "1.26.0")]
1785 impl<K, V> FusedIterator for RangeMut<'_, K, V> {}
1787 impl<'a, K, V> RangeMut<'a, K, V> {
1788 unsafe fn next_back_unchecked(&mut self) -> (&'a mut K, &'a mut V) {
1789 unwrap_unchecked(self.back.as_mut()).next_back_unchecked()
1793 #[stable(feature = "rust1", since = "1.0.0")]
1794 impl<K: Ord, V> FromIterator<(K, V)> for BTreeMap<K, V> {
1795 fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> BTreeMap<K, V> {
1796 let mut map = BTreeMap::new();
1802 #[stable(feature = "rust1", since = "1.0.0")]
1803 impl<K: Ord, V> Extend<(K, V)> for BTreeMap<K, V> {
1805 fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) {
1806 iter.into_iter().for_each(move |(k, v)| {
1812 #[stable(feature = "extend_ref", since = "1.2.0")]
1813 impl<'a, K: Ord + Copy, V: Copy> Extend<(&'a K, &'a V)> for BTreeMap<K, V> {
1814 fn extend<I: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: I) {
1815 self.extend(iter.into_iter().map(|(&key, &value)| (key, value)));
1819 #[stable(feature = "rust1", since = "1.0.0")]
1820 impl<K: Hash, V: Hash> Hash for BTreeMap<K, V> {
1821 fn hash<H: Hasher>(&self, state: &mut H) {
1828 #[stable(feature = "rust1", since = "1.0.0")]
1829 impl<K: Ord, V> Default for BTreeMap<K, V> {
1830 /// Creates an empty `BTreeMap<K, V>`.
1831 fn default() -> BTreeMap<K, V> {
1836 #[stable(feature = "rust1", since = "1.0.0")]
1837 impl<K: PartialEq, V: PartialEq> PartialEq for BTreeMap<K, V> {
1838 fn eq(&self, other: &BTreeMap<K, V>) -> bool {
1839 self.len() == other.len() && self.iter().zip(other).all(|(a, b)| a == b)
1843 #[stable(feature = "rust1", since = "1.0.0")]
1844 impl<K: Eq, V: Eq> Eq for BTreeMap<K, V> {}
1846 #[stable(feature = "rust1", since = "1.0.0")]
1847 impl<K: PartialOrd, V: PartialOrd> PartialOrd for BTreeMap<K, V> {
1849 fn partial_cmp(&self, other: &BTreeMap<K, V>) -> Option<Ordering> {
1850 self.iter().partial_cmp(other.iter())
1854 #[stable(feature = "rust1", since = "1.0.0")]
1855 impl<K: Ord, V: Ord> Ord for BTreeMap<K, V> {
1857 fn cmp(&self, other: &BTreeMap<K, V>) -> Ordering {
1858 self.iter().cmp(other.iter())
1862 #[stable(feature = "rust1", since = "1.0.0")]
1863 impl<K: Debug, V: Debug> Debug for BTreeMap<K, V> {
1864 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1865 f.debug_map().entries(self.iter()).finish()
1869 #[stable(feature = "rust1", since = "1.0.0")]
1870 impl<K: Ord, Q: ?Sized, V> Index<&Q> for BTreeMap<K, V>
1877 /// Returns a reference to the value corresponding to the supplied key.
1881 /// Panics if the key is not present in the `BTreeMap`.
1883 fn index(&self, key: &Q) -> &V {
1884 self.get(key).expect("no entry found for key")
1888 fn range_search<BorrowType, K, V, Q: ?Sized, R: RangeBounds<Q>>(
1889 root1: NodeRef<BorrowType, K, V, marker::LeafOrInternal>,
1890 root2: NodeRef<BorrowType, K, V, marker::LeafOrInternal>,
1893 Handle<NodeRef<BorrowType, K, V, marker::Leaf>, marker::Edge>,
1894 Handle<NodeRef<BorrowType, K, V, marker::Leaf>, marker::Edge>,
1900 match (range.start_bound(), range.end_bound()) {
1901 (Excluded(s), Excluded(e)) if s == e => {
1902 panic!("range start and end are equal and excluded in BTreeMap")
1904 (Included(s), Included(e))
1905 | (Included(s), Excluded(e))
1906 | (Excluded(s), Included(e))
1907 | (Excluded(s), Excluded(e))
1910 panic!("range start is greater than range end in BTreeMap")
1915 let mut min_node = root1;
1916 let mut max_node = root2;
1917 let mut min_found = false;
1918 let mut max_found = false;
1921 let front = match (min_found, range.start_bound()) {
1922 (false, Included(key)) => match search::search_node(min_node, key) {
1927 GoDown(edge) => edge,
1929 (false, Excluded(key)) => match search::search_node(min_node, key) {
1934 GoDown(edge) => edge,
1936 (true, Included(_)) => min_node.last_edge(),
1937 (true, Excluded(_)) => min_node.first_edge(),
1938 (_, Unbounded) => min_node.first_edge(),
1941 let back = match (max_found, range.end_bound()) {
1942 (false, Included(key)) => match search::search_node(max_node, key) {
1947 GoDown(edge) => edge,
1949 (false, Excluded(key)) => match search::search_node(max_node, key) {
1954 GoDown(edge) => edge,
1956 (true, Included(_)) => max_node.first_edge(),
1957 (true, Excluded(_)) => max_node.last_edge(),
1958 (_, Unbounded) => max_node.last_edge(),
1961 if front.partial_cmp(&back) == Some(Ordering::Greater) {
1962 panic!("Ord is ill-defined in BTreeMap range");
1964 match (front.force(), back.force()) {
1965 (Leaf(f), Leaf(b)) => {
1968 (Internal(min_int), Internal(max_int)) => {
1969 min_node = min_int.descend();
1970 max_node = max_int.descend();
1972 _ => unreachable!("BTreeMap has different depths"),
1977 impl<K, V> BTreeMap<K, V> {
1978 /// Gets an iterator over the entries of the map, sorted by key.
1985 /// use std::collections::BTreeMap;
1987 /// let mut map = BTreeMap::new();
1988 /// map.insert(3, "c");
1989 /// map.insert(2, "b");
1990 /// map.insert(1, "a");
1992 /// for (key, value) in map.iter() {
1993 /// println!("{}: {}", key, value);
1996 /// let (first_key, first_value) = map.iter().next().unwrap();
1997 /// assert_eq!((*first_key, *first_value), (1, "a"));
1999 #[stable(feature = "rust1", since = "1.0.0")]
2000 pub fn iter(&self) -> Iter<'_, K, V> {
2003 front: self.root.as_ref().map(|r| r.as_ref().first_leaf_edge()),
2004 back: self.root.as_ref().map(|r| r.as_ref().last_leaf_edge()),
2006 length: self.length,
2010 /// Gets a mutable iterator over the entries of the map, sorted by key.
2017 /// use std::collections::BTreeMap;
2019 /// let mut map = BTreeMap::new();
2020 /// map.insert("a", 1);
2021 /// map.insert("b", 2);
2022 /// map.insert("c", 3);
2024 /// // add 10 to the value if the key isn't "a"
2025 /// for (key, value) in map.iter_mut() {
2026 /// if key != &"a" {
2031 #[stable(feature = "rust1", since = "1.0.0")]
2032 pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {
2034 range: if let Some(root) = &mut self.root {
2035 let root1 = root.as_mut();
2036 let root2 = unsafe { ptr::read(&root1) };
2038 front: Some(root1.first_leaf_edge()),
2039 back: Some(root2.last_leaf_edge()),
2040 _marker: PhantomData,
2043 RangeMut { front: None, back: None, _marker: PhantomData }
2045 length: self.length,
2049 /// Gets an iterator over the keys of the map, in sorted order.
2056 /// use std::collections::BTreeMap;
2058 /// let mut a = BTreeMap::new();
2059 /// a.insert(2, "b");
2060 /// a.insert(1, "a");
2062 /// let keys: Vec<_> = a.keys().cloned().collect();
2063 /// assert_eq!(keys, [1, 2]);
2065 #[stable(feature = "rust1", since = "1.0.0")]
2066 pub fn keys(&self) -> Keys<'_, K, V> {
2067 Keys { inner: self.iter() }
2070 /// Gets an iterator over the values of the map, in order by key.
2077 /// use std::collections::BTreeMap;
2079 /// let mut a = BTreeMap::new();
2080 /// a.insert(1, "hello");
2081 /// a.insert(2, "goodbye");
2083 /// let values: Vec<&str> = a.values().cloned().collect();
2084 /// assert_eq!(values, ["hello", "goodbye"]);
2086 #[stable(feature = "rust1", since = "1.0.0")]
2087 pub fn values(&self) -> Values<'_, K, V> {
2088 Values { inner: self.iter() }
2091 /// Gets a mutable iterator over the values of the map, in order by key.
2098 /// use std::collections::BTreeMap;
2100 /// let mut a = BTreeMap::new();
2101 /// a.insert(1, String::from("hello"));
2102 /// a.insert(2, String::from("goodbye"));
2104 /// for value in a.values_mut() {
2105 /// value.push_str("!");
2108 /// let values: Vec<String> = a.values().cloned().collect();
2109 /// assert_eq!(values, [String::from("hello!"),
2110 /// String::from("goodbye!")]);
2112 #[stable(feature = "map_values_mut", since = "1.10.0")]
2113 pub fn values_mut(&mut self) -> ValuesMut<'_, K, V> {
2114 ValuesMut { inner: self.iter_mut() }
2117 /// Returns the number of elements in the map.
2124 /// use std::collections::BTreeMap;
2126 /// let mut a = BTreeMap::new();
2127 /// assert_eq!(a.len(), 0);
2128 /// a.insert(1, "a");
2129 /// assert_eq!(a.len(), 1);
2131 #[stable(feature = "rust1", since = "1.0.0")]
2132 pub fn len(&self) -> usize {
2136 /// Returns `true` if the map contains no elements.
2143 /// use std::collections::BTreeMap;
2145 /// let mut a = BTreeMap::new();
2146 /// assert!(a.is_empty());
2147 /// a.insert(1, "a");
2148 /// assert!(!a.is_empty());
2150 #[stable(feature = "rust1", since = "1.0.0")]
2151 pub fn is_empty(&self) -> bool {
2156 impl<'a, K: Ord, V> Entry<'a, K, V> {
2157 /// Ensures a value is in the entry by inserting the default if empty, and returns
2158 /// a mutable reference to the value in the entry.
2163 /// use std::collections::BTreeMap;
2165 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2166 /// map.entry("poneyland").or_insert(12);
2168 /// assert_eq!(map["poneyland"], 12);
2170 #[stable(feature = "rust1", since = "1.0.0")]
2171 pub fn or_insert(self, default: V) -> &'a mut V {
2173 Occupied(entry) => entry.into_mut(),
2174 Vacant(entry) => entry.insert(default),
2178 /// Ensures a value is in the entry by inserting the result of the default function if empty,
2179 /// and returns a mutable reference to the value in the entry.
2184 /// use std::collections::BTreeMap;
2186 /// let mut map: BTreeMap<&str, String> = BTreeMap::new();
2187 /// let s = "hoho".to_string();
2189 /// map.entry("poneyland").or_insert_with(|| s);
2191 /// assert_eq!(map["poneyland"], "hoho".to_string());
2193 #[stable(feature = "rust1", since = "1.0.0")]
2194 pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V {
2196 Occupied(entry) => entry.into_mut(),
2197 Vacant(entry) => entry.insert(default()),
2201 /// Returns a reference to this entry's key.
2206 /// use std::collections::BTreeMap;
2208 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2209 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2211 #[stable(feature = "map_entry_keys", since = "1.10.0")]
2212 pub fn key(&self) -> &K {
2214 Occupied(ref entry) => entry.key(),
2215 Vacant(ref entry) => entry.key(),
2219 /// Provides in-place mutable access to an occupied entry before any
2220 /// potential inserts into the map.
2225 /// use std::collections::BTreeMap;
2227 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2229 /// map.entry("poneyland")
2230 /// .and_modify(|e| { *e += 1 })
2232 /// assert_eq!(map["poneyland"], 42);
2234 /// map.entry("poneyland")
2235 /// .and_modify(|e| { *e += 1 })
2237 /// assert_eq!(map["poneyland"], 43);
2239 #[stable(feature = "entry_and_modify", since = "1.26.0")]
2240 pub fn and_modify<F>(self, f: F) -> Self
2245 Occupied(mut entry) => {
2249 Vacant(entry) => Vacant(entry),
2254 impl<'a, K: Ord, V: Default> Entry<'a, K, V> {
2255 #[stable(feature = "entry_or_default", since = "1.28.0")]
2256 /// Ensures a value is in the entry by inserting the default value if empty,
2257 /// and returns a mutable reference to the value in the entry.
2262 /// use std::collections::BTreeMap;
2264 /// let mut map: BTreeMap<&str, Option<usize>> = BTreeMap::new();
2265 /// map.entry("poneyland").or_default();
2267 /// assert_eq!(map["poneyland"], None);
2269 pub fn or_default(self) -> &'a mut V {
2271 Occupied(entry) => entry.into_mut(),
2272 Vacant(entry) => entry.insert(Default::default()),
2277 impl<'a, K: Ord, V> VacantEntry<'a, K, V> {
2278 /// Gets a reference to the key that would be used when inserting a value
2279 /// through the VacantEntry.
2284 /// use std::collections::BTreeMap;
2286 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2287 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2289 #[stable(feature = "map_entry_keys", since = "1.10.0")]
2290 pub fn key(&self) -> &K {
2294 /// Take ownership of the key.
2299 /// use std::collections::BTreeMap;
2300 /// use std::collections::btree_map::Entry;
2302 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2304 /// if let Entry::Vacant(v) = map.entry("poneyland") {
2308 #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")]
2309 pub fn into_key(self) -> K {
2313 /// Sets the value of the entry with the `VacantEntry`'s key,
2314 /// and returns a mutable reference to it.
2319 /// use std::collections::BTreeMap;
2321 /// let mut count: BTreeMap<&str, usize> = BTreeMap::new();
2323 /// // count the number of occurrences of letters in the vec
2324 /// for x in vec!["a","b","a","c","a","b"] {
2325 /// *count.entry(x).or_insert(0) += 1;
2328 /// assert_eq!(count["a"], 3);
2330 #[stable(feature = "rust1", since = "1.0.0")]
2331 pub fn insert(self, value: V) -> &'a mut V {
2340 let mut cur_parent = match self.handle.insert(self.key, value) {
2341 (Fit(handle), _) => return handle.into_kv_mut().1,
2342 (Split(left, k, v, right), ptr) => {
2347 left.ascend().map_err(|n| n.into_root_mut())
2353 Ok(parent) => match parent.insert(ins_k, ins_v, ins_edge) {
2354 Fit(_) => return unsafe { &mut *out_ptr },
2355 Split(left, k, v, right) => {
2359 cur_parent = left.ascend().map_err(|n| n.into_root_mut());
2363 root.push_level().push(ins_k, ins_v, ins_edge);
2364 return unsafe { &mut *out_ptr };
2371 impl<'a, K: Ord, V> OccupiedEntry<'a, K, V> {
2372 /// Gets a reference to the key in the entry.
2377 /// use std::collections::BTreeMap;
2379 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2380 /// map.entry("poneyland").or_insert(12);
2381 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2383 #[stable(feature = "map_entry_keys", since = "1.10.0")]
2384 pub fn key(&self) -> &K {
2385 self.handle.reborrow().into_kv().0
2388 /// Take ownership of the key and value from the map.
2393 /// use std::collections::BTreeMap;
2394 /// use std::collections::btree_map::Entry;
2396 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2397 /// map.entry("poneyland").or_insert(12);
2399 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2400 /// // We delete the entry from the map.
2401 /// o.remove_entry();
2404 /// // If now try to get the value, it will panic:
2405 /// // println!("{}", map["poneyland"]);
2407 #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")]
2408 pub fn remove_entry(self) -> (K, V) {
2412 /// Gets a reference to the value in the entry.
2417 /// use std::collections::BTreeMap;
2418 /// use std::collections::btree_map::Entry;
2420 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2421 /// map.entry("poneyland").or_insert(12);
2423 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2424 /// assert_eq!(o.get(), &12);
2427 #[stable(feature = "rust1", since = "1.0.0")]
2428 pub fn get(&self) -> &V {
2429 self.handle.reborrow().into_kv().1
2432 /// Gets a mutable reference to the value in the entry.
2434 /// If you need a reference to the `OccupiedEntry` that may outlive the
2435 /// destruction of the `Entry` value, see [`into_mut`].
2437 /// [`into_mut`]: #method.into_mut
2442 /// use std::collections::BTreeMap;
2443 /// use std::collections::btree_map::Entry;
2445 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2446 /// map.entry("poneyland").or_insert(12);
2448 /// assert_eq!(map["poneyland"], 12);
2449 /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
2450 /// *o.get_mut() += 10;
2451 /// assert_eq!(*o.get(), 22);
2453 /// // We can use the same Entry multiple times.
2454 /// *o.get_mut() += 2;
2456 /// assert_eq!(map["poneyland"], 24);
2458 #[stable(feature = "rust1", since = "1.0.0")]
2459 pub fn get_mut(&mut self) -> &mut V {
2460 self.handle.kv_mut().1
2463 /// Converts the entry into a mutable reference to its value.
2465 /// If you need multiple references to the `OccupiedEntry`, see [`get_mut`].
2467 /// [`get_mut`]: #method.get_mut
2472 /// use std::collections::BTreeMap;
2473 /// use std::collections::btree_map::Entry;
2475 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2476 /// map.entry("poneyland").or_insert(12);
2478 /// assert_eq!(map["poneyland"], 12);
2479 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2480 /// *o.into_mut() += 10;
2482 /// assert_eq!(map["poneyland"], 22);
2484 #[stable(feature = "rust1", since = "1.0.0")]
2485 pub fn into_mut(self) -> &'a mut V {
2486 self.handle.into_kv_mut().1
2489 /// Sets the value of the entry with the `OccupiedEntry`'s key,
2490 /// and returns the entry's old value.
2495 /// use std::collections::BTreeMap;
2496 /// use std::collections::btree_map::Entry;
2498 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2499 /// map.entry("poneyland").or_insert(12);
2501 /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
2502 /// assert_eq!(o.insert(15), 12);
2504 /// assert_eq!(map["poneyland"], 15);
2506 #[stable(feature = "rust1", since = "1.0.0")]
2507 pub fn insert(&mut self, value: V) -> V {
2508 mem::replace(self.get_mut(), value)
2511 /// Takes the value of the entry out of the map, and returns it.
2516 /// use std::collections::BTreeMap;
2517 /// use std::collections::btree_map::Entry;
2519 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2520 /// map.entry("poneyland").or_insert(12);
2522 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2523 /// assert_eq!(o.remove(), 12);
2525 /// // If we try to get "poneyland"'s value, it'll panic:
2526 /// // println!("{}", map["poneyland"]);
2528 #[stable(feature = "rust1", since = "1.0.0")]
2529 pub fn remove(self) -> V {
2533 fn remove_kv(self) -> (K, V) {
2536 let (small_leaf, old_key, old_val) = match self.handle.force() {
2538 let (hole, old_key, old_val) = leaf.remove();
2539 (hole.into_node(), old_key, old_val)
2541 Internal(mut internal) => {
2542 let key_loc = internal.kv_mut().0 as *mut K;
2543 let val_loc = internal.kv_mut().1 as *mut V;
2545 let to_remove = internal.right_edge().descend().first_leaf_edge().right_kv().ok();
2546 let to_remove = unsafe { unwrap_unchecked(to_remove) };
2548 let (hole, key, val) = to_remove.remove();
2550 let old_key = unsafe { mem::replace(&mut *key_loc, key) };
2551 let old_val = unsafe { mem::replace(&mut *val_loc, val) };
2553 (hole.into_node(), old_key, old_val)
2558 let mut cur_node = small_leaf.forget_type();
2559 while cur_node.len() < node::MIN_LEN {
2560 match handle_underfull_node(cur_node) {
2562 EmptyParent(_) => unreachable!(),
2564 if parent.len() == 0 {
2565 // We must be at the root
2566 parent.into_root_mut().pop_level();
2569 cur_node = parent.forget_type();
2580 enum UnderflowResult<'a, K, V> {
2582 EmptyParent(NodeRef<marker::Mut<'a>, K, V, marker::Internal>),
2583 Merged(NodeRef<marker::Mut<'a>, K, V, marker::Internal>),
2584 Stole(NodeRef<marker::Mut<'a>, K, V, marker::Internal>),
2587 fn handle_underfull_node<K, V>(
2588 node: NodeRef<marker::Mut<'_>, K, V, marker::LeafOrInternal>,
2589 ) -> UnderflowResult<'_, K, V> {
2590 let parent = if let Ok(parent) = node.ascend() {
2596 let (is_left, mut handle) = match parent.left_kv() {
2597 Ok(left) => (true, left),
2598 Err(parent) => match parent.right_kv() {
2599 Ok(right) => (false, right),
2601 return EmptyParent(parent.into_node());
2606 if handle.can_merge() {
2607 Merged(handle.merge().into_node())
2610 handle.steal_left();
2612 handle.steal_right();
2614 Stole(handle.into_node())
2618 impl<K: Ord, V, I: Iterator<Item = (K, V)>> Iterator for MergeIter<K, V, I> {
2621 fn next(&mut self) -> Option<(K, V)> {
2622 let res = match (self.left.peek(), self.right.peek()) {
2623 (Some(&(ref left_key, _)), Some(&(ref right_key, _))) => left_key.cmp(right_key),
2624 (Some(_), None) => Ordering::Less,
2625 (None, Some(_)) => Ordering::Greater,
2626 (None, None) => return None,
2629 // Check which elements comes first and only advance the corresponding iterator.
2630 // If two keys are equal, take the value from `right`.
2632 Ordering::Less => self.left.next(),
2633 Ordering::Greater => self.right.next(),
2634 Ordering::Equal => {