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