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