]> git.lizzy.rs Git - rust.git/blob - library/alloc/src/collections/btree/map.rs
Add diagnostic items
[rust.git] / library / alloc / src / collections / btree / map.rs
1 use core::borrow::Borrow;
2 use core::cmp::Ordering;
3 use core::fmt::{self, Debug};
4 use core::hash::{Hash, Hasher};
5 use core::iter::{FromIterator, FusedIterator};
6 use core::marker::PhantomData;
7 use core::mem::{self, ManuallyDrop};
8 use core::ops::{Index, RangeBounds};
9 use core::ptr;
10
11 use super::borrow::DormantMutRef;
12 use super::navigate::LeafRange;
13 use super::node::{self, marker, ForceResult::*, Handle, NodeRef, Root};
14 use super::search::SearchResult::*;
15
16 mod entry;
17 pub use entry::{Entry, OccupiedEntry, VacantEntry};
18 use Entry::*;
19
20 /// Minimum number of elements in nodes that are not a root.
21 /// We might temporarily have fewer elements during methods.
22 pub(super) const MIN_LEN: usize = node::MIN_LEN_AFTER_SPLIT;
23
24 // A tree in a `BTreeMap` is a tree in the `node` module with addtional invariants:
25 // - Keys must appear in ascending order (according to the key's type).
26 // - If the root node is internal, it must contain at least 1 element.
27 // - Every non-root node contains at least MIN_LEN elements.
28 //
29 // An empty map may be represented both by the absense of a root node or by a
30 // root node that is an empty leaf.
31
32 /// A map based on a B-Tree.
33 ///
34 /// B-Trees represent a fundamental compromise between cache-efficiency and actually minimizing
35 /// the amount of work performed in a search. In theory, a binary search tree (BST) is the optimal
36 /// choice for a sorted map, as a perfectly balanced BST performs the theoretical minimum amount of
37 /// comparisons necessary to find an element (log<sub>2</sub>n). However, in practice the way this
38 /// is done is *very* inefficient for modern computer architectures. In particular, every element
39 /// is stored in its own individually heap-allocated node. This means that every single insertion
40 /// triggers a heap-allocation, and every single comparison should be a cache-miss. Since these
41 /// are both notably expensive things to do in practice, we are forced to at very least reconsider
42 /// the BST strategy.
43 ///
44 /// A B-Tree instead makes each node contain B-1 to 2B-1 elements in a contiguous array. By doing
45 /// this, we reduce the number of allocations by a factor of B, and improve cache efficiency in
46 /// searches. However, this does mean that searches will have to do *more* comparisons on average.
47 /// The precise number of comparisons depends on the node search strategy used. For optimal cache
48 /// efficiency, one could search the nodes linearly. For optimal comparisons, one could search
49 /// the node using binary search. As a compromise, one could also perform a linear search
50 /// that initially only checks every i<sup>th</sup> element for some choice of i.
51 ///
52 /// Currently, our implementation simply performs naive linear search. This provides excellent
53 /// performance on *small* nodes of elements which are cheap to compare. However in the future we
54 /// would like to further explore choosing the optimal search strategy based on the choice of B,
55 /// and possibly other factors. Using linear search, searching for a random element is expected
56 /// to take O(B * log(n)) comparisons, which is generally worse than a BST. In practice,
57 /// however, performance is excellent.
58 ///
59 /// It is a logic error for a key to be modified in such a way that the key's ordering relative to
60 /// any other key, as determined by the [`Ord`] trait, changes while it is in the map. This is
61 /// normally only possible through [`Cell`], [`RefCell`], global state, I/O, or unsafe code.
62 /// The behavior resulting from such a logic error is not specified, but will not result in
63 /// undefined behavior. This could include panics, incorrect results, aborts, memory leaks, and
64 /// non-termination.
65 ///
66 /// [`Cell`]: core::cell::Cell
67 /// [`RefCell`]: core::cell::RefCell
68 ///
69 /// # Examples
70 ///
71 /// ```
72 /// use std::collections::BTreeMap;
73 ///
74 /// // type inference lets us omit an explicit type signature (which
75 /// // would be `BTreeMap<&str, &str>` in this example).
76 /// let mut movie_reviews = BTreeMap::new();
77 ///
78 /// // review some movies.
79 /// movie_reviews.insert("Office Space",       "Deals with real issues in the workplace.");
80 /// movie_reviews.insert("Pulp Fiction",       "Masterpiece.");
81 /// movie_reviews.insert("The Godfather",      "Very enjoyable.");
82 /// movie_reviews.insert("The Blues Brothers", "Eye lyked it a lot.");
83 ///
84 /// // check for a specific one.
85 /// if !movie_reviews.contains_key("Les Misérables") {
86 ///     println!("We've got {} reviews, but Les Misérables ain't one.",
87 ///              movie_reviews.len());
88 /// }
89 ///
90 /// // oops, this review has a lot of spelling mistakes, let's delete it.
91 /// movie_reviews.remove("The Blues Brothers");
92 ///
93 /// // look up the values associated with some keys.
94 /// let to_find = ["Up!", "Office Space"];
95 /// for movie in &to_find {
96 ///     match movie_reviews.get(movie) {
97 ///        Some(review) => println!("{}: {}", movie, review),
98 ///        None => println!("{} is unreviewed.", movie)
99 ///     }
100 /// }
101 ///
102 /// // Look up the value for a key (will panic if the key is not found).
103 /// println!("Movie review: {}", movie_reviews["Office Space"]);
104 ///
105 /// // iterate over everything.
106 /// for (movie, review) in &movie_reviews {
107 ///     println!("{}: \"{}\"", movie, review);
108 /// }
109 /// ```
110 ///
111 /// `BTreeMap` also implements an [`Entry API`], which allows for more complex
112 /// methods of getting, setting, updating and removing keys and their values:
113 ///
114 /// [`Entry API`]: BTreeMap::entry
115 ///
116 /// ```
117 /// use std::collections::BTreeMap;
118 ///
119 /// // type inference lets us omit an explicit type signature (which
120 /// // would be `BTreeMap<&str, u8>` in this example).
121 /// let mut player_stats = BTreeMap::new();
122 ///
123 /// fn random_stat_buff() -> u8 {
124 ///     // could actually return some random value here - let's just return
125 ///     // some fixed value for now
126 ///     42
127 /// }
128 ///
129 /// // insert a key only if it doesn't already exist
130 /// player_stats.entry("health").or_insert(100);
131 ///
132 /// // insert a key using a function that provides a new value only if it
133 /// // doesn't already exist
134 /// player_stats.entry("defence").or_insert_with(random_stat_buff);
135 ///
136 /// // update a key, guarding against the key possibly not being set
137 /// let stat = player_stats.entry("attack").or_insert(100);
138 /// *stat += random_stat_buff();
139 /// ```
140 #[stable(feature = "rust1", since = "1.0.0")]
141 #[cfg_attr(not(test), rustc_diagnostic_item = "BTreeMap")]
142 pub struct BTreeMap<K, V> {
143     root: Option<Root<K, V>>,
144     length: usize,
145 }
146
147 #[stable(feature = "btree_drop", since = "1.7.0")]
148 unsafe impl<#[may_dangle] K, #[may_dangle] V> Drop for BTreeMap<K, V> {
149     fn drop(&mut self) {
150         if let Some(root) = self.root.take() {
151             Dropper { front: root.into_dying().first_leaf_edge(), remaining_length: self.length };
152         }
153     }
154 }
155
156 #[stable(feature = "rust1", since = "1.0.0")]
157 impl<K: Clone, V: Clone> Clone for BTreeMap<K, V> {
158     fn clone(&self) -> BTreeMap<K, V> {
159         fn clone_subtree<'a, K: Clone, V: Clone>(
160             node: NodeRef<marker::Immut<'a>, K, V, marker::LeafOrInternal>,
161         ) -> BTreeMap<K, V>
162         where
163             K: 'a,
164             V: 'a,
165         {
166             match node.force() {
167                 Leaf(leaf) => {
168                     let mut out_tree = BTreeMap { root: Some(Root::new()), length: 0 };
169
170                     {
171                         let root = out_tree.root.as_mut().unwrap(); // unwrap succeeds because we just wrapped
172                         let mut out_node = match root.borrow_mut().force() {
173                             Leaf(leaf) => leaf,
174                             Internal(_) => unreachable!(),
175                         };
176
177                         let mut in_edge = leaf.first_edge();
178                         while let Ok(kv) = in_edge.right_kv() {
179                             let (k, v) = kv.into_kv();
180                             in_edge = kv.right_edge();
181
182                             out_node.push(k.clone(), v.clone());
183                             out_tree.length += 1;
184                         }
185                     }
186
187                     out_tree
188                 }
189                 Internal(internal) => {
190                     let mut out_tree = clone_subtree(internal.first_edge().descend());
191
192                     {
193                         let out_root = BTreeMap::ensure_is_owned(&mut out_tree.root);
194                         let mut out_node = out_root.push_internal_level();
195                         let mut in_edge = internal.first_edge();
196                         while let Ok(kv) = in_edge.right_kv() {
197                             let (k, v) = kv.into_kv();
198                             in_edge = kv.right_edge();
199
200                             let k = (*k).clone();
201                             let v = (*v).clone();
202                             let subtree = clone_subtree(in_edge.descend());
203
204                             // We can't destructure subtree directly
205                             // because BTreeMap implements Drop
206                             let (subroot, sublength) = unsafe {
207                                 let subtree = ManuallyDrop::new(subtree);
208                                 let root = ptr::read(&subtree.root);
209                                 let length = subtree.length;
210                                 (root, length)
211                             };
212
213                             out_node.push(k, v, subroot.unwrap_or_else(Root::new));
214                             out_tree.length += 1 + sublength;
215                         }
216                     }
217
218                     out_tree
219                 }
220             }
221         }
222
223         if self.is_empty() {
224             // Ideally we'd call `BTreeMap::new` here, but that has the `K:
225             // Ord` constraint, which this method lacks.
226             BTreeMap { root: None, length: 0 }
227         } else {
228             clone_subtree(self.root.as_ref().unwrap().reborrow()) // unwrap succeeds because not empty
229         }
230     }
231 }
232
233 impl<K, Q: ?Sized> super::Recover<Q> for BTreeMap<K, ()>
234 where
235     K: Borrow<Q> + Ord,
236     Q: Ord,
237 {
238     type Key = K;
239
240     fn get(&self, key: &Q) -> Option<&K> {
241         let root_node = self.root.as_ref()?.reborrow();
242         match root_node.search_tree(key) {
243             Found(handle) => Some(handle.into_kv().0),
244             GoDown(_) => None,
245         }
246     }
247
248     fn take(&mut self, key: &Q) -> Option<K> {
249         let (map, dormant_map) = DormantMutRef::new(self);
250         let root_node = map.root.as_mut()?.borrow_mut();
251         match root_node.search_tree(key) {
252             Found(handle) => {
253                 Some(OccupiedEntry { handle, dormant_map, _marker: PhantomData }.remove_kv().0)
254             }
255             GoDown(_) => None,
256         }
257     }
258
259     fn replace(&mut self, key: K) -> Option<K> {
260         let (map, dormant_map) = DormantMutRef::new(self);
261         let root_node = Self::ensure_is_owned(&mut map.root).borrow_mut();
262         match root_node.search_tree::<K>(&key) {
263             Found(mut kv) => Some(mem::replace(kv.key_mut(), key)),
264             GoDown(handle) => {
265                 VacantEntry { key, handle, dormant_map, _marker: PhantomData }.insert(());
266                 None
267             }
268         }
269     }
270 }
271
272 /// An iterator over the entries of a `BTreeMap`.
273 ///
274 /// This `struct` is created by the [`iter`] method on [`BTreeMap`]. See its
275 /// documentation for more.
276 ///
277 /// [`iter`]: BTreeMap::iter
278 #[stable(feature = "rust1", since = "1.0.0")]
279 pub struct Iter<'a, K: 'a, V: 'a> {
280     range: Range<'a, K, V>,
281     length: usize,
282 }
283
284 #[stable(feature = "collection_debug", since = "1.17.0")]
285 impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for Iter<'_, K, V> {
286     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
287         f.debug_list().entries(self.clone()).finish()
288     }
289 }
290
291 /// A mutable iterator over the entries of a `BTreeMap`.
292 ///
293 /// This `struct` is created by the [`iter_mut`] method on [`BTreeMap`]. See its
294 /// documentation for more.
295 ///
296 /// [`iter_mut`]: BTreeMap::iter_mut
297 #[stable(feature = "rust1", since = "1.0.0")]
298 #[derive(Debug)]
299 pub struct IterMut<'a, K: 'a, V: 'a> {
300     range: RangeMut<'a, K, V>,
301     length: usize,
302 }
303
304 /// An owning iterator over the entries of a `BTreeMap`.
305 ///
306 /// This `struct` is created by the [`into_iter`] method on [`BTreeMap`]
307 /// (provided by the `IntoIterator` trait). See its documentation for more.
308 ///
309 /// [`into_iter`]: IntoIterator::into_iter
310 #[stable(feature = "rust1", since = "1.0.0")]
311 pub struct IntoIter<K, V> {
312     range: LeafRange<marker::Dying, K, V>,
313     length: usize,
314 }
315
316 impl<K, V> IntoIter<K, V> {
317     /// Returns an iterator of references over the remaining items.
318     #[inline]
319     pub(super) fn iter(&self) -> Iter<'_, K, V> {
320         let range = Range { inner: self.range.reborrow() };
321         Iter { range: range, length: self.length }
322     }
323 }
324
325 #[stable(feature = "collection_debug", since = "1.17.0")]
326 impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for IntoIter<K, V> {
327     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
328         f.debug_list().entries(self.iter()).finish()
329     }
330 }
331
332 /// A simplified version of `IntoIter` that is not double-ended and has only one
333 /// purpose: to drop the remainder of an `IntoIter`. Therefore it also serves to
334 /// drop an entire tree without the need to first look up a `back` leaf edge.
335 struct Dropper<K, V> {
336     front: Handle<NodeRef<marker::Dying, K, V, marker::Leaf>, marker::Edge>,
337     remaining_length: usize,
338 }
339
340 /// An iterator over the keys of a `BTreeMap`.
341 ///
342 /// This `struct` is created by the [`keys`] method on [`BTreeMap`]. See its
343 /// documentation for more.
344 ///
345 /// [`keys`]: BTreeMap::keys
346 #[stable(feature = "rust1", since = "1.0.0")]
347 pub struct Keys<'a, K: 'a, V: 'a> {
348     inner: Iter<'a, K, V>,
349 }
350
351 #[stable(feature = "collection_debug", since = "1.17.0")]
352 impl<K: fmt::Debug, V> fmt::Debug for Keys<'_, K, V> {
353     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
354         f.debug_list().entries(self.clone()).finish()
355     }
356 }
357
358 /// An iterator over the values of a `BTreeMap`.
359 ///
360 /// This `struct` is created by the [`values`] method on [`BTreeMap`]. See its
361 /// documentation for more.
362 ///
363 /// [`values`]: BTreeMap::values
364 #[stable(feature = "rust1", since = "1.0.0")]
365 pub struct Values<'a, K: 'a, V: 'a> {
366     inner: Iter<'a, K, V>,
367 }
368
369 #[stable(feature = "collection_debug", since = "1.17.0")]
370 impl<K, V: fmt::Debug> fmt::Debug for Values<'_, K, V> {
371     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
372         f.debug_list().entries(self.clone()).finish()
373     }
374 }
375
376 /// A mutable iterator over the values of a `BTreeMap`.
377 ///
378 /// This `struct` is created by the [`values_mut`] method on [`BTreeMap`]. See its
379 /// documentation for more.
380 ///
381 /// [`values_mut`]: BTreeMap::values_mut
382 #[stable(feature = "map_values_mut", since = "1.10.0")]
383 pub struct ValuesMut<'a, K: 'a, V: 'a> {
384     inner: IterMut<'a, K, V>,
385 }
386
387 #[stable(feature = "map_values_mut", since = "1.10.0")]
388 impl<K, V: fmt::Debug> fmt::Debug for ValuesMut<'_, K, V> {
389     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
390         f.debug_list().entries(self.inner.iter().map(|(_, val)| val)).finish()
391     }
392 }
393
394 /// An owning iterator over the keys of a `BTreeMap`.
395 ///
396 /// This `struct` is created by the [`into_keys`] method on [`BTreeMap`].
397 /// See its documentation for more.
398 ///
399 /// [`into_keys`]: BTreeMap::into_keys
400 #[unstable(feature = "map_into_keys_values", issue = "75294")]
401 pub struct IntoKeys<K, V> {
402     inner: IntoIter<K, V>,
403 }
404
405 #[unstable(feature = "map_into_keys_values", issue = "75294")]
406 impl<K: fmt::Debug, V> fmt::Debug for IntoKeys<K, V> {
407     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
408         f.debug_list().entries(self.inner.iter().map(|(key, _)| key)).finish()
409     }
410 }
411
412 /// An owning iterator over the values of a `BTreeMap`.
413 ///
414 /// This `struct` is created by the [`into_values`] method on [`BTreeMap`].
415 /// See its documentation for more.
416 ///
417 /// [`into_values`]: BTreeMap::into_values
418 #[unstable(feature = "map_into_keys_values", issue = "75294")]
419 pub struct IntoValues<K, V> {
420     inner: IntoIter<K, V>,
421 }
422
423 #[unstable(feature = "map_into_keys_values", issue = "75294")]
424 impl<K, V: fmt::Debug> fmt::Debug for IntoValues<K, V> {
425     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
426         f.debug_list().entries(self.inner.iter().map(|(_, val)| val)).finish()
427     }
428 }
429
430 /// An iterator over a sub-range of entries in a `BTreeMap`.
431 ///
432 /// This `struct` is created by the [`range`] method on [`BTreeMap`]. See its
433 /// documentation for more.
434 ///
435 /// [`range`]: BTreeMap::range
436 #[stable(feature = "btree_range", since = "1.17.0")]
437 pub struct Range<'a, K: 'a, V: 'a> {
438     inner: LeafRange<marker::Immut<'a>, K, V>,
439 }
440
441 #[stable(feature = "collection_debug", since = "1.17.0")]
442 impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for Range<'_, K, V> {
443     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
444         f.debug_list().entries(self.clone()).finish()
445     }
446 }
447
448 /// A mutable iterator over a sub-range of entries in a `BTreeMap`.
449 ///
450 /// This `struct` is created by the [`range_mut`] method on [`BTreeMap`]. See its
451 /// documentation for more.
452 ///
453 /// [`range_mut`]: BTreeMap::range_mut
454 #[stable(feature = "btree_range", since = "1.17.0")]
455 pub struct RangeMut<'a, K: 'a, V: 'a> {
456     inner: LeafRange<marker::ValMut<'a>, K, V>,
457
458     // Be invariant in `K` and `V`
459     _marker: PhantomData<&'a mut (K, V)>,
460 }
461
462 #[stable(feature = "collection_debug", since = "1.17.0")]
463 impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for RangeMut<'_, K, V> {
464     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
465         let range = Range { inner: self.inner.reborrow() };
466         f.debug_list().entries(range).finish()
467     }
468 }
469
470 impl<K, V> BTreeMap<K, V> {
471     /// Makes a new, empty `BTreeMap`.
472     ///
473     /// Does not allocate anything on its own.
474     ///
475     /// # Examples
476     ///
477     /// Basic usage:
478     ///
479     /// ```
480     /// use std::collections::BTreeMap;
481     ///
482     /// let mut map = BTreeMap::new();
483     ///
484     /// // entries can now be inserted into the empty map
485     /// map.insert(1, "a");
486     /// ```
487     #[stable(feature = "rust1", since = "1.0.0")]
488     #[rustc_const_unstable(feature = "const_btree_new", issue = "71835")]
489     pub const fn new() -> BTreeMap<K, V>
490     where
491         K: Ord,
492     {
493         BTreeMap { root: None, length: 0 }
494     }
495
496     /// Clears the map, removing all elements.
497     ///
498     /// # Examples
499     ///
500     /// Basic usage:
501     ///
502     /// ```
503     /// use std::collections::BTreeMap;
504     ///
505     /// let mut a = BTreeMap::new();
506     /// a.insert(1, "a");
507     /// a.clear();
508     /// assert!(a.is_empty());
509     /// ```
510     #[stable(feature = "rust1", since = "1.0.0")]
511     pub fn clear(&mut self) {
512         *self = BTreeMap { root: None, length: 0 };
513     }
514
515     /// Returns a reference to the value corresponding to the key.
516     ///
517     /// The key may be any borrowed form of the map's key type, but the ordering
518     /// on the borrowed form *must* match the ordering on the key type.
519     ///
520     /// # Examples
521     ///
522     /// Basic usage:
523     ///
524     /// ```
525     /// use std::collections::BTreeMap;
526     ///
527     /// let mut map = BTreeMap::new();
528     /// map.insert(1, "a");
529     /// assert_eq!(map.get(&1), Some(&"a"));
530     /// assert_eq!(map.get(&2), None);
531     /// ```
532     #[stable(feature = "rust1", since = "1.0.0")]
533     pub fn get<Q: ?Sized>(&self, key: &Q) -> Option<&V>
534     where
535         K: Borrow<Q> + Ord,
536         Q: Ord,
537     {
538         let root_node = self.root.as_ref()?.reborrow();
539         match root_node.search_tree(key) {
540             Found(handle) => Some(handle.into_kv().1),
541             GoDown(_) => None,
542         }
543     }
544
545     /// Returns the key-value pair corresponding to the supplied key.
546     ///
547     /// The supplied key may be any borrowed form of the map's key type, but the ordering
548     /// on the borrowed form *must* match the ordering on the key type.
549     ///
550     /// # Examples
551     ///
552     /// ```
553     /// use std::collections::BTreeMap;
554     ///
555     /// let mut map = BTreeMap::new();
556     /// map.insert(1, "a");
557     /// assert_eq!(map.get_key_value(&1), Some((&1, &"a")));
558     /// assert_eq!(map.get_key_value(&2), None);
559     /// ```
560     #[stable(feature = "map_get_key_value", since = "1.40.0")]
561     pub fn get_key_value<Q: ?Sized>(&self, k: &Q) -> Option<(&K, &V)>
562     where
563         K: Borrow<Q> + Ord,
564         Q: Ord,
565     {
566         let root_node = self.root.as_ref()?.reborrow();
567         match root_node.search_tree(k) {
568             Found(handle) => Some(handle.into_kv()),
569             GoDown(_) => None,
570         }
571     }
572
573     /// Returns the first key-value pair in the map.
574     /// The key in this pair is the minimum key in the map.
575     ///
576     /// # Examples
577     ///
578     /// Basic usage:
579     ///
580     /// ```
581     /// #![feature(map_first_last)]
582     /// use std::collections::BTreeMap;
583     ///
584     /// let mut map = BTreeMap::new();
585     /// assert_eq!(map.first_key_value(), None);
586     /// map.insert(1, "b");
587     /// map.insert(2, "a");
588     /// assert_eq!(map.first_key_value(), Some((&1, &"b")));
589     /// ```
590     #[unstable(feature = "map_first_last", issue = "62924")]
591     pub fn first_key_value(&self) -> Option<(&K, &V)>
592     where
593         K: Ord,
594     {
595         let root_node = self.root.as_ref()?.reborrow();
596         root_node.first_leaf_edge().right_kv().ok().map(Handle::into_kv)
597     }
598
599     /// Returns the first entry in the map for in-place manipulation.
600     /// The key of this entry is the minimum key in the map.
601     ///
602     /// # Examples
603     ///
604     /// ```
605     /// #![feature(map_first_last)]
606     /// use std::collections::BTreeMap;
607     ///
608     /// let mut map = BTreeMap::new();
609     /// map.insert(1, "a");
610     /// map.insert(2, "b");
611     /// if let Some(mut entry) = map.first_entry() {
612     ///     if *entry.key() > 0 {
613     ///         entry.insert("first");
614     ///     }
615     /// }
616     /// assert_eq!(*map.get(&1).unwrap(), "first");
617     /// assert_eq!(*map.get(&2).unwrap(), "b");
618     /// ```
619     #[unstable(feature = "map_first_last", issue = "62924")]
620     pub fn first_entry(&mut self) -> Option<OccupiedEntry<'_, K, V>>
621     where
622         K: Ord,
623     {
624         let (map, dormant_map) = DormantMutRef::new(self);
625         let root_node = map.root.as_mut()?.borrow_mut();
626         let kv = root_node.first_leaf_edge().right_kv().ok()?;
627         Some(OccupiedEntry { handle: kv.forget_node_type(), dormant_map, _marker: PhantomData })
628     }
629
630     /// Removes and returns the first element in the map.
631     /// The key of this element is the minimum key that was in the map.
632     ///
633     /// # Examples
634     ///
635     /// Draining elements in ascending order, while keeping a usable map each iteration.
636     ///
637     /// ```
638     /// #![feature(map_first_last)]
639     /// use std::collections::BTreeMap;
640     ///
641     /// let mut map = BTreeMap::new();
642     /// map.insert(1, "a");
643     /// map.insert(2, "b");
644     /// while let Some((key, _val)) = map.pop_first() {
645     ///     assert!(map.iter().all(|(k, _v)| *k > key));
646     /// }
647     /// assert!(map.is_empty());
648     /// ```
649     #[unstable(feature = "map_first_last", issue = "62924")]
650     pub fn pop_first(&mut self) -> Option<(K, V)>
651     where
652         K: Ord,
653     {
654         self.first_entry().map(|entry| entry.remove_entry())
655     }
656
657     /// Returns the last key-value pair in the map.
658     /// The key in this pair is the maximum key in the map.
659     ///
660     /// # Examples
661     ///
662     /// Basic usage:
663     ///
664     /// ```
665     /// #![feature(map_first_last)]
666     /// use std::collections::BTreeMap;
667     ///
668     /// let mut map = BTreeMap::new();
669     /// map.insert(1, "b");
670     /// map.insert(2, "a");
671     /// assert_eq!(map.last_key_value(), Some((&2, &"a")));
672     /// ```
673     #[unstable(feature = "map_first_last", issue = "62924")]
674     pub fn last_key_value(&self) -> Option<(&K, &V)>
675     where
676         K: Ord,
677     {
678         let root_node = self.root.as_ref()?.reborrow();
679         root_node.last_leaf_edge().left_kv().ok().map(Handle::into_kv)
680     }
681
682     /// Returns the last entry in the map for in-place manipulation.
683     /// The key of this entry is the maximum key in the map.
684     ///
685     /// # Examples
686     ///
687     /// ```
688     /// #![feature(map_first_last)]
689     /// use std::collections::BTreeMap;
690     ///
691     /// let mut map = BTreeMap::new();
692     /// map.insert(1, "a");
693     /// map.insert(2, "b");
694     /// if let Some(mut entry) = map.last_entry() {
695     ///     if *entry.key() > 0 {
696     ///         entry.insert("last");
697     ///     }
698     /// }
699     /// assert_eq!(*map.get(&1).unwrap(), "a");
700     /// assert_eq!(*map.get(&2).unwrap(), "last");
701     /// ```
702     #[unstable(feature = "map_first_last", issue = "62924")]
703     pub fn last_entry(&mut self) -> Option<OccupiedEntry<'_, K, V>>
704     where
705         K: Ord,
706     {
707         let (map, dormant_map) = DormantMutRef::new(self);
708         let root_node = map.root.as_mut()?.borrow_mut();
709         let kv = root_node.last_leaf_edge().left_kv().ok()?;
710         Some(OccupiedEntry { handle: kv.forget_node_type(), dormant_map, _marker: PhantomData })
711     }
712
713     /// Removes and returns the last element in the map.
714     /// The key of this element is the maximum key that was in the map.
715     ///
716     /// # Examples
717     ///
718     /// Draining elements in descending order, while keeping a usable map each iteration.
719     ///
720     /// ```
721     /// #![feature(map_first_last)]
722     /// use std::collections::BTreeMap;
723     ///
724     /// let mut map = BTreeMap::new();
725     /// map.insert(1, "a");
726     /// map.insert(2, "b");
727     /// while let Some((key, _val)) = map.pop_last() {
728     ///     assert!(map.iter().all(|(k, _v)| *k < key));
729     /// }
730     /// assert!(map.is_empty());
731     /// ```
732     #[unstable(feature = "map_first_last", issue = "62924")]
733     pub fn pop_last(&mut self) -> Option<(K, V)>
734     where
735         K: Ord,
736     {
737         self.last_entry().map(|entry| entry.remove_entry())
738     }
739
740     /// Returns `true` if the map contains a value for the specified key.
741     ///
742     /// The key may be any borrowed form of the map's key type, but the ordering
743     /// on the borrowed form *must* match the ordering on the key type.
744     ///
745     /// # Examples
746     ///
747     /// Basic usage:
748     ///
749     /// ```
750     /// use std::collections::BTreeMap;
751     ///
752     /// let mut map = BTreeMap::new();
753     /// map.insert(1, "a");
754     /// assert_eq!(map.contains_key(&1), true);
755     /// assert_eq!(map.contains_key(&2), false);
756     /// ```
757     #[stable(feature = "rust1", since = "1.0.0")]
758     pub fn contains_key<Q: ?Sized>(&self, key: &Q) -> bool
759     where
760         K: Borrow<Q> + Ord,
761         Q: Ord,
762     {
763         self.get(key).is_some()
764     }
765
766     /// Returns a mutable reference to the value corresponding to the key.
767     ///
768     /// The key may be any borrowed form of the map's key type, but the ordering
769     /// on the borrowed form *must* match the ordering on the key type.
770     ///
771     /// # Examples
772     ///
773     /// Basic usage:
774     ///
775     /// ```
776     /// use std::collections::BTreeMap;
777     ///
778     /// let mut map = BTreeMap::new();
779     /// map.insert(1, "a");
780     /// if let Some(x) = map.get_mut(&1) {
781     ///     *x = "b";
782     /// }
783     /// assert_eq!(map[&1], "b");
784     /// ```
785     // See `get` for implementation notes, this is basically a copy-paste with mut's added
786     #[stable(feature = "rust1", since = "1.0.0")]
787     pub fn get_mut<Q: ?Sized>(&mut self, key: &Q) -> Option<&mut V>
788     where
789         K: Borrow<Q> + Ord,
790         Q: Ord,
791     {
792         let root_node = self.root.as_mut()?.borrow_mut();
793         match root_node.search_tree(key) {
794             Found(handle) => Some(handle.into_val_mut()),
795             GoDown(_) => None,
796         }
797     }
798
799     /// Inserts a key-value pair into the map.
800     ///
801     /// If the map did not have this key present, `None` is returned.
802     ///
803     /// If the map did have this key present, the value is updated, and the old
804     /// value is returned. The key is not updated, though; this matters for
805     /// types that can be `==` without being identical. See the [module-level
806     /// documentation] for more.
807     ///
808     /// [module-level documentation]: index.html#insert-and-complex-keys
809     ///
810     /// # Examples
811     ///
812     /// Basic usage:
813     ///
814     /// ```
815     /// use std::collections::BTreeMap;
816     ///
817     /// let mut map = BTreeMap::new();
818     /// assert_eq!(map.insert(37, "a"), None);
819     /// assert_eq!(map.is_empty(), false);
820     ///
821     /// map.insert(37, "b");
822     /// assert_eq!(map.insert(37, "c"), Some("b"));
823     /// assert_eq!(map[&37], "c");
824     /// ```
825     #[stable(feature = "rust1", since = "1.0.0")]
826     pub fn insert(&mut self, key: K, value: V) -> Option<V>
827     where
828         K: Ord,
829     {
830         match self.entry(key) {
831             Occupied(mut entry) => Some(entry.insert(value)),
832             Vacant(entry) => {
833                 entry.insert(value);
834                 None
835             }
836         }
837     }
838
839     /// Removes a key from the map, returning the value at the key if the key
840     /// was previously in the map.
841     ///
842     /// The key may be any borrowed form of the map's key type, but the ordering
843     /// on the borrowed form *must* match the ordering on the key type.
844     ///
845     /// # Examples
846     ///
847     /// Basic usage:
848     ///
849     /// ```
850     /// use std::collections::BTreeMap;
851     ///
852     /// let mut map = BTreeMap::new();
853     /// map.insert(1, "a");
854     /// assert_eq!(map.remove(&1), Some("a"));
855     /// assert_eq!(map.remove(&1), None);
856     /// ```
857     #[doc(alias = "delete")]
858     #[stable(feature = "rust1", since = "1.0.0")]
859     pub fn remove<Q: ?Sized>(&mut self, key: &Q) -> Option<V>
860     where
861         K: Borrow<Q> + Ord,
862         Q: Ord,
863     {
864         self.remove_entry(key).map(|(_, v)| v)
865     }
866
867     /// Removes a key from the map, returning the stored key and value if the key
868     /// was previously in the map.
869     ///
870     /// The key may be any borrowed form of the map's key type, but the ordering
871     /// on the borrowed form *must* match the ordering on the key type.
872     ///
873     /// # Examples
874     ///
875     /// Basic usage:
876     ///
877     /// ```
878     /// use std::collections::BTreeMap;
879     ///
880     /// let mut map = BTreeMap::new();
881     /// map.insert(1, "a");
882     /// assert_eq!(map.remove_entry(&1), Some((1, "a")));
883     /// assert_eq!(map.remove_entry(&1), None);
884     /// ```
885     #[stable(feature = "btreemap_remove_entry", since = "1.45.0")]
886     pub fn remove_entry<Q: ?Sized>(&mut self, key: &Q) -> Option<(K, V)>
887     where
888         K: Borrow<Q> + Ord,
889         Q: Ord,
890     {
891         let (map, dormant_map) = DormantMutRef::new(self);
892         let root_node = map.root.as_mut()?.borrow_mut();
893         match root_node.search_tree(key) {
894             Found(handle) => {
895                 Some(OccupiedEntry { handle, dormant_map, _marker: PhantomData }.remove_entry())
896             }
897             GoDown(_) => None,
898         }
899     }
900
901     /// Retains only the elements specified by the predicate.
902     ///
903     /// In other words, remove all pairs `(k, v)` such that `f(&k, &mut v)` returns `false`.
904     ///
905     /// # Examples
906     ///
907     /// ```
908     /// #![feature(btree_retain)]
909     /// use std::collections::BTreeMap;
910     ///
911     /// let mut map: BTreeMap<i32, i32> = (0..8).map(|x| (x, x*10)).collect();
912     /// // Keep only the elements with even-numbered keys.
913     /// map.retain(|&k, _| k % 2 == 0);
914     /// assert!(map.into_iter().eq(vec![(0, 0), (2, 20), (4, 40), (6, 60)]));
915     /// ```
916     #[inline]
917     #[unstable(feature = "btree_retain", issue = "79025")]
918     pub fn retain<F>(&mut self, mut f: F)
919     where
920         K: Ord,
921         F: FnMut(&K, &mut V) -> bool,
922     {
923         self.drain_filter(|k, v| !f(k, v));
924     }
925
926     /// Moves all elements from `other` into `Self`, leaving `other` empty.
927     ///
928     /// # Examples
929     ///
930     /// ```
931     /// use std::collections::BTreeMap;
932     ///
933     /// let mut a = BTreeMap::new();
934     /// a.insert(1, "a");
935     /// a.insert(2, "b");
936     /// a.insert(3, "c");
937     ///
938     /// let mut b = BTreeMap::new();
939     /// b.insert(3, "d");
940     /// b.insert(4, "e");
941     /// b.insert(5, "f");
942     ///
943     /// a.append(&mut b);
944     ///
945     /// assert_eq!(a.len(), 5);
946     /// assert_eq!(b.len(), 0);
947     ///
948     /// assert_eq!(a[&1], "a");
949     /// assert_eq!(a[&2], "b");
950     /// assert_eq!(a[&3], "d");
951     /// assert_eq!(a[&4], "e");
952     /// assert_eq!(a[&5], "f");
953     /// ```
954     #[stable(feature = "btree_append", since = "1.11.0")]
955     pub fn append(&mut self, other: &mut Self)
956     where
957         K: Ord,
958     {
959         // Do we have to append anything at all?
960         if other.is_empty() {
961             return;
962         }
963
964         // We can just swap `self` and `other` if `self` is empty.
965         if self.is_empty() {
966             mem::swap(self, other);
967             return;
968         }
969
970         let self_iter = mem::take(self).into_iter();
971         let other_iter = mem::take(other).into_iter();
972         let root = BTreeMap::ensure_is_owned(&mut self.root);
973         root.append_from_sorted_iters(self_iter, other_iter, &mut self.length)
974     }
975
976     /// Constructs a double-ended iterator over a sub-range of elements in the map.
977     /// The simplest way is to use the range syntax `min..max`, thus `range(min..max)` will
978     /// yield elements from min (inclusive) to max (exclusive).
979     /// The range may also be entered as `(Bound<T>, Bound<T>)`, so for example
980     /// `range((Excluded(4), Included(10)))` will yield a left-exclusive, right-inclusive
981     /// range from 4 to 10.
982     ///
983     /// # Panics
984     ///
985     /// Panics if range `start > end`.
986     /// Panics if range `start == end` and both bounds are `Excluded`.
987     ///
988     /// # Examples
989     ///
990     /// Basic usage:
991     ///
992     /// ```
993     /// use std::collections::BTreeMap;
994     /// use std::ops::Bound::Included;
995     ///
996     /// let mut map = BTreeMap::new();
997     /// map.insert(3, "a");
998     /// map.insert(5, "b");
999     /// map.insert(8, "c");
1000     /// for (&key, &value) in map.range((Included(&4), Included(&8))) {
1001     ///     println!("{}: {}", key, value);
1002     /// }
1003     /// assert_eq!(Some((&5, &"b")), map.range(4..).next());
1004     /// ```
1005     #[stable(feature = "btree_range", since = "1.17.0")]
1006     pub fn range<T: ?Sized, R>(&self, range: R) -> Range<'_, K, V>
1007     where
1008         T: Ord,
1009         K: Borrow<T> + Ord,
1010         R: RangeBounds<T>,
1011     {
1012         if let Some(root) = &self.root {
1013             Range { inner: root.reborrow().range_search(range) }
1014         } else {
1015             Range { inner: LeafRange::none() }
1016         }
1017     }
1018
1019     /// Constructs a mutable double-ended iterator over a sub-range of elements in the map.
1020     /// The simplest way is to use the range syntax `min..max`, thus `range(min..max)` will
1021     /// yield elements from min (inclusive) to max (exclusive).
1022     /// The range may also be entered as `(Bound<T>, Bound<T>)`, so for example
1023     /// `range((Excluded(4), Included(10)))` will yield a left-exclusive, right-inclusive
1024     /// range from 4 to 10.
1025     ///
1026     /// # Panics
1027     ///
1028     /// Panics if range `start > end`.
1029     /// Panics if range `start == end` and both bounds are `Excluded`.
1030     ///
1031     /// # Examples
1032     ///
1033     /// Basic usage:
1034     ///
1035     /// ```
1036     /// use std::collections::BTreeMap;
1037     ///
1038     /// let mut map: BTreeMap<&str, i32> = ["Alice", "Bob", "Carol", "Cheryl"]
1039     ///     .iter()
1040     ///     .map(|&s| (s, 0))
1041     ///     .collect();
1042     /// for (_, balance) in map.range_mut("B".."Cheryl") {
1043     ///     *balance += 100;
1044     /// }
1045     /// for (name, balance) in &map {
1046     ///     println!("{} => {}", name, balance);
1047     /// }
1048     /// ```
1049     #[stable(feature = "btree_range", since = "1.17.0")]
1050     pub fn range_mut<T: ?Sized, R>(&mut self, range: R) -> RangeMut<'_, K, V>
1051     where
1052         T: Ord,
1053         K: Borrow<T> + Ord,
1054         R: RangeBounds<T>,
1055     {
1056         if let Some(root) = &mut self.root {
1057             RangeMut { inner: root.borrow_valmut().range_search(range), _marker: PhantomData }
1058         } else {
1059             RangeMut { inner: LeafRange::none(), _marker: PhantomData }
1060         }
1061     }
1062
1063     /// Gets the given key's corresponding entry in the map for in-place manipulation.
1064     ///
1065     /// # Examples
1066     ///
1067     /// Basic usage:
1068     ///
1069     /// ```
1070     /// use std::collections::BTreeMap;
1071     ///
1072     /// let mut count: BTreeMap<&str, usize> = BTreeMap::new();
1073     ///
1074     /// // count the number of occurrences of letters in the vec
1075     /// for x in vec!["a", "b", "a", "c", "a", "b"] {
1076     ///     *count.entry(x).or_insert(0) += 1;
1077     /// }
1078     ///
1079     /// assert_eq!(count["a"], 3);
1080     /// ```
1081     #[stable(feature = "rust1", since = "1.0.0")]
1082     pub fn entry(&mut self, key: K) -> Entry<'_, K, V>
1083     where
1084         K: Ord,
1085     {
1086         // FIXME(@porglezomp) Avoid allocating if we don't insert
1087         let (map, dormant_map) = DormantMutRef::new(self);
1088         let root_node = Self::ensure_is_owned(&mut map.root).borrow_mut();
1089         match root_node.search_tree(&key) {
1090             Found(handle) => Occupied(OccupiedEntry { handle, dormant_map, _marker: PhantomData }),
1091             GoDown(handle) => {
1092                 Vacant(VacantEntry { key, handle, dormant_map, _marker: PhantomData })
1093             }
1094         }
1095     }
1096
1097     /// Splits the collection into two at the given key. Returns everything after the given key,
1098     /// including the key.
1099     ///
1100     /// # Examples
1101     ///
1102     /// Basic usage:
1103     ///
1104     /// ```
1105     /// use std::collections::BTreeMap;
1106     ///
1107     /// let mut a = BTreeMap::new();
1108     /// a.insert(1, "a");
1109     /// a.insert(2, "b");
1110     /// a.insert(3, "c");
1111     /// a.insert(17, "d");
1112     /// a.insert(41, "e");
1113     ///
1114     /// let b = a.split_off(&3);
1115     ///
1116     /// assert_eq!(a.len(), 2);
1117     /// assert_eq!(b.len(), 3);
1118     ///
1119     /// assert_eq!(a[&1], "a");
1120     /// assert_eq!(a[&2], "b");
1121     ///
1122     /// assert_eq!(b[&3], "c");
1123     /// assert_eq!(b[&17], "d");
1124     /// assert_eq!(b[&41], "e");
1125     /// ```
1126     #[stable(feature = "btree_split_off", since = "1.11.0")]
1127     pub fn split_off<Q: ?Sized + Ord>(&mut self, key: &Q) -> Self
1128     where
1129         K: Borrow<Q> + Ord,
1130     {
1131         if self.is_empty() {
1132             return Self::new();
1133         }
1134
1135         let total_num = self.len();
1136         let left_root = self.root.as_mut().unwrap(); // unwrap succeeds because not empty
1137
1138         let right_root = left_root.split_off(key);
1139
1140         let (new_left_len, right_len) = Root::calc_split_length(total_num, &left_root, &right_root);
1141         self.length = new_left_len;
1142
1143         BTreeMap { root: Some(right_root), length: right_len }
1144     }
1145
1146     /// Creates an iterator that visits all elements (key-value pairs) in
1147     /// ascending key order and uses a closure to determine if an element should
1148     /// be removed. If the closure returns `true`, the element is removed from
1149     /// the map and yielded. If the closure returns `false`, or panics, the
1150     /// element remains in the map and will not be yielded.
1151     ///
1152     /// The iterator also lets you mutate the value of each element in the
1153     /// closure, regardless of whether you choose to keep or remove it.
1154     ///
1155     /// If the iterator is only partially consumed or not consumed at all, each
1156     /// of the remaining elements is still subjected to the closure, which may
1157     /// change its value and, by returning `true`, have the element removed and
1158     /// dropped.
1159     ///
1160     /// It is unspecified how many more elements will be subjected to the
1161     /// closure if a panic occurs in the closure, or a panic occurs while
1162     /// dropping an element, or if the `DrainFilter` value is leaked.
1163     ///
1164     /// # Examples
1165     ///
1166     /// Splitting a map into even and odd keys, reusing the original map:
1167     ///
1168     /// ```
1169     /// #![feature(btree_drain_filter)]
1170     /// use std::collections::BTreeMap;
1171     ///
1172     /// let mut map: BTreeMap<i32, i32> = (0..8).map(|x| (x, x)).collect();
1173     /// let evens: BTreeMap<_, _> = map.drain_filter(|k, _v| k % 2 == 0).collect();
1174     /// let odds = map;
1175     /// assert_eq!(evens.keys().copied().collect::<Vec<_>>(), vec![0, 2, 4, 6]);
1176     /// assert_eq!(odds.keys().copied().collect::<Vec<_>>(), vec![1, 3, 5, 7]);
1177     /// ```
1178     #[unstable(feature = "btree_drain_filter", issue = "70530")]
1179     pub fn drain_filter<F>(&mut self, pred: F) -> DrainFilter<'_, K, V, F>
1180     where
1181         K: Ord,
1182         F: FnMut(&K, &mut V) -> bool,
1183     {
1184         DrainFilter { pred, inner: self.drain_filter_inner() }
1185     }
1186
1187     pub(super) fn drain_filter_inner(&mut self) -> DrainFilterInner<'_, K, V>
1188     where
1189         K: Ord,
1190     {
1191         if let Some(root) = self.root.as_mut() {
1192             let (root, dormant_root) = DormantMutRef::new(root);
1193             let front = root.borrow_mut().first_leaf_edge();
1194             DrainFilterInner {
1195                 length: &mut self.length,
1196                 dormant_root: Some(dormant_root),
1197                 cur_leaf_edge: Some(front),
1198             }
1199         } else {
1200             DrainFilterInner { length: &mut self.length, dormant_root: None, cur_leaf_edge: None }
1201         }
1202     }
1203
1204     /// Creates a consuming iterator visiting all the keys, in sorted order.
1205     /// The map cannot be used after calling this.
1206     /// The iterator element type is `K`.
1207     ///
1208     /// # Examples
1209     ///
1210     /// ```
1211     /// #![feature(map_into_keys_values)]
1212     /// use std::collections::BTreeMap;
1213     ///
1214     /// let mut a = BTreeMap::new();
1215     /// a.insert(2, "b");
1216     /// a.insert(1, "a");
1217     ///
1218     /// let keys: Vec<i32> = a.into_keys().collect();
1219     /// assert_eq!(keys, [1, 2]);
1220     /// ```
1221     #[inline]
1222     #[unstable(feature = "map_into_keys_values", issue = "75294")]
1223     pub fn into_keys(self) -> IntoKeys<K, V> {
1224         IntoKeys { inner: self.into_iter() }
1225     }
1226
1227     /// Creates a consuming iterator visiting all the values, in order by key.
1228     /// The map cannot be used after calling this.
1229     /// The iterator element type is `V`.
1230     ///
1231     /// # Examples
1232     ///
1233     /// ```
1234     /// #![feature(map_into_keys_values)]
1235     /// use std::collections::BTreeMap;
1236     ///
1237     /// let mut a = BTreeMap::new();
1238     /// a.insert(1, "hello");
1239     /// a.insert(2, "goodbye");
1240     ///
1241     /// let values: Vec<&str> = a.into_values().collect();
1242     /// assert_eq!(values, ["hello", "goodbye"]);
1243     /// ```
1244     #[inline]
1245     #[unstable(feature = "map_into_keys_values", issue = "75294")]
1246     pub fn into_values(self) -> IntoValues<K, V> {
1247         IntoValues { inner: self.into_iter() }
1248     }
1249 }
1250
1251 #[stable(feature = "rust1", since = "1.0.0")]
1252 impl<'a, K, V> IntoIterator for &'a BTreeMap<K, V> {
1253     type Item = (&'a K, &'a V);
1254     type IntoIter = Iter<'a, K, V>;
1255
1256     fn into_iter(self) -> Iter<'a, K, V> {
1257         self.iter()
1258     }
1259 }
1260
1261 #[stable(feature = "rust1", since = "1.0.0")]
1262 impl<'a, K: 'a, V: 'a> Iterator for Iter<'a, K, V> {
1263     type Item = (&'a K, &'a V);
1264
1265     fn next(&mut self) -> Option<(&'a K, &'a V)> {
1266         if self.length == 0 {
1267             None
1268         } else {
1269             self.length -= 1;
1270             Some(unsafe { self.range.next_unchecked() })
1271         }
1272     }
1273
1274     fn size_hint(&self) -> (usize, Option<usize>) {
1275         (self.length, Some(self.length))
1276     }
1277
1278     fn last(mut self) -> Option<(&'a K, &'a V)> {
1279         self.next_back()
1280     }
1281
1282     fn min(mut self) -> Option<(&'a K, &'a V)> {
1283         self.next()
1284     }
1285
1286     fn max(mut self) -> Option<(&'a K, &'a V)> {
1287         self.next_back()
1288     }
1289 }
1290
1291 #[stable(feature = "fused", since = "1.26.0")]
1292 impl<K, V> FusedIterator for Iter<'_, K, V> {}
1293
1294 #[stable(feature = "rust1", since = "1.0.0")]
1295 impl<'a, K: 'a, V: 'a> DoubleEndedIterator for Iter<'a, K, V> {
1296     fn next_back(&mut self) -> Option<(&'a K, &'a V)> {
1297         if self.length == 0 {
1298             None
1299         } else {
1300             self.length -= 1;
1301             Some(unsafe { self.range.next_back_unchecked() })
1302         }
1303     }
1304 }
1305
1306 #[stable(feature = "rust1", since = "1.0.0")]
1307 impl<K, V> ExactSizeIterator for Iter<'_, K, V> {
1308     fn len(&self) -> usize {
1309         self.length
1310     }
1311 }
1312
1313 #[stable(feature = "rust1", since = "1.0.0")]
1314 impl<K, V> Clone for Iter<'_, K, V> {
1315     fn clone(&self) -> Self {
1316         Iter { range: self.range.clone(), length: self.length }
1317     }
1318 }
1319
1320 #[stable(feature = "rust1", since = "1.0.0")]
1321 impl<'a, K, V> IntoIterator for &'a mut BTreeMap<K, V> {
1322     type Item = (&'a K, &'a mut V);
1323     type IntoIter = IterMut<'a, K, V>;
1324
1325     fn into_iter(self) -> IterMut<'a, K, V> {
1326         self.iter_mut()
1327     }
1328 }
1329
1330 #[stable(feature = "rust1", since = "1.0.0")]
1331 impl<'a, K: 'a, V: 'a> Iterator for IterMut<'a, K, V> {
1332     type Item = (&'a K, &'a mut V);
1333
1334     fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
1335         if self.length == 0 {
1336             None
1337         } else {
1338             self.length -= 1;
1339             Some(unsafe { self.range.next_unchecked() })
1340         }
1341     }
1342
1343     fn size_hint(&self) -> (usize, Option<usize>) {
1344         (self.length, Some(self.length))
1345     }
1346
1347     fn last(mut self) -> Option<(&'a K, &'a mut V)> {
1348         self.next_back()
1349     }
1350
1351     fn min(mut self) -> Option<(&'a K, &'a mut V)> {
1352         self.next()
1353     }
1354
1355     fn max(mut self) -> Option<(&'a K, &'a mut V)> {
1356         self.next_back()
1357     }
1358 }
1359
1360 #[stable(feature = "rust1", since = "1.0.0")]
1361 impl<'a, K: 'a, V: 'a> DoubleEndedIterator for IterMut<'a, K, V> {
1362     fn next_back(&mut self) -> Option<(&'a K, &'a mut V)> {
1363         if self.length == 0 {
1364             None
1365         } else {
1366             self.length -= 1;
1367             Some(unsafe { self.range.next_back_unchecked() })
1368         }
1369     }
1370 }
1371
1372 #[stable(feature = "rust1", since = "1.0.0")]
1373 impl<K, V> ExactSizeIterator for IterMut<'_, K, V> {
1374     fn len(&self) -> usize {
1375         self.length
1376     }
1377 }
1378
1379 #[stable(feature = "fused", since = "1.26.0")]
1380 impl<K, V> FusedIterator for IterMut<'_, K, V> {}
1381
1382 impl<'a, K, V> IterMut<'a, K, V> {
1383     /// Returns an iterator of references over the remaining items.
1384     #[inline]
1385     pub(super) fn iter(&self) -> Iter<'_, K, V> {
1386         Iter { range: self.range.iter(), length: self.length }
1387     }
1388 }
1389
1390 #[stable(feature = "rust1", since = "1.0.0")]
1391 impl<K, V> IntoIterator for BTreeMap<K, V> {
1392     type Item = (K, V);
1393     type IntoIter = IntoIter<K, V>;
1394
1395     fn into_iter(self) -> IntoIter<K, V> {
1396         let mut me = ManuallyDrop::new(self);
1397         if let Some(root) = me.root.take() {
1398             let full_range = root.into_dying().full_range();
1399
1400             IntoIter { range: full_range, length: me.length }
1401         } else {
1402             IntoIter { range: LeafRange::none(), length: 0 }
1403         }
1404     }
1405 }
1406
1407 impl<K, V> Drop for Dropper<K, V> {
1408     fn drop(&mut self) {
1409         // Similar to advancing a non-fusing iterator.
1410         fn next_or_end<K, V>(this: &mut Dropper<K, V>) -> Option<(K, V)> {
1411             if this.remaining_length == 0 {
1412                 unsafe { ptr::read(&this.front).deallocating_end() }
1413                 None
1414             } else {
1415                 this.remaining_length -= 1;
1416                 Some(unsafe { this.front.deallocating_next_unchecked() })
1417             }
1418         }
1419
1420         struct DropGuard<'a, K, V>(&'a mut Dropper<K, V>);
1421
1422         impl<'a, K, V> Drop for DropGuard<'a, K, V> {
1423             fn drop(&mut self) {
1424                 // Continue the same loop we perform below. This only runs when unwinding, so we
1425                 // don't have to care about panics this time (they'll abort).
1426                 while let Some(_pair) = next_or_end(&mut self.0) {}
1427             }
1428         }
1429
1430         while let Some(pair) = next_or_end(self) {
1431             let guard = DropGuard(self);
1432             drop(pair);
1433             mem::forget(guard);
1434         }
1435     }
1436 }
1437
1438 #[stable(feature = "btree_drop", since = "1.7.0")]
1439 impl<K, V> Drop for IntoIter<K, V> {
1440     fn drop(&mut self) {
1441         if let Some(front) = self.range.front.take() {
1442             Dropper { front, remaining_length: self.length };
1443         }
1444     }
1445 }
1446
1447 #[stable(feature = "rust1", since = "1.0.0")]
1448 impl<K, V> Iterator for IntoIter<K, V> {
1449     type Item = (K, V);
1450
1451     fn next(&mut self) -> Option<(K, V)> {
1452         if self.length == 0 {
1453             None
1454         } else {
1455             self.length -= 1;
1456             Some(unsafe { self.range.front.as_mut().unwrap().deallocating_next_unchecked() })
1457         }
1458     }
1459
1460     fn size_hint(&self) -> (usize, Option<usize>) {
1461         (self.length, Some(self.length))
1462     }
1463 }
1464
1465 #[stable(feature = "rust1", since = "1.0.0")]
1466 impl<K, V> DoubleEndedIterator for IntoIter<K, V> {
1467     fn next_back(&mut self) -> Option<(K, V)> {
1468         if self.length == 0 {
1469             None
1470         } else {
1471             self.length -= 1;
1472             Some(unsafe { self.range.back.as_mut().unwrap().deallocating_next_back_unchecked() })
1473         }
1474     }
1475 }
1476
1477 #[stable(feature = "rust1", since = "1.0.0")]
1478 impl<K, V> ExactSizeIterator for IntoIter<K, V> {
1479     fn len(&self) -> usize {
1480         self.length
1481     }
1482 }
1483
1484 #[stable(feature = "fused", since = "1.26.0")]
1485 impl<K, V> FusedIterator for IntoIter<K, V> {}
1486
1487 #[stable(feature = "rust1", since = "1.0.0")]
1488 impl<'a, K, V> Iterator for Keys<'a, K, V> {
1489     type Item = &'a K;
1490
1491     fn next(&mut self) -> Option<&'a K> {
1492         self.inner.next().map(|(k, _)| k)
1493     }
1494
1495     fn size_hint(&self) -> (usize, Option<usize>) {
1496         self.inner.size_hint()
1497     }
1498
1499     fn last(mut self) -> Option<&'a K> {
1500         self.next_back()
1501     }
1502
1503     fn min(mut self) -> Option<&'a K> {
1504         self.next()
1505     }
1506
1507     fn max(mut self) -> Option<&'a K> {
1508         self.next_back()
1509     }
1510 }
1511
1512 #[stable(feature = "rust1", since = "1.0.0")]
1513 impl<'a, K, V> DoubleEndedIterator for Keys<'a, K, V> {
1514     fn next_back(&mut self) -> Option<&'a K> {
1515         self.inner.next_back().map(|(k, _)| k)
1516     }
1517 }
1518
1519 #[stable(feature = "rust1", since = "1.0.0")]
1520 impl<K, V> ExactSizeIterator for Keys<'_, K, V> {
1521     fn len(&self) -> usize {
1522         self.inner.len()
1523     }
1524 }
1525
1526 #[stable(feature = "fused", since = "1.26.0")]
1527 impl<K, V> FusedIterator for Keys<'_, K, V> {}
1528
1529 #[stable(feature = "rust1", since = "1.0.0")]
1530 impl<K, V> Clone for Keys<'_, K, V> {
1531     fn clone(&self) -> Self {
1532         Keys { inner: self.inner.clone() }
1533     }
1534 }
1535
1536 #[stable(feature = "rust1", since = "1.0.0")]
1537 impl<'a, K, V> Iterator for Values<'a, K, V> {
1538     type Item = &'a V;
1539
1540     fn next(&mut self) -> Option<&'a V> {
1541         self.inner.next().map(|(_, v)| v)
1542     }
1543
1544     fn size_hint(&self) -> (usize, Option<usize>) {
1545         self.inner.size_hint()
1546     }
1547
1548     fn last(mut self) -> Option<&'a V> {
1549         self.next_back()
1550     }
1551 }
1552
1553 #[stable(feature = "rust1", since = "1.0.0")]
1554 impl<'a, K, V> DoubleEndedIterator for Values<'a, K, V> {
1555     fn next_back(&mut self) -> Option<&'a V> {
1556         self.inner.next_back().map(|(_, v)| v)
1557     }
1558 }
1559
1560 #[stable(feature = "rust1", since = "1.0.0")]
1561 impl<K, V> ExactSizeIterator for Values<'_, K, V> {
1562     fn len(&self) -> usize {
1563         self.inner.len()
1564     }
1565 }
1566
1567 #[stable(feature = "fused", since = "1.26.0")]
1568 impl<K, V> FusedIterator for Values<'_, K, V> {}
1569
1570 #[stable(feature = "rust1", since = "1.0.0")]
1571 impl<K, V> Clone for Values<'_, K, V> {
1572     fn clone(&self) -> Self {
1573         Values { inner: self.inner.clone() }
1574     }
1575 }
1576
1577 /// An iterator produced by calling `drain_filter` on BTreeMap.
1578 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1579 pub struct DrainFilter<'a, K, V, F>
1580 where
1581     K: 'a,
1582     V: 'a,
1583     F: 'a + FnMut(&K, &mut V) -> bool,
1584 {
1585     pred: F,
1586     inner: DrainFilterInner<'a, K, V>,
1587 }
1588 /// Most of the implementation of DrainFilter are generic over the type
1589 /// of the predicate, thus also serving for BTreeSet::DrainFilter.
1590 pub(super) struct DrainFilterInner<'a, K: 'a, V: 'a> {
1591     /// Reference to the length field in the borrowed map, updated live.
1592     length: &'a mut usize,
1593     /// Buried reference to the root field in the borrowed map.
1594     /// Wrapped in `Option` to allow drop handler to `take` it.
1595     dormant_root: Option<DormantMutRef<'a, Root<K, V>>>,
1596     /// Contains a leaf edge preceding the next element to be returned, or the last leaf edge.
1597     /// Empty if the map has no root, if iteration went beyond the last leaf edge,
1598     /// or if a panic occurred in the predicate.
1599     cur_leaf_edge: Option<Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge>>,
1600 }
1601
1602 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1603 impl<K, V, F> Drop for DrainFilter<'_, K, V, F>
1604 where
1605     F: FnMut(&K, &mut V) -> bool,
1606 {
1607     fn drop(&mut self) {
1608         self.for_each(drop);
1609     }
1610 }
1611
1612 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1613 impl<K, V, F> fmt::Debug for DrainFilter<'_, K, V, F>
1614 where
1615     K: fmt::Debug,
1616     V: fmt::Debug,
1617     F: FnMut(&K, &mut V) -> bool,
1618 {
1619     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1620         f.debug_tuple("DrainFilter").field(&self.inner.peek()).finish()
1621     }
1622 }
1623
1624 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1625 impl<K, V, F> Iterator for DrainFilter<'_, K, V, F>
1626 where
1627     F: FnMut(&K, &mut V) -> bool,
1628 {
1629     type Item = (K, V);
1630
1631     fn next(&mut self) -> Option<(K, V)> {
1632         self.inner.next(&mut self.pred)
1633     }
1634
1635     fn size_hint(&self) -> (usize, Option<usize>) {
1636         self.inner.size_hint()
1637     }
1638 }
1639
1640 impl<'a, K: 'a, V: 'a> DrainFilterInner<'a, K, V> {
1641     /// Allow Debug implementations to predict the next element.
1642     pub(super) fn peek(&self) -> Option<(&K, &V)> {
1643         let edge = self.cur_leaf_edge.as_ref()?;
1644         edge.reborrow().next_kv().ok().map(Handle::into_kv)
1645     }
1646
1647     /// Implementation of a typical `DrainFilter::next` method, given the predicate.
1648     pub(super) fn next<F>(&mut self, pred: &mut F) -> Option<(K, V)>
1649     where
1650         F: FnMut(&K, &mut V) -> bool,
1651     {
1652         while let Ok(mut kv) = self.cur_leaf_edge.take()?.next_kv() {
1653             let (k, v) = kv.kv_mut();
1654             if pred(k, v) {
1655                 *self.length -= 1;
1656                 let (kv, pos) = kv.remove_kv_tracking(|| {
1657                     // SAFETY: we will touch the root in a way that will not
1658                     // invalidate the position returned.
1659                     let root = unsafe { self.dormant_root.take().unwrap().awaken() };
1660                     root.pop_internal_level();
1661                     self.dormant_root = Some(DormantMutRef::new(root).1);
1662                 });
1663                 self.cur_leaf_edge = Some(pos);
1664                 return Some(kv);
1665             }
1666             self.cur_leaf_edge = Some(kv.next_leaf_edge());
1667         }
1668         None
1669     }
1670
1671     /// Implementation of a typical `DrainFilter::size_hint` method.
1672     pub(super) fn size_hint(&self) -> (usize, Option<usize>) {
1673         // In most of the btree iterators, `self.length` is the number of elements
1674         // yet to be visited. Here, it includes elements that were visited and that
1675         // the predicate decided not to drain. Making this upper bound more accurate
1676         // requires maintaining an extra field and is not worth while.
1677         (0, Some(*self.length))
1678     }
1679 }
1680
1681 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1682 impl<K, V, F> FusedIterator for DrainFilter<'_, K, V, F> where F: FnMut(&K, &mut V) -> bool {}
1683
1684 #[stable(feature = "btree_range", since = "1.17.0")]
1685 impl<'a, K, V> Iterator for Range<'a, K, V> {
1686     type Item = (&'a K, &'a V);
1687
1688     fn next(&mut self) -> Option<(&'a K, &'a V)> {
1689         if self.inner.is_empty() { None } else { Some(unsafe { self.next_unchecked() }) }
1690     }
1691
1692     fn last(mut self) -> Option<(&'a K, &'a V)> {
1693         self.next_back()
1694     }
1695
1696     fn min(mut self) -> Option<(&'a K, &'a V)> {
1697         self.next()
1698     }
1699
1700     fn max(mut self) -> Option<(&'a K, &'a V)> {
1701         self.next_back()
1702     }
1703 }
1704
1705 #[stable(feature = "map_values_mut", since = "1.10.0")]
1706 impl<'a, K, V> Iterator for ValuesMut<'a, K, V> {
1707     type Item = &'a mut V;
1708
1709     fn next(&mut self) -> Option<&'a mut V> {
1710         self.inner.next().map(|(_, v)| v)
1711     }
1712
1713     fn size_hint(&self) -> (usize, Option<usize>) {
1714         self.inner.size_hint()
1715     }
1716
1717     fn last(mut self) -> Option<&'a mut V> {
1718         self.next_back()
1719     }
1720 }
1721
1722 #[stable(feature = "map_values_mut", since = "1.10.0")]
1723 impl<'a, K, V> DoubleEndedIterator for ValuesMut<'a, K, V> {
1724     fn next_back(&mut self) -> Option<&'a mut V> {
1725         self.inner.next_back().map(|(_, v)| v)
1726     }
1727 }
1728
1729 #[stable(feature = "map_values_mut", since = "1.10.0")]
1730 impl<K, V> ExactSizeIterator for ValuesMut<'_, K, V> {
1731     fn len(&self) -> usize {
1732         self.inner.len()
1733     }
1734 }
1735
1736 #[stable(feature = "fused", since = "1.26.0")]
1737 impl<K, V> FusedIterator for ValuesMut<'_, K, V> {}
1738
1739 impl<'a, K, V> Range<'a, K, V> {
1740     unsafe fn next_unchecked(&mut self) -> (&'a K, &'a V) {
1741         unsafe { self.inner.front.as_mut().unwrap_unchecked().next_unchecked() }
1742     }
1743 }
1744
1745 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1746 impl<K, V> Iterator for IntoKeys<K, V> {
1747     type Item = K;
1748
1749     fn next(&mut self) -> Option<K> {
1750         self.inner.next().map(|(k, _)| k)
1751     }
1752
1753     fn size_hint(&self) -> (usize, Option<usize>) {
1754         self.inner.size_hint()
1755     }
1756
1757     fn last(mut self) -> Option<K> {
1758         self.next_back()
1759     }
1760
1761     fn min(mut self) -> Option<K> {
1762         self.next()
1763     }
1764
1765     fn max(mut self) -> Option<K> {
1766         self.next_back()
1767     }
1768 }
1769
1770 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1771 impl<K, V> DoubleEndedIterator for IntoKeys<K, V> {
1772     fn next_back(&mut self) -> Option<K> {
1773         self.inner.next_back().map(|(k, _)| k)
1774     }
1775 }
1776
1777 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1778 impl<K, V> ExactSizeIterator for IntoKeys<K, V> {
1779     fn len(&self) -> usize {
1780         self.inner.len()
1781     }
1782 }
1783
1784 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1785 impl<K, V> FusedIterator for IntoKeys<K, V> {}
1786
1787 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1788 impl<K, V> Iterator for IntoValues<K, V> {
1789     type Item = V;
1790
1791     fn next(&mut self) -> Option<V> {
1792         self.inner.next().map(|(_, v)| v)
1793     }
1794
1795     fn size_hint(&self) -> (usize, Option<usize>) {
1796         self.inner.size_hint()
1797     }
1798
1799     fn last(mut self) -> Option<V> {
1800         self.next_back()
1801     }
1802 }
1803
1804 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1805 impl<K, V> DoubleEndedIterator for IntoValues<K, V> {
1806     fn next_back(&mut self) -> Option<V> {
1807         self.inner.next_back().map(|(_, v)| v)
1808     }
1809 }
1810
1811 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1812 impl<K, V> ExactSizeIterator for IntoValues<K, V> {
1813     fn len(&self) -> usize {
1814         self.inner.len()
1815     }
1816 }
1817
1818 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1819 impl<K, V> FusedIterator for IntoValues<K, V> {}
1820
1821 #[stable(feature = "btree_range", since = "1.17.0")]
1822 impl<'a, K, V> DoubleEndedIterator for Range<'a, K, V> {
1823     fn next_back(&mut self) -> Option<(&'a K, &'a V)> {
1824         if self.inner.is_empty() { None } else { Some(unsafe { self.next_back_unchecked() }) }
1825     }
1826 }
1827
1828 impl<'a, K, V> Range<'a, K, V> {
1829     unsafe fn next_back_unchecked(&mut self) -> (&'a K, &'a V) {
1830         unsafe { self.inner.back.as_mut().unwrap_unchecked().next_back_unchecked() }
1831     }
1832 }
1833
1834 #[stable(feature = "fused", since = "1.26.0")]
1835 impl<K, V> FusedIterator for Range<'_, K, V> {}
1836
1837 #[stable(feature = "btree_range", since = "1.17.0")]
1838 impl<K, V> Clone for Range<'_, K, V> {
1839     fn clone(&self) -> Self {
1840         Range { inner: LeafRange { front: self.inner.front, back: self.inner.back } }
1841     }
1842 }
1843
1844 #[stable(feature = "btree_range", since = "1.17.0")]
1845 impl<'a, K, V> Iterator for RangeMut<'a, K, V> {
1846     type Item = (&'a K, &'a mut V);
1847
1848     fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
1849         if self.inner.is_empty() { None } else { Some(unsafe { self.next_unchecked() }) }
1850     }
1851
1852     fn last(mut self) -> Option<(&'a K, &'a mut V)> {
1853         self.next_back()
1854     }
1855
1856     fn min(mut self) -> Option<(&'a K, &'a mut V)> {
1857         self.next()
1858     }
1859
1860     fn max(mut self) -> Option<(&'a K, &'a mut V)> {
1861         self.next_back()
1862     }
1863 }
1864
1865 impl<'a, K, V> RangeMut<'a, K, V> {
1866     unsafe fn next_unchecked(&mut self) -> (&'a K, &'a mut V) {
1867         unsafe { self.inner.front.as_mut().unwrap_unchecked().next_unchecked() }
1868     }
1869
1870     /// Returns an iterator of references over the remaining items.
1871     #[inline]
1872     pub(super) fn iter(&self) -> Range<'_, K, V> {
1873         Range { inner: self.inner.reborrow() }
1874     }
1875 }
1876
1877 #[stable(feature = "btree_range", since = "1.17.0")]
1878 impl<'a, K, V> DoubleEndedIterator for RangeMut<'a, K, V> {
1879     fn next_back(&mut self) -> Option<(&'a K, &'a mut V)> {
1880         if self.inner.is_empty() { None } else { Some(unsafe { self.next_back_unchecked() }) }
1881     }
1882 }
1883
1884 #[stable(feature = "fused", since = "1.26.0")]
1885 impl<K, V> FusedIterator for RangeMut<'_, K, V> {}
1886
1887 impl<'a, K, V> RangeMut<'a, K, V> {
1888     unsafe fn next_back_unchecked(&mut self) -> (&'a K, &'a mut V) {
1889         unsafe { self.inner.back.as_mut().unwrap_unchecked().next_back_unchecked() }
1890     }
1891 }
1892
1893 #[stable(feature = "rust1", since = "1.0.0")]
1894 impl<K: Ord, V> FromIterator<(K, V)> for BTreeMap<K, V> {
1895     fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> BTreeMap<K, V> {
1896         let mut map = BTreeMap::new();
1897         map.extend(iter);
1898         map
1899     }
1900 }
1901
1902 #[stable(feature = "rust1", since = "1.0.0")]
1903 impl<K: Ord, V> Extend<(K, V)> for BTreeMap<K, V> {
1904     #[inline]
1905     fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) {
1906         iter.into_iter().for_each(move |(k, v)| {
1907             self.insert(k, v);
1908         });
1909     }
1910
1911     #[inline]
1912     fn extend_one(&mut self, (k, v): (K, V)) {
1913         self.insert(k, v);
1914     }
1915 }
1916
1917 #[stable(feature = "extend_ref", since = "1.2.0")]
1918 impl<'a, K: Ord + Copy, V: Copy> Extend<(&'a K, &'a V)> for BTreeMap<K, V> {
1919     fn extend<I: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: I) {
1920         self.extend(iter.into_iter().map(|(&key, &value)| (key, value)));
1921     }
1922
1923     #[inline]
1924     fn extend_one(&mut self, (&k, &v): (&'a K, &'a V)) {
1925         self.insert(k, v);
1926     }
1927 }
1928
1929 #[stable(feature = "rust1", since = "1.0.0")]
1930 impl<K: Hash, V: Hash> Hash for BTreeMap<K, V> {
1931     fn hash<H: Hasher>(&self, state: &mut H) {
1932         for elt in self {
1933             elt.hash(state);
1934         }
1935     }
1936 }
1937
1938 #[stable(feature = "rust1", since = "1.0.0")]
1939 impl<K: Ord, V> Default for BTreeMap<K, V> {
1940     /// Creates an empty `BTreeMap`.
1941     fn default() -> BTreeMap<K, V> {
1942         BTreeMap::new()
1943     }
1944 }
1945
1946 #[stable(feature = "rust1", since = "1.0.0")]
1947 impl<K: PartialEq, V: PartialEq> PartialEq for BTreeMap<K, V> {
1948     fn eq(&self, other: &BTreeMap<K, V>) -> bool {
1949         self.len() == other.len() && self.iter().zip(other).all(|(a, b)| a == b)
1950     }
1951 }
1952
1953 #[stable(feature = "rust1", since = "1.0.0")]
1954 impl<K: Eq, V: Eq> Eq for BTreeMap<K, V> {}
1955
1956 #[stable(feature = "rust1", since = "1.0.0")]
1957 impl<K: PartialOrd, V: PartialOrd> PartialOrd for BTreeMap<K, V> {
1958     #[inline]
1959     fn partial_cmp(&self, other: &BTreeMap<K, V>) -> Option<Ordering> {
1960         self.iter().partial_cmp(other.iter())
1961     }
1962 }
1963
1964 #[stable(feature = "rust1", since = "1.0.0")]
1965 impl<K: Ord, V: Ord> Ord for BTreeMap<K, V> {
1966     #[inline]
1967     fn cmp(&self, other: &BTreeMap<K, V>) -> Ordering {
1968         self.iter().cmp(other.iter())
1969     }
1970 }
1971
1972 #[stable(feature = "rust1", since = "1.0.0")]
1973 impl<K: Debug, V: Debug> Debug for BTreeMap<K, V> {
1974     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1975         f.debug_map().entries(self.iter()).finish()
1976     }
1977 }
1978
1979 #[stable(feature = "rust1", since = "1.0.0")]
1980 impl<K, Q: ?Sized, V> Index<&Q> for BTreeMap<K, V>
1981 where
1982     K: Borrow<Q> + Ord,
1983     Q: Ord,
1984 {
1985     type Output = V;
1986
1987     /// Returns a reference to the value corresponding to the supplied key.
1988     ///
1989     /// # Panics
1990     ///
1991     /// Panics if the key is not present in the `BTreeMap`.
1992     #[inline]
1993     fn index(&self, key: &Q) -> &V {
1994         self.get(key).expect("no entry found for key")
1995     }
1996 }
1997
1998 impl<K, V> BTreeMap<K, V> {
1999     /// Gets an iterator over the entries of the map, sorted by key.
2000     ///
2001     /// # Examples
2002     ///
2003     /// Basic usage:
2004     ///
2005     /// ```
2006     /// use std::collections::BTreeMap;
2007     ///
2008     /// let mut map = BTreeMap::new();
2009     /// map.insert(3, "c");
2010     /// map.insert(2, "b");
2011     /// map.insert(1, "a");
2012     ///
2013     /// for (key, value) in map.iter() {
2014     ///     println!("{}: {}", key, value);
2015     /// }
2016     ///
2017     /// let (first_key, first_value) = map.iter().next().unwrap();
2018     /// assert_eq!((*first_key, *first_value), (1, "a"));
2019     /// ```
2020     #[stable(feature = "rust1", since = "1.0.0")]
2021     pub fn iter(&self) -> Iter<'_, K, V> {
2022         if let Some(root) = &self.root {
2023             let full_range = root.reborrow().full_range();
2024
2025             Iter { range: Range { inner: full_range }, length: self.length }
2026         } else {
2027             Iter { range: Range { inner: LeafRange::none() }, length: 0 }
2028         }
2029     }
2030
2031     /// Gets a mutable iterator over the entries of the map, sorted by key.
2032     ///
2033     /// # Examples
2034     ///
2035     /// Basic usage:
2036     ///
2037     /// ```
2038     /// use std::collections::BTreeMap;
2039     ///
2040     /// let mut map = BTreeMap::new();
2041     /// map.insert("a", 1);
2042     /// map.insert("b", 2);
2043     /// map.insert("c", 3);
2044     ///
2045     /// // add 10 to the value if the key isn't "a"
2046     /// for (key, value) in map.iter_mut() {
2047     ///     if key != &"a" {
2048     ///         *value += 10;
2049     ///     }
2050     /// }
2051     /// ```
2052     #[stable(feature = "rust1", since = "1.0.0")]
2053     pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {
2054         if let Some(root) = &mut self.root {
2055             let full_range = root.borrow_valmut().full_range();
2056
2057             IterMut {
2058                 range: RangeMut { inner: full_range, _marker: PhantomData },
2059                 length: self.length,
2060             }
2061         } else {
2062             IterMut {
2063                 range: RangeMut { inner: LeafRange::none(), _marker: PhantomData },
2064                 length: 0,
2065             }
2066         }
2067     }
2068
2069     /// Gets an iterator over the keys of the map, in sorted order.
2070     ///
2071     /// # Examples
2072     ///
2073     /// Basic usage:
2074     ///
2075     /// ```
2076     /// use std::collections::BTreeMap;
2077     ///
2078     /// let mut a = BTreeMap::new();
2079     /// a.insert(2, "b");
2080     /// a.insert(1, "a");
2081     ///
2082     /// let keys: Vec<_> = a.keys().cloned().collect();
2083     /// assert_eq!(keys, [1, 2]);
2084     /// ```
2085     #[stable(feature = "rust1", since = "1.0.0")]
2086     pub fn keys(&self) -> Keys<'_, K, V> {
2087         Keys { inner: self.iter() }
2088     }
2089
2090     /// Gets an iterator over the values of the map, in order by key.
2091     ///
2092     /// # Examples
2093     ///
2094     /// Basic usage:
2095     ///
2096     /// ```
2097     /// use std::collections::BTreeMap;
2098     ///
2099     /// let mut a = BTreeMap::new();
2100     /// a.insert(1, "hello");
2101     /// a.insert(2, "goodbye");
2102     ///
2103     /// let values: Vec<&str> = a.values().cloned().collect();
2104     /// assert_eq!(values, ["hello", "goodbye"]);
2105     /// ```
2106     #[stable(feature = "rust1", since = "1.0.0")]
2107     pub fn values(&self) -> Values<'_, K, V> {
2108         Values { inner: self.iter() }
2109     }
2110
2111     /// Gets a mutable iterator over the values of the map, in order by key.
2112     ///
2113     /// # Examples
2114     ///
2115     /// Basic usage:
2116     ///
2117     /// ```
2118     /// use std::collections::BTreeMap;
2119     ///
2120     /// let mut a = BTreeMap::new();
2121     /// a.insert(1, String::from("hello"));
2122     /// a.insert(2, String::from("goodbye"));
2123     ///
2124     /// for value in a.values_mut() {
2125     ///     value.push_str("!");
2126     /// }
2127     ///
2128     /// let values: Vec<String> = a.values().cloned().collect();
2129     /// assert_eq!(values, [String::from("hello!"),
2130     ///                     String::from("goodbye!")]);
2131     /// ```
2132     #[stable(feature = "map_values_mut", since = "1.10.0")]
2133     pub fn values_mut(&mut self) -> ValuesMut<'_, K, V> {
2134         ValuesMut { inner: self.iter_mut() }
2135     }
2136
2137     /// Returns the number of elements in the map.
2138     ///
2139     /// # Examples
2140     ///
2141     /// Basic usage:
2142     ///
2143     /// ```
2144     /// use std::collections::BTreeMap;
2145     ///
2146     /// let mut a = BTreeMap::new();
2147     /// assert_eq!(a.len(), 0);
2148     /// a.insert(1, "a");
2149     /// assert_eq!(a.len(), 1);
2150     /// ```
2151     #[doc(alias = "length")]
2152     #[stable(feature = "rust1", since = "1.0.0")]
2153     #[rustc_const_unstable(feature = "const_btree_new", issue = "71835")]
2154     pub const fn len(&self) -> usize {
2155         self.length
2156     }
2157
2158     /// Returns `true` if the map contains no elements.
2159     ///
2160     /// # Examples
2161     ///
2162     /// Basic usage:
2163     ///
2164     /// ```
2165     /// use std::collections::BTreeMap;
2166     ///
2167     /// let mut a = BTreeMap::new();
2168     /// assert!(a.is_empty());
2169     /// a.insert(1, "a");
2170     /// assert!(!a.is_empty());
2171     /// ```
2172     #[stable(feature = "rust1", since = "1.0.0")]
2173     #[rustc_const_unstable(feature = "const_btree_new", issue = "71835")]
2174     pub const fn is_empty(&self) -> bool {
2175         self.len() == 0
2176     }
2177
2178     /// If the root node is the empty (non-allocated) root node, allocate our
2179     /// own node. Is an associated function to avoid borrowing the entire BTreeMap.
2180     fn ensure_is_owned(root: &mut Option<Root<K, V>>) -> &mut Root<K, V> {
2181         root.get_or_insert_with(Root::new)
2182     }
2183 }
2184
2185 #[cfg(test)]
2186 mod tests;