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