]>
Commit | Line | Data |
---|---|---|
9cc50fc6 | 1 | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT |
1a4d82fc JJ |
2 | // file at the top-level directory of this distribution and at |
3 | // http://rust-lang.org/COPYRIGHT. | |
4 | // | |
5 | // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or | |
6 | // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license | |
7 | // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your | |
8 | // option. This file may not be copied, modified, or distributed | |
9 | // except according to those terms. | |
10 | ||
1a4d82fc | 11 | use core::cmp::Ordering; |
85aaf69f | 12 | use core::fmt::Debug; |
1a4d82fc | 13 | use core::hash::{Hash, Hasher}; |
9e0c209e | 14 | use core::iter::{FromIterator, Peekable, FusedIterator}; |
9cc50fc6 | 15 | use core::marker::PhantomData; |
0531ce1d | 16 | use core::ops::Bound::{Excluded, Included, Unbounded}; |
c34b1796 | 17 | use core::ops::Index; |
0531ce1d | 18 | use core::ops::RangeBounds; |
9cc50fc6 | 19 | use core::{fmt, intrinsics, mem, ptr}; |
1a4d82fc | 20 | |
85aaf69f | 21 | use borrow::Borrow; |
9cc50fc6 | 22 | |
3157f602 | 23 | use super::node::{self, Handle, NodeRef, marker}; |
9cc50fc6 | 24 | use super::search; |
1a4d82fc | 25 | |
9cc50fc6 SL |
26 | use super::node::InsertResult::*; |
27 | use super::node::ForceResult::*; | |
28 | use super::search::SearchResult::*; | |
29 | use self::UnderflowResult::*; | |
30 | use self::Entry::*; | |
1a4d82fc | 31 | |
1a4d82fc JJ |
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<sub>B</sub>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. | |
62 | /// | |
63 | /// [`Ord`]: ../../std/cmp/trait.Ord.html | |
64 | /// [`Cell`]: ../../std/cell/struct.Cell.html | |
65 | /// [`RefCell`]: ../../std/cell/struct.RefCell.html | |
54a0048b SL |
66 | /// |
67 | /// # Examples | |
68 | /// | |
69 | /// ``` | |
70 | /// use std::collections::BTreeMap; | |
71 | /// | |
72 | /// // type inference lets us omit an explicit type signature (which | |
73 | /// // would be `BTreeMap<&str, &str>` in this example). | |
74 | /// let mut movie_reviews = BTreeMap::new(); | |
75 | /// | |
3157f602 | 76 | /// // review some movies. |
54a0048b SL |
77 | /// movie_reviews.insert("Office Space", "Deals with real issues in the workplace."); |
78 | /// movie_reviews.insert("Pulp Fiction", "Masterpiece."); | |
79 | /// movie_reviews.insert("The Godfather", "Very enjoyable."); | |
80 | /// movie_reviews.insert("The Blues Brothers", "Eye lyked it alot."); | |
81 | /// | |
82 | /// // check for a specific one. | |
83 | /// if !movie_reviews.contains_key("Les Misérables") { | |
84 | /// println!("We've got {} reviews, but Les Misérables ain't one.", | |
85 | /// movie_reviews.len()); | |
86 | /// } | |
87 | /// | |
88 | /// // oops, this review has a lot of spelling mistakes, let's delete it. | |
89 | /// movie_reviews.remove("The Blues Brothers"); | |
90 | /// | |
91 | /// // look up the values associated with some keys. | |
92 | /// let to_find = ["Up!", "Office Space"]; | |
93 | /// for book in &to_find { | |
94 | /// match movie_reviews.get(book) { | |
95 | /// Some(review) => println!("{}: {}", book, review), | |
96 | /// None => println!("{} is unreviewed.", book) | |
97 | /// } | |
98 | /// } | |
99 | /// | |
100 | /// // iterate over everything. | |
101 | /// for (movie, review) in &movie_reviews { | |
102 | /// println!("{}: \"{}\"", movie, review); | |
103 | /// } | |
104 | /// ``` | |
105 | /// | |
106 | /// `BTreeMap` also implements an [`Entry API`](#method.entry), which allows | |
107 | /// for more complex methods of getting, setting, updating and removing keys and | |
108 | /// their values: | |
109 | /// | |
110 | /// ``` | |
111 | /// use std::collections::BTreeMap; | |
112 | /// | |
113 | /// // type inference lets us omit an explicit type signature (which | |
114 | /// // would be `BTreeMap<&str, u8>` in this example). | |
115 | /// let mut player_stats = BTreeMap::new(); | |
116 | /// | |
117 | /// fn random_stat_buff() -> u8 { | |
118 | /// // could actually return some random value here - let's just return | |
119 | /// // some fixed value for now | |
120 | /// 42 | |
121 | /// } | |
122 | /// | |
123 | /// // insert a key only if it doesn't already exist | |
124 | /// player_stats.entry("health").or_insert(100); | |
125 | /// | |
126 | /// // insert a key using a function that provides a new value only if it | |
127 | /// // doesn't already exist | |
128 | /// player_stats.entry("defence").or_insert_with(random_stat_buff); | |
129 | /// | |
130 | /// // update a key, guarding against the key possibly not being set | |
131 | /// let stat = player_stats.entry("attack").or_insert(100); | |
132 | /// *stat += random_stat_buff(); | |
133 | /// ``` | |
85aaf69f | 134 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc | 135 | pub struct BTreeMap<K, V> { |
9cc50fc6 | 136 | root: node::Root<K, V>, |
3157f602 | 137 | length: usize, |
9cc50fc6 SL |
138 | } |
139 | ||
c30ab7b3 | 140 | #[stable(feature = "btree_drop", since = "1.7.0")] |
32a655c1 | 141 | unsafe impl<#[may_dangle] K, #[may_dangle] V> Drop for BTreeMap<K, V> { |
9cc50fc6 SL |
142 | fn drop(&mut self) { |
143 | unsafe { | |
cc61c64b | 144 | drop(ptr::read(self).into_iter()); |
9cc50fc6 SL |
145 | } |
146 | } | |
147 | } | |
148 | ||
c30ab7b3 | 149 | #[stable(feature = "rust1", since = "1.0.0")] |
9cc50fc6 SL |
150 | impl<K: Clone, V: Clone> Clone for BTreeMap<K, V> { |
151 | fn clone(&self) -> BTreeMap<K, V> { | |
3157f602 XL |
152 | fn clone_subtree<K: Clone, V: Clone>(node: node::NodeRef<marker::Immut, |
153 | K, | |
154 | V, | |
155 | marker::LeafOrInternal>) | |
156 | -> BTreeMap<K, V> { | |
9cc50fc6 SL |
157 | |
158 | match node.force() { | |
159 | Leaf(leaf) => { | |
160 | let mut out_tree = BTreeMap { | |
161 | root: node::Root::new_leaf(), | |
3157f602 | 162 | length: 0, |
9cc50fc6 SL |
163 | }; |
164 | ||
165 | { | |
166 | let mut out_node = match out_tree.root.as_mut().force() { | |
167 | Leaf(leaf) => leaf, | |
3157f602 | 168 | Internal(_) => unreachable!(), |
9cc50fc6 SL |
169 | }; |
170 | ||
171 | let mut in_edge = leaf.first_edge(); | |
172 | while let Ok(kv) = in_edge.right_kv() { | |
173 | let (k, v) = kv.into_kv(); | |
174 | in_edge = kv.right_edge(); | |
175 | ||
176 | out_node.push(k.clone(), v.clone()); | |
177 | out_tree.length += 1; | |
178 | } | |
179 | } | |
180 | ||
181 | out_tree | |
3157f602 | 182 | } |
9cc50fc6 SL |
183 | Internal(internal) => { |
184 | let mut out_tree = clone_subtree(internal.first_edge().descend()); | |
185 | ||
186 | { | |
187 | let mut out_node = out_tree.root.push_level(); | |
188 | let mut in_edge = internal.first_edge(); | |
189 | while let Ok(kv) = in_edge.right_kv() { | |
190 | let (k, v) = kv.into_kv(); | |
191 | in_edge = kv.right_edge(); | |
192 | ||
193 | let k = (*k).clone(); | |
194 | let v = (*v).clone(); | |
195 | let subtree = clone_subtree(in_edge.descend()); | |
196 | ||
197 | // We can't destructure subtree directly | |
198 | // because BTreeMap implements Drop | |
199 | let (subroot, sublength) = unsafe { | |
200 | let root = ptr::read(&subtree.root); | |
201 | let length = subtree.length; | |
202 | mem::forget(subtree); | |
203 | (root, length) | |
204 | }; | |
205 | ||
206 | out_node.push(k, v, subroot); | |
207 | out_tree.length += 1 + sublength; | |
208 | } | |
209 | } | |
210 | ||
211 | out_tree | |
212 | } | |
213 | } | |
214 | } | |
215 | ||
216 | clone_subtree(self.root.as_ref()) | |
217 | } | |
1a4d82fc JJ |
218 | } |
219 | ||
9cc50fc6 SL |
220 | impl<K, Q: ?Sized> super::Recover<Q> for BTreeMap<K, ()> |
221 | where K: Borrow<Q> + Ord, | |
222 | Q: Ord | |
223 | { | |
224 | type Key = K; | |
225 | ||
226 | fn get(&self, key: &Q) -> Option<&K> { | |
227 | match search::search_tree(self.root.as_ref(), key) { | |
228 | Found(handle) => Some(handle.into_kv().0), | |
3157f602 | 229 | GoDown(_) => None, |
9cc50fc6 SL |
230 | } |
231 | } | |
232 | ||
233 | fn take(&mut self, key: &Q) -> Option<K> { | |
234 | match search::search_tree(self.root.as_mut(), key) { | |
235 | Found(handle) => { | |
236 | Some(OccupiedEntry { | |
3b2f2976 | 237 | handle, |
3157f602 XL |
238 | length: &mut self.length, |
239 | _marker: PhantomData, | |
240 | } | |
241 | .remove_kv() | |
242 | .0) | |
243 | } | |
244 | GoDown(_) => None, | |
9cc50fc6 SL |
245 | } |
246 | } | |
247 | ||
248 | fn replace(&mut self, key: K) -> Option<K> { | |
249 | match search::search_tree::<marker::Mut, K, (), K>(self.root.as_mut(), &key) { | |
250 | Found(handle) => Some(mem::replace(handle.into_kv_mut().0, key)), | |
251 | GoDown(handle) => { | |
252 | VacantEntry { | |
3b2f2976 XL |
253 | key, |
254 | handle, | |
9cc50fc6 SL |
255 | length: &mut self.length, |
256 | _marker: PhantomData, | |
3157f602 XL |
257 | } |
258 | .insert(()); | |
9cc50fc6 SL |
259 | None |
260 | } | |
261 | } | |
262 | } | |
1a4d82fc JJ |
263 | } |
264 | ||
cc61c64b XL |
265 | /// An iterator over the entries of a `BTreeMap`. |
266 | /// | |
267 | /// This `struct` is created by the [`iter`] method on [`BTreeMap`]. See its | |
268 | /// documentation for more. | |
269 | /// | |
270 | /// [`iter`]: struct.BTreeMap.html#method.iter | |
271 | /// [`BTreeMap`]: struct.BTreeMap.html | |
85aaf69f | 272 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc | 273 | pub struct Iter<'a, K: 'a, V: 'a> { |
9cc50fc6 | 274 | range: Range<'a, K, V>, |
3157f602 | 275 | length: usize, |
1a4d82fc JJ |
276 | } |
277 | ||
8bb4bdeb XL |
278 | #[stable(feature = "collection_debug", since = "1.17.0")] |
279 | impl<'a, K: 'a + fmt::Debug, V: 'a + fmt::Debug> fmt::Debug for Iter<'a, K, V> { | |
280 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
281 | f.debug_list().entries(self.clone()).finish() | |
282 | } | |
283 | } | |
284 | ||
cc61c64b XL |
285 | /// A mutable iterator over the entries of a `BTreeMap`. |
286 | /// | |
287 | /// This `struct` is created by the [`iter_mut`] method on [`BTreeMap`]. See its | |
288 | /// documentation for more. | |
289 | /// | |
290 | /// [`iter_mut`]: struct.BTreeMap.html#method.iter_mut | |
291 | /// [`BTreeMap`]: struct.BTreeMap.html | |
85aaf69f | 292 | #[stable(feature = "rust1", since = "1.0.0")] |
8bb4bdeb | 293 | #[derive(Debug)] |
1a4d82fc | 294 | pub struct IterMut<'a, K: 'a, V: 'a> { |
9cc50fc6 | 295 | range: RangeMut<'a, K, V>, |
3157f602 | 296 | length: usize, |
1a4d82fc JJ |
297 | } |
298 | ||
cc61c64b XL |
299 | /// An owning iterator over the entries of a `BTreeMap`. |
300 | /// | |
301 | /// This `struct` is created by the [`into_iter`] method on [`BTreeMap`][`BTreeMap`] | |
302 | /// (provided by the `IntoIterator` trait). See its documentation for more. | |
303 | /// | |
304 | /// [`into_iter`]: struct.BTreeMap.html#method.into_iter | |
305 | /// [`BTreeMap`]: struct.BTreeMap.html | |
85aaf69f | 306 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc | 307 | pub struct IntoIter<K, V> { |
9cc50fc6 SL |
308 | front: Handle<NodeRef<marker::Owned, K, V, marker::Leaf>, marker::Edge>, |
309 | back: Handle<NodeRef<marker::Owned, K, V, marker::Leaf>, marker::Edge>, | |
3157f602 | 310 | length: usize, |
1a4d82fc JJ |
311 | } |
312 | ||
8bb4bdeb XL |
313 | #[stable(feature = "collection_debug", since = "1.17.0")] |
314 | impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for IntoIter<K, V> { | |
315 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
316 | let range = Range { | |
317 | front: self.front.reborrow(), | |
318 | back: self.back.reborrow(), | |
319 | }; | |
320 | f.debug_list().entries(range).finish() | |
321 | } | |
322 | } | |
323 | ||
cc61c64b XL |
324 | /// An iterator over the keys of a `BTreeMap`. |
325 | /// | |
326 | /// This `struct` is created by the [`keys`] method on [`BTreeMap`]. See its | |
327 | /// documentation for more. | |
328 | /// | |
329 | /// [`keys`]: struct.BTreeMap.html#method.keys | |
330 | /// [`BTreeMap`]: struct.BTreeMap.html | |
85aaf69f | 331 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc | 332 | pub struct Keys<'a, K: 'a, V: 'a> { |
9cc50fc6 | 333 | inner: Iter<'a, K, V>, |
1a4d82fc JJ |
334 | } |
335 | ||
8bb4bdeb | 336 | #[stable(feature = "collection_debug", since = "1.17.0")] |
041b39d2 | 337 | impl<'a, K: 'a + fmt::Debug, V: 'a> fmt::Debug for Keys<'a, K, V> { |
8bb4bdeb | 338 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
041b39d2 | 339 | f.debug_list().entries(self.clone()).finish() |
8bb4bdeb XL |
340 | } |
341 | } | |
342 | ||
cc61c64b XL |
343 | /// An iterator over the values of a `BTreeMap`. |
344 | /// | |
345 | /// This `struct` is created by the [`values`] method on [`BTreeMap`]. See its | |
346 | /// documentation for more. | |
347 | /// | |
348 | /// [`values`]: struct.BTreeMap.html#method.values | |
349 | /// [`BTreeMap`]: struct.BTreeMap.html | |
85aaf69f | 350 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc | 351 | pub struct Values<'a, K: 'a, V: 'a> { |
9cc50fc6 | 352 | inner: Iter<'a, K, V>, |
85aaf69f SL |
353 | } |
354 | ||
8bb4bdeb | 355 | #[stable(feature = "collection_debug", since = "1.17.0")] |
041b39d2 | 356 | impl<'a, K: 'a, V: 'a + fmt::Debug> fmt::Debug for Values<'a, K, V> { |
8bb4bdeb | 357 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
041b39d2 | 358 | f.debug_list().entries(self.clone()).finish() |
8bb4bdeb XL |
359 | } |
360 | } | |
361 | ||
cc61c64b XL |
362 | /// A mutable iterator over the values of a `BTreeMap`. |
363 | /// | |
364 | /// This `struct` is created by the [`values_mut`] method on [`BTreeMap`]. See its | |
365 | /// documentation for more. | |
366 | /// | |
367 | /// [`values_mut`]: struct.BTreeMap.html#method.values_mut | |
368 | /// [`BTreeMap`]: struct.BTreeMap.html | |
a7813a04 | 369 | #[stable(feature = "map_values_mut", since = "1.10.0")] |
8bb4bdeb | 370 | #[derive(Debug)] |
54a0048b SL |
371 | pub struct ValuesMut<'a, K: 'a, V: 'a> { |
372 | inner: IterMut<'a, K, V>, | |
373 | } | |
374 | ||
cc61c64b XL |
375 | /// An iterator over a sub-range of entries in a `BTreeMap`. |
376 | /// | |
377 | /// This `struct` is created by the [`range`] method on [`BTreeMap`]. See its | |
378 | /// documentation for more. | |
379 | /// | |
380 | /// [`range`]: struct.BTreeMap.html#method.range | |
381 | /// [`BTreeMap`]: struct.BTreeMap.html | |
8bb4bdeb | 382 | #[stable(feature = "btree_range", since = "1.17.0")] |
85aaf69f | 383 | pub struct Range<'a, K: 'a, V: 'a> { |
9cc50fc6 | 384 | front: Handle<NodeRef<marker::Immut<'a>, K, V, marker::Leaf>, marker::Edge>, |
3157f602 | 385 | back: Handle<NodeRef<marker::Immut<'a>, K, V, marker::Leaf>, marker::Edge>, |
85aaf69f SL |
386 | } |
387 | ||
8bb4bdeb XL |
388 | #[stable(feature = "collection_debug", since = "1.17.0")] |
389 | impl<'a, K: 'a + fmt::Debug, V: 'a + fmt::Debug> fmt::Debug for Range<'a, K, V> { | |
390 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
391 | f.debug_list().entries(self.clone()).finish() | |
392 | } | |
393 | } | |
394 | ||
cc61c64b XL |
395 | /// A mutable iterator over a sub-range of entries in a `BTreeMap`. |
396 | /// | |
397 | /// This `struct` is created by the [`range_mut`] method on [`BTreeMap`]. See its | |
398 | /// documentation for more. | |
399 | /// | |
400 | /// [`range_mut`]: struct.BTreeMap.html#method.range_mut | |
401 | /// [`BTreeMap`]: struct.BTreeMap.html | |
8bb4bdeb | 402 | #[stable(feature = "btree_range", since = "1.17.0")] |
85aaf69f | 403 | pub struct RangeMut<'a, K: 'a, V: 'a> { |
9cc50fc6 SL |
404 | front: Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge>, |
405 | back: Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge>, | |
406 | ||
407 | // Be invariant in `K` and `V` | |
408 | _marker: PhantomData<&'a mut (K, V)>, | |
1a4d82fc JJ |
409 | } |
410 | ||
8bb4bdeb XL |
411 | #[stable(feature = "collection_debug", since = "1.17.0")] |
412 | impl<'a, K: 'a + fmt::Debug, V: 'a + fmt::Debug> fmt::Debug for RangeMut<'a, K, V> { | |
413 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
414 | let range = Range { | |
415 | front: self.front.reborrow(), | |
416 | back: self.back.reborrow(), | |
417 | }; | |
418 | f.debug_list().entries(range).finish() | |
419 | } | |
420 | } | |
421 | ||
1a4d82fc | 422 | /// A view into a single entry in a map, which may either be vacant or occupied. |
cc61c64b XL |
423 | /// |
424 | /// This `enum` is constructed from the [`entry`] method on [`BTreeMap`]. | |
5bcae85e SL |
425 | /// |
426 | /// [`BTreeMap`]: struct.BTreeMap.html | |
427 | /// [`entry`]: struct.BTreeMap.html#method.entry | |
c34b1796 | 428 | #[stable(feature = "rust1", since = "1.0.0")] |
92a42be0 | 429 | pub enum Entry<'a, K: 'a, V: 'a> { |
cc61c64b | 430 | /// A vacant entry. |
c34b1796 | 431 | #[stable(feature = "rust1", since = "1.0.0")] |
3157f602 XL |
432 | Vacant(#[stable(feature = "rust1", since = "1.0.0")] |
433 | VacantEntry<'a, K, V>), | |
c34b1796 | 434 | |
cc61c64b | 435 | /// An occupied entry. |
c34b1796 | 436 | #[stable(feature = "rust1", since = "1.0.0")] |
3157f602 XL |
437 | Occupied(#[stable(feature = "rust1", since = "1.0.0")] |
438 | OccupiedEntry<'a, K, V>), | |
1a4d82fc JJ |
439 | } |
440 | ||
5bcae85e SL |
441 | #[stable(feature= "debug_btree_map", since = "1.12.0")] |
442 | impl<'a, K: 'a + Debug + Ord, V: 'a + Debug> Debug for Entry<'a, K, V> { | |
443 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
444 | match *self { | |
445 | Vacant(ref v) => f.debug_tuple("Entry") | |
446 | .field(v) | |
447 | .finish(), | |
448 | Occupied(ref o) => f.debug_tuple("Entry") | |
449 | .field(o) | |
450 | .finish(), | |
451 | } | |
452 | } | |
453 | } | |
454 | ||
cc61c64b XL |
455 | /// A view into a vacant entry in a `BTreeMap`. |
456 | /// It is part of the [`Entry`] enum. | |
5bcae85e SL |
457 | /// |
458 | /// [`Entry`]: enum.Entry.html | |
c34b1796 | 459 | #[stable(feature = "rust1", since = "1.0.0")] |
92a42be0 | 460 | pub struct VacantEntry<'a, K: 'a, V: 'a> { |
1a4d82fc | 461 | key: K, |
9cc50fc6 SL |
462 | handle: Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge>, |
463 | length: &'a mut usize, | |
464 | ||
465 | // Be invariant in `K` and `V` | |
466 | _marker: PhantomData<&'a mut (K, V)>, | |
1a4d82fc JJ |
467 | } |
468 | ||
5bcae85e SL |
469 | #[stable(feature= "debug_btree_map", since = "1.12.0")] |
470 | impl<'a, K: 'a + Debug + Ord, V: 'a> Debug for VacantEntry<'a, K, V> { | |
471 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
472 | f.debug_tuple("VacantEntry") | |
473 | .field(self.key()) | |
474 | .finish() | |
475 | } | |
476 | } | |
477 | ||
cc61c64b XL |
478 | /// A view into an occupied entry in a `BTreeMap`. |
479 | /// It is part of the [`Entry`] enum. | |
5bcae85e SL |
480 | /// |
481 | /// [`Entry`]: enum.Entry.html | |
c34b1796 | 482 | #[stable(feature = "rust1", since = "1.0.0")] |
92a42be0 | 483 | pub struct OccupiedEntry<'a, K: 'a, V: 'a> { |
3157f602 | 484 | handle: Handle<NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal>, marker::KV>, |
9cc50fc6 SL |
485 | |
486 | length: &'a mut usize, | |
487 | ||
488 | // Be invariant in `K` and `V` | |
489 | _marker: PhantomData<&'a mut (K, V)>, | |
1a4d82fc JJ |
490 | } |
491 | ||
5bcae85e SL |
492 | #[stable(feature= "debug_btree_map", since = "1.12.0")] |
493 | impl<'a, K: 'a + Debug + Ord, V: 'a + Debug> Debug for OccupiedEntry<'a, K, V> { | |
494 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
495 | f.debug_struct("OccupiedEntry") | |
496 | .field("key", self.key()) | |
497 | .field("value", self.get()) | |
498 | .finish() | |
499 | } | |
500 | } | |
501 | ||
a7813a04 | 502 | // An iterator for merging two sorted sequences into one |
3157f602 | 503 | struct MergeIter<K, V, I: Iterator<Item = (K, V)>> { |
a7813a04 XL |
504 | left: Peekable<I>, |
505 | right: Peekable<I>, | |
506 | } | |
507 | ||
1a4d82fc JJ |
508 | impl<K: Ord, V> BTreeMap<K, V> { |
509 | /// Makes a new empty BTreeMap with a reasonable choice for B. | |
54a0048b SL |
510 | /// |
511 | /// # Examples | |
512 | /// | |
513 | /// Basic usage: | |
514 | /// | |
515 | /// ``` | |
516 | /// use std::collections::BTreeMap; | |
517 | /// | |
518 | /// let mut map = BTreeMap::new(); | |
519 | /// | |
520 | /// // entries can now be inserted into the empty map | |
521 | /// map.insert(1, "a"); | |
522 | /// ``` | |
85aaf69f | 523 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc | 524 | pub fn new() -> BTreeMap<K, V> { |
1a4d82fc | 525 | BTreeMap { |
9cc50fc6 | 526 | root: node::Root::new_leaf(), |
3157f602 | 527 | length: 0, |
1a4d82fc JJ |
528 | } |
529 | } | |
530 | ||
531 | /// Clears the map, removing all values. | |
532 | /// | |
533 | /// # Examples | |
534 | /// | |
54a0048b SL |
535 | /// Basic usage: |
536 | /// | |
1a4d82fc JJ |
537 | /// ``` |
538 | /// use std::collections::BTreeMap; | |
539 | /// | |
540 | /// let mut a = BTreeMap::new(); | |
85aaf69f | 541 | /// a.insert(1, "a"); |
1a4d82fc JJ |
542 | /// a.clear(); |
543 | /// assert!(a.is_empty()); | |
544 | /// ``` | |
85aaf69f | 545 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc | 546 | pub fn clear(&mut self) { |
9cc50fc6 SL |
547 | // FIXME(gereeter) .clear() allocates |
548 | *self = BTreeMap::new(); | |
1a4d82fc JJ |
549 | } |
550 | ||
1a4d82fc JJ |
551 | /// Returns a reference to the value corresponding to the key. |
552 | /// | |
553 | /// The key may be any borrowed form of the map's key type, but the ordering | |
554 | /// on the borrowed form *must* match the ordering on the key type. | |
555 | /// | |
556 | /// # Examples | |
557 | /// | |
54a0048b SL |
558 | /// Basic usage: |
559 | /// | |
1a4d82fc JJ |
560 | /// ``` |
561 | /// use std::collections::BTreeMap; | |
562 | /// | |
563 | /// let mut map = BTreeMap::new(); | |
85aaf69f | 564 | /// map.insert(1, "a"); |
1a4d82fc JJ |
565 | /// assert_eq!(map.get(&1), Some(&"a")); |
566 | /// assert_eq!(map.get(&2), None); | |
567 | /// ``` | |
85aaf69f | 568 | #[stable(feature = "rust1", since = "1.0.0")] |
3157f602 XL |
569 | pub fn get<Q: ?Sized>(&self, key: &Q) -> Option<&V> |
570 | where K: Borrow<Q>, | |
571 | Q: Ord | |
572 | { | |
9cc50fc6 SL |
573 | match search::search_tree(self.root.as_ref(), key) { |
574 | Found(handle) => Some(handle.into_kv().1), | |
3157f602 | 575 | GoDown(_) => None, |
1a4d82fc JJ |
576 | } |
577 | } | |
578 | ||
0531ce1d XL |
579 | /// Returns the key-value pair corresponding to the supplied key. |
580 | /// | |
581 | /// The supplied key may be any borrowed form of the map's key type, but the ordering | |
582 | /// on the borrowed form *must* match the ordering on the key type. | |
583 | /// | |
584 | /// # Examples | |
585 | /// | |
586 | /// ``` | |
587 | /// #![feature(map_get_key_value)] | |
588 | /// use std::collections::BTreeMap; | |
589 | /// | |
590 | /// let mut map = BTreeMap::new(); | |
591 | /// map.insert(1, "a"); | |
592 | /// assert_eq!(map.get_key_value(&1), Some((&1, &"a"))); | |
593 | /// assert_eq!(map.get_key_value(&2), None); | |
594 | /// ``` | |
595 | #[unstable(feature = "map_get_key_value", issue = "49347")] | |
596 | pub fn get_key_value<Q: ?Sized>(&self, k: &Q) -> Option<(&K, &V)> | |
597 | where K: Borrow<Q>, | |
598 | Q: Ord | |
599 | { | |
600 | match search::search_tree(self.root.as_ref(), k) { | |
601 | Found(handle) => Some(handle.into_kv()), | |
602 | GoDown(_) => None, | |
603 | } | |
604 | } | |
605 | ||
cc61c64b | 606 | /// Returns `true` if the map contains a value for the specified key. |
1a4d82fc JJ |
607 | /// |
608 | /// The key may be any borrowed form of the map's key type, but the ordering | |
609 | /// on the borrowed form *must* match the ordering on the key type. | |
610 | /// | |
611 | /// # Examples | |
612 | /// | |
54a0048b SL |
613 | /// Basic usage: |
614 | /// | |
1a4d82fc JJ |
615 | /// ``` |
616 | /// use std::collections::BTreeMap; | |
617 | /// | |
618 | /// let mut map = BTreeMap::new(); | |
85aaf69f | 619 | /// map.insert(1, "a"); |
1a4d82fc JJ |
620 | /// assert_eq!(map.contains_key(&1), true); |
621 | /// assert_eq!(map.contains_key(&2), false); | |
622 | /// ``` | |
85aaf69f | 623 | #[stable(feature = "rust1", since = "1.0.0")] |
3157f602 XL |
624 | pub fn contains_key<Q: ?Sized>(&self, key: &Q) -> bool |
625 | where K: Borrow<Q>, | |
626 | Q: Ord | |
627 | { | |
1a4d82fc JJ |
628 | self.get(key).is_some() |
629 | } | |
630 | ||
631 | /// Returns a mutable reference to the value corresponding to the key. | |
632 | /// | |
633 | /// The key may be any borrowed form of the map's key type, but the ordering | |
634 | /// on the borrowed form *must* match the ordering on the key type. | |
635 | /// | |
636 | /// # Examples | |
637 | /// | |
54a0048b SL |
638 | /// Basic usage: |
639 | /// | |
1a4d82fc JJ |
640 | /// ``` |
641 | /// use std::collections::BTreeMap; | |
642 | /// | |
643 | /// let mut map = BTreeMap::new(); | |
85aaf69f | 644 | /// map.insert(1, "a"); |
9346a6ac AL |
645 | /// if let Some(x) = map.get_mut(&1) { |
646 | /// *x = "b"; | |
1a4d82fc | 647 | /// } |
c34b1796 | 648 | /// assert_eq!(map[&1], "b"); |
1a4d82fc JJ |
649 | /// ``` |
650 | // See `get` for implementation notes, this is basically a copy-paste with mut's added | |
85aaf69f | 651 | #[stable(feature = "rust1", since = "1.0.0")] |
3157f602 XL |
652 | pub fn get_mut<Q: ?Sized>(&mut self, key: &Q) -> Option<&mut V> |
653 | where K: Borrow<Q>, | |
654 | Q: Ord | |
655 | { | |
9cc50fc6 SL |
656 | match search::search_tree(self.root.as_mut(), key) { |
657 | Found(handle) => Some(handle.into_kv_mut().1), | |
3157f602 | 658 | GoDown(_) => None, |
1a4d82fc JJ |
659 | } |
660 | } | |
661 | ||
b039eaaf SL |
662 | /// Inserts a key-value pair into the map. |
663 | /// | |
664 | /// If the map did not have this key present, `None` is returned. | |
665 | /// | |
7453a54e SL |
666 | /// If the map did have this key present, the value is updated, and the old |
667 | /// value is returned. The key is not updated, though; this matters for | |
668 | /// types that can be `==` without being identical. See the [module-level | |
669 | /// documentation] for more. | |
b039eaaf SL |
670 | /// |
671 | /// [module-level documentation]: index.html#insert-and-complex-keys | |
1a4d82fc JJ |
672 | /// |
673 | /// # Examples | |
674 | /// | |
54a0048b SL |
675 | /// Basic usage: |
676 | /// | |
1a4d82fc JJ |
677 | /// ``` |
678 | /// use std::collections::BTreeMap; | |
679 | /// | |
680 | /// let mut map = BTreeMap::new(); | |
85aaf69f | 681 | /// assert_eq!(map.insert(37, "a"), None); |
1a4d82fc JJ |
682 | /// assert_eq!(map.is_empty(), false); |
683 | /// | |
684 | /// map.insert(37, "b"); | |
685 | /// assert_eq!(map.insert(37, "c"), Some("b")); | |
c34b1796 | 686 | /// assert_eq!(map[&37], "c"); |
1a4d82fc | 687 | /// ``` |
85aaf69f | 688 | #[stable(feature = "rust1", since = "1.0.0")] |
9cc50fc6 SL |
689 | pub fn insert(&mut self, key: K, value: V) -> Option<V> { |
690 | match self.entry(key) { | |
691 | Occupied(mut entry) => Some(entry.insert(value)), | |
692 | Vacant(entry) => { | |
693 | entry.insert(value); | |
694 | None | |
1a4d82fc JJ |
695 | } |
696 | } | |
697 | } | |
698 | ||
1a4d82fc JJ |
699 | /// Removes a key from the map, returning the value at the key if the key |
700 | /// was previously in the map. | |
701 | /// | |
702 | /// The key may be any borrowed form of the map's key type, but the ordering | |
703 | /// on the borrowed form *must* match the ordering on the key type. | |
704 | /// | |
705 | /// # Examples | |
706 | /// | |
54a0048b SL |
707 | /// Basic usage: |
708 | /// | |
1a4d82fc JJ |
709 | /// ``` |
710 | /// use std::collections::BTreeMap; | |
711 | /// | |
712 | /// let mut map = BTreeMap::new(); | |
85aaf69f | 713 | /// map.insert(1, "a"); |
1a4d82fc JJ |
714 | /// assert_eq!(map.remove(&1), Some("a")); |
715 | /// assert_eq!(map.remove(&1), None); | |
716 | /// ``` | |
85aaf69f | 717 | #[stable(feature = "rust1", since = "1.0.0")] |
3157f602 XL |
718 | pub fn remove<Q: ?Sized>(&mut self, key: &Q) -> Option<V> |
719 | where K: Borrow<Q>, | |
720 | Q: Ord | |
721 | { | |
9cc50fc6 SL |
722 | match search::search_tree(self.root.as_mut(), key) { |
723 | Found(handle) => { | |
724 | Some(OccupiedEntry { | |
3b2f2976 | 725 | handle, |
3157f602 XL |
726 | length: &mut self.length, |
727 | _marker: PhantomData, | |
728 | } | |
729 | .remove()) | |
730 | } | |
731 | GoDown(_) => None, | |
1a4d82fc JJ |
732 | } |
733 | } | |
85aaf69f | 734 | |
a7813a04 XL |
735 | /// Moves all elements from `other` into `Self`, leaving `other` empty. |
736 | /// | |
737 | /// # Examples | |
738 | /// | |
739 | /// ``` | |
a7813a04 XL |
740 | /// use std::collections::BTreeMap; |
741 | /// | |
742 | /// let mut a = BTreeMap::new(); | |
743 | /// a.insert(1, "a"); | |
744 | /// a.insert(2, "b"); | |
745 | /// a.insert(3, "c"); | |
746 | /// | |
747 | /// let mut b = BTreeMap::new(); | |
748 | /// b.insert(3, "d"); | |
749 | /// b.insert(4, "e"); | |
750 | /// b.insert(5, "f"); | |
751 | /// | |
752 | /// a.append(&mut b); | |
753 | /// | |
754 | /// assert_eq!(a.len(), 5); | |
755 | /// assert_eq!(b.len(), 0); | |
756 | /// | |
757 | /// assert_eq!(a[&1], "a"); | |
758 | /// assert_eq!(a[&2], "b"); | |
759 | /// assert_eq!(a[&3], "d"); | |
760 | /// assert_eq!(a[&4], "e"); | |
761 | /// assert_eq!(a[&5], "f"); | |
762 | /// ``` | |
3157f602 | 763 | #[stable(feature = "btree_append", since = "1.11.0")] |
a7813a04 XL |
764 | pub fn append(&mut self, other: &mut Self) { |
765 | // Do we have to append anything at all? | |
766 | if other.len() == 0 { | |
767 | return; | |
768 | } | |
769 | ||
770 | // We can just swap `self` and `other` if `self` is empty. | |
771 | if self.len() == 0 { | |
772 | mem::swap(self, other); | |
773 | return; | |
774 | } | |
775 | ||
776 | // First, we merge `self` and `other` into a sorted sequence in linear time. | |
777 | let self_iter = mem::replace(self, BTreeMap::new()).into_iter(); | |
778 | let other_iter = mem::replace(other, BTreeMap::new()).into_iter(); | |
779 | let iter = MergeIter { | |
780 | left: self_iter.peekable(), | |
781 | right: other_iter.peekable(), | |
782 | }; | |
783 | ||
784 | // Second, we build a tree from the sorted sequence in linear time. | |
785 | self.from_sorted_iter(iter); | |
786 | self.fix_right_edge(); | |
787 | } | |
788 | ||
32a655c1 SL |
789 | /// Constructs a double-ended iterator over a sub-range of elements in the map. |
790 | /// The simplest way is to use the range syntax `min..max`, thus `range(min..max)` will | |
791 | /// yield elements from min (inclusive) to max (exclusive). | |
792 | /// The range may also be entered as `(Bound<T>, Bound<T>)`, so for example | |
793 | /// `range((Excluded(4), Included(10)))` will yield a left-exclusive, right-inclusive | |
794 | /// range from 4 to 10. | |
9346a6ac | 795 | /// |
8bb4bdeb XL |
796 | /// # Panics |
797 | /// | |
798 | /// Panics if range `start > end`. | |
799 | /// Panics if range `start == end` and both bounds are `Excluded`. | |
800 | /// | |
9346a6ac AL |
801 | /// # Examples |
802 | /// | |
54a0048b SL |
803 | /// Basic usage: |
804 | /// | |
9346a6ac AL |
805 | /// ``` |
806 | /// use std::collections::BTreeMap; | |
0531ce1d | 807 | /// use std::ops::Bound::Included; |
9346a6ac AL |
808 | /// |
809 | /// let mut map = BTreeMap::new(); | |
9cc50fc6 SL |
810 | /// map.insert(3, "a"); |
811 | /// map.insert(5, "b"); | |
812 | /// map.insert(8, "c"); | |
32a655c1 | 813 | /// for (&key, &value) in map.range((Included(&4), Included(&8))) { |
9346a6ac AL |
814 | /// println!("{}: {}", key, value); |
815 | /// } | |
32a655c1 | 816 | /// assert_eq!(Some((&5, &"b")), map.range(4..).next()); |
9346a6ac | 817 | /// ``` |
8bb4bdeb | 818 | #[stable(feature = "btree_range", since = "1.17.0")] |
32a655c1 | 819 | pub fn range<T: ?Sized, R>(&self, range: R) -> Range<K, V> |
0531ce1d | 820 | where T: Ord, K: Borrow<T>, R: RangeBounds<T> |
9cc50fc6 | 821 | { |
8bb4bdeb XL |
822 | let root1 = self.root.as_ref(); |
823 | let root2 = self.root.as_ref(); | |
824 | let (f, b) = range_search(root1, root2, range); | |
9cc50fc6 | 825 | |
8bb4bdeb | 826 | Range { front: f, back: b} |
9cc50fc6 SL |
827 | } |
828 | ||
32a655c1 SL |
829 | /// Constructs a mutable double-ended iterator over a sub-range of elements in the map. |
830 | /// The simplest way is to use the range syntax `min..max`, thus `range(min..max)` will | |
831 | /// yield elements from min (inclusive) to max (exclusive). | |
832 | /// The range may also be entered as `(Bound<T>, Bound<T>)`, so for example | |
833 | /// `range((Excluded(4), Included(10)))` will yield a left-exclusive, right-inclusive | |
834 | /// range from 4 to 10. | |
9cc50fc6 | 835 | /// |
8bb4bdeb XL |
836 | /// # Panics |
837 | /// | |
838 | /// Panics if range `start > end`. | |
839 | /// Panics if range `start == end` and both bounds are `Excluded`. | |
840 | /// | |
9cc50fc6 SL |
841 | /// # Examples |
842 | /// | |
54a0048b SL |
843 | /// Basic usage: |
844 | /// | |
9cc50fc6 | 845 | /// ``` |
9cc50fc6 | 846 | /// use std::collections::BTreeMap; |
9cc50fc6 SL |
847 | /// |
848 | /// let mut map: BTreeMap<&str, i32> = ["Alice", "Bob", "Carol", "Cheryl"].iter() | |
849 | /// .map(|&s| (s, 0)) | |
850 | /// .collect(); | |
32a655c1 | 851 | /// for (_, balance) in map.range_mut("B".."Cheryl") { |
9cc50fc6 SL |
852 | /// *balance += 100; |
853 | /// } | |
854 | /// for (name, balance) in &map { | |
855 | /// println!("{} => {}", name, balance); | |
856 | /// } | |
857 | /// ``` | |
8bb4bdeb | 858 | #[stable(feature = "btree_range", since = "1.17.0")] |
32a655c1 | 859 | pub fn range_mut<T: ?Sized, R>(&mut self, range: R) -> RangeMut<K, V> |
0531ce1d | 860 | where T: Ord, K: Borrow<T>, R: RangeBounds<T> |
9cc50fc6 SL |
861 | { |
862 | let root1 = self.root.as_mut(); | |
863 | let root2 = unsafe { ptr::read(&root1) }; | |
8bb4bdeb | 864 | let (f, b) = range_search(root1, root2, range); |
9cc50fc6 SL |
865 | |
866 | RangeMut { | |
8bb4bdeb XL |
867 | front: f, |
868 | back: b, | |
3157f602 | 869 | _marker: PhantomData, |
9cc50fc6 SL |
870 | } |
871 | } | |
872 | ||
873 | /// Gets the given key's corresponding entry in the map for in-place manipulation. | |
874 | /// | |
875 | /// # Examples | |
876 | /// | |
54a0048b SL |
877 | /// Basic usage: |
878 | /// | |
9cc50fc6 SL |
879 | /// ``` |
880 | /// use std::collections::BTreeMap; | |
881 | /// | |
882 | /// let mut count: BTreeMap<&str, usize> = BTreeMap::new(); | |
883 | /// | |
884 | /// // count the number of occurrences of letters in the vec | |
885 | /// for x in vec!["a","b","a","c","a","b"] { | |
886 | /// *count.entry(x).or_insert(0) += 1; | |
887 | /// } | |
888 | /// | |
889 | /// assert_eq!(count["a"], 3); | |
890 | /// ``` | |
891 | #[stable(feature = "rust1", since = "1.0.0")] | |
892 | pub fn entry(&mut self, key: K) -> Entry<K, V> { | |
893 | match search::search_tree(self.root.as_mut(), &key) { | |
3157f602 XL |
894 | Found(handle) => { |
895 | Occupied(OccupiedEntry { | |
3b2f2976 | 896 | handle, |
3157f602 XL |
897 | length: &mut self.length, |
898 | _marker: PhantomData, | |
899 | }) | |
900 | } | |
901 | GoDown(handle) => { | |
902 | Vacant(VacantEntry { | |
3b2f2976 XL |
903 | key, |
904 | handle, | |
3157f602 XL |
905 | length: &mut self.length, |
906 | _marker: PhantomData, | |
907 | }) | |
908 | } | |
9346a6ac | 909 | } |
85aaf69f | 910 | } |
a7813a04 | 911 | |
3157f602 | 912 | fn from_sorted_iter<I: Iterator<Item = (K, V)>>(&mut self, iter: I) { |
a7813a04 XL |
913 | let mut cur_node = last_leaf_edge(self.root.as_mut()).into_node(); |
914 | // Iterate through all key-value pairs, pushing them into nodes at the right level. | |
915 | for (key, value) in iter { | |
916 | // Try to push key-value pair into the current leaf node. | |
917 | if cur_node.len() < node::CAPACITY { | |
918 | cur_node.push(key, value); | |
919 | } else { | |
920 | // No space left, go up and push there. | |
921 | let mut open_node; | |
922 | let mut test_node = cur_node.forget_type(); | |
923 | loop { | |
924 | match test_node.ascend() { | |
925 | Ok(parent) => { | |
926 | let parent = parent.into_node(); | |
927 | if parent.len() < node::CAPACITY { | |
928 | // Found a node with space left, push here. | |
929 | open_node = parent; | |
930 | break; | |
931 | } else { | |
932 | // Go up again. | |
933 | test_node = parent.forget_type(); | |
934 | } | |
3157f602 | 935 | } |
a7813a04 XL |
936 | Err(node) => { |
937 | // We are at the top, create a new root node and push there. | |
938 | open_node = node.into_root_mut().push_level(); | |
939 | break; | |
3157f602 | 940 | } |
a7813a04 XL |
941 | } |
942 | } | |
943 | ||
944 | // Push key-value pair and new right subtree. | |
945 | let tree_height = open_node.height() - 1; | |
946 | let mut right_tree = node::Root::new_leaf(); | |
947 | for _ in 0..tree_height { | |
948 | right_tree.push_level(); | |
949 | } | |
950 | open_node.push(key, value, right_tree); | |
951 | ||
952 | // Go down to the right-most leaf again. | |
953 | cur_node = last_leaf_edge(open_node.forget_type()).into_node(); | |
954 | } | |
955 | ||
956 | self.length += 1; | |
957 | } | |
958 | } | |
959 | ||
960 | fn fix_right_edge(&mut self) { | |
961 | // Handle underfull nodes, start from the top. | |
962 | let mut cur_node = self.root.as_mut(); | |
963 | while let Internal(internal) = cur_node.force() { | |
964 | // Check if right-most child is underfull. | |
965 | let mut last_edge = internal.last_edge(); | |
966 | let right_child_len = last_edge.reborrow().descend().len(); | |
3157f602 | 967 | if right_child_len < node::MIN_LEN { |
a7813a04 XL |
968 | // We need to steal. |
969 | let mut last_kv = match last_edge.left_kv() { | |
970 | Ok(left) => left, | |
971 | Err(_) => unreachable!(), | |
972 | }; | |
3157f602 | 973 | last_kv.bulk_steal_left(node::MIN_LEN - right_child_len); |
a7813a04 XL |
974 | last_edge = last_kv.right_edge(); |
975 | } | |
976 | ||
977 | // Go further down. | |
978 | cur_node = last_edge.descend(); | |
979 | } | |
980 | } | |
3157f602 XL |
981 | |
982 | /// Splits the collection into two at the given key. Returns everything after the given key, | |
983 | /// including the key. | |
984 | /// | |
985 | /// # Examples | |
986 | /// | |
987 | /// Basic usage: | |
988 | /// | |
989 | /// ``` | |
990 | /// use std::collections::BTreeMap; | |
991 | /// | |
992 | /// let mut a = BTreeMap::new(); | |
993 | /// a.insert(1, "a"); | |
994 | /// a.insert(2, "b"); | |
995 | /// a.insert(3, "c"); | |
996 | /// a.insert(17, "d"); | |
997 | /// a.insert(41, "e"); | |
998 | /// | |
999 | /// let b = a.split_off(&3); | |
1000 | /// | |
1001 | /// assert_eq!(a.len(), 2); | |
1002 | /// assert_eq!(b.len(), 3); | |
1003 | /// | |
1004 | /// assert_eq!(a[&1], "a"); | |
1005 | /// assert_eq!(a[&2], "b"); | |
1006 | /// | |
1007 | /// assert_eq!(b[&3], "c"); | |
1008 | /// assert_eq!(b[&17], "d"); | |
1009 | /// assert_eq!(b[&41], "e"); | |
1010 | /// ``` | |
1011 | #[stable(feature = "btree_split_off", since = "1.11.0")] | |
1012 | pub fn split_off<Q: ?Sized + Ord>(&mut self, key: &Q) -> Self | |
1013 | where K: Borrow<Q> | |
1014 | { | |
1015 | if self.is_empty() { | |
1016 | return Self::new(); | |
1017 | } | |
1018 | ||
1019 | let total_num = self.len(); | |
1020 | ||
1021 | let mut right = Self::new(); | |
1022 | for _ in 0..(self.root.as_ref().height()) { | |
1023 | right.root.push_level(); | |
1024 | } | |
1025 | ||
1026 | { | |
1027 | let mut left_node = self.root.as_mut(); | |
1028 | let mut right_node = right.root.as_mut(); | |
1029 | ||
1030 | loop { | |
1031 | let mut split_edge = match search::search_node(left_node, key) { | |
1032 | // key is going to the right tree | |
1033 | Found(handle) => handle.left_edge(), | |
1034 | GoDown(handle) => handle, | |
1035 | }; | |
1036 | ||
1037 | split_edge.move_suffix(&mut right_node); | |
1038 | ||
1039 | match (split_edge.force(), right_node.force()) { | |
1040 | (Internal(edge), Internal(node)) => { | |
1041 | left_node = edge.descend(); | |
1042 | right_node = node.first_edge().descend(); | |
1043 | } | |
1044 | (Leaf(_), Leaf(_)) => { | |
1045 | break; | |
1046 | } | |
1047 | _ => { | |
1048 | unreachable!(); | |
1049 | } | |
1050 | } | |
1051 | } | |
1052 | } | |
1053 | ||
1054 | self.fix_right_border(); | |
1055 | right.fix_left_border(); | |
1056 | ||
1057 | if self.root.as_ref().height() < right.root.as_ref().height() { | |
1058 | self.recalc_length(); | |
1059 | right.length = total_num - self.len(); | |
1060 | } else { | |
1061 | right.recalc_length(); | |
1062 | self.length = total_num - right.len(); | |
1063 | } | |
1064 | ||
1065 | right | |
1066 | } | |
1067 | ||
1068 | /// Calculates the number of elements if it is incorrect. | |
1069 | fn recalc_length(&mut self) { | |
1070 | fn dfs<K, V>(node: NodeRef<marker::Immut, K, V, marker::LeafOrInternal>) -> usize { | |
1071 | let mut res = node.len(); | |
1072 | ||
1073 | if let Internal(node) = node.force() { | |
1074 | let mut edge = node.first_edge(); | |
1075 | loop { | |
1076 | res += dfs(edge.reborrow().descend()); | |
1077 | match edge.right_kv() { | |
1078 | Ok(right_kv) => { | |
1079 | edge = right_kv.right_edge(); | |
1080 | } | |
1081 | Err(_) => { | |
1082 | break; | |
1083 | } | |
1084 | } | |
1085 | } | |
1086 | } | |
1087 | ||
1088 | res | |
1089 | } | |
1090 | ||
1091 | self.length = dfs(self.root.as_ref()); | |
1092 | } | |
1093 | ||
1094 | /// Removes empty levels on the top. | |
1095 | fn fix_top(&mut self) { | |
1096 | loop { | |
1097 | { | |
1098 | let node = self.root.as_ref(); | |
1099 | if node.height() == 0 || node.len() > 0 { | |
1100 | break; | |
1101 | } | |
1102 | } | |
1103 | self.root.pop_level(); | |
1104 | } | |
1105 | } | |
1106 | ||
1107 | fn fix_right_border(&mut self) { | |
1108 | self.fix_top(); | |
1109 | ||
1110 | { | |
1111 | let mut cur_node = self.root.as_mut(); | |
1112 | ||
1113 | while let Internal(node) = cur_node.force() { | |
1114 | let mut last_kv = node.last_kv(); | |
1115 | ||
1116 | if last_kv.can_merge() { | |
1117 | cur_node = last_kv.merge().descend(); | |
1118 | } else { | |
1119 | let right_len = last_kv.reborrow().right_edge().descend().len(); | |
1120 | // `MINLEN + 1` to avoid readjust if merge happens on the next level. | |
1121 | if right_len < node::MIN_LEN + 1 { | |
1122 | last_kv.bulk_steal_left(node::MIN_LEN + 1 - right_len); | |
1123 | } | |
1124 | cur_node = last_kv.right_edge().descend(); | |
1125 | } | |
1126 | } | |
1127 | } | |
1128 | ||
1129 | self.fix_top(); | |
1130 | } | |
1131 | ||
1132 | /// The symmetric clone of `fix_right_border`. | |
1133 | fn fix_left_border(&mut self) { | |
1134 | self.fix_top(); | |
1135 | ||
1136 | { | |
1137 | let mut cur_node = self.root.as_mut(); | |
1138 | ||
1139 | while let Internal(node) = cur_node.force() { | |
1140 | let mut first_kv = node.first_kv(); | |
1141 | ||
1142 | if first_kv.can_merge() { | |
1143 | cur_node = first_kv.merge().descend(); | |
1144 | } else { | |
1145 | let left_len = first_kv.reborrow().left_edge().descend().len(); | |
1146 | if left_len < node::MIN_LEN + 1 { | |
1147 | first_kv.bulk_steal_right(node::MIN_LEN + 1 - left_len); | |
1148 | } | |
1149 | cur_node = first_kv.left_edge().descend(); | |
1150 | } | |
1151 | } | |
1152 | } | |
1153 | ||
1154 | self.fix_top(); | |
1155 | } | |
85aaf69f SL |
1156 | } |
1157 | ||
c30ab7b3 | 1158 | #[stable(feature = "rust1", since = "1.0.0")] |
9cc50fc6 | 1159 | impl<'a, K: 'a, V: 'a> IntoIterator for &'a BTreeMap<K, V> { |
85aaf69f SL |
1160 | type Item = (&'a K, &'a V); |
1161 | type IntoIter = Iter<'a, K, V>; | |
1162 | ||
1163 | fn into_iter(self) -> Iter<'a, K, V> { | |
1164 | self.iter() | |
1165 | } | |
1166 | } | |
1167 | ||
c30ab7b3 | 1168 | #[stable(feature = "rust1", since = "1.0.0")] |
9cc50fc6 SL |
1169 | impl<'a, K: 'a, V: 'a> Iterator for Iter<'a, K, V> { |
1170 | type Item = (&'a K, &'a V); | |
85aaf69f | 1171 | |
9cc50fc6 SL |
1172 | fn next(&mut self) -> Option<(&'a K, &'a V)> { |
1173 | if self.length == 0 { | |
1174 | None | |
1175 | } else { | |
1176 | self.length -= 1; | |
1177 | unsafe { Some(self.range.next_unchecked()) } | |
1178 | } | |
85aaf69f | 1179 | } |
85aaf69f | 1180 | |
9cc50fc6 SL |
1181 | fn size_hint(&self) -> (usize, Option<usize>) { |
1182 | (self.length, Some(self.length)) | |
1183 | } | |
1a4d82fc JJ |
1184 | } |
1185 | ||
0531ce1d | 1186 | #[stable(feature = "fused", since = "1.26.0")] |
9e0c209e SL |
1187 | impl<'a, K, V> FusedIterator for Iter<'a, K, V> {} |
1188 | ||
c30ab7b3 | 1189 | #[stable(feature = "rust1", since = "1.0.0")] |
9cc50fc6 SL |
1190 | impl<'a, K: 'a, V: 'a> DoubleEndedIterator for Iter<'a, K, V> { |
1191 | fn next_back(&mut self) -> Option<(&'a K, &'a V)> { | |
1192 | if self.length == 0 { | |
1193 | None | |
1194 | } else { | |
1195 | self.length -= 1; | |
1196 | unsafe { Some(self.range.next_back_unchecked()) } | |
85aaf69f SL |
1197 | } |
1198 | } | |
9cc50fc6 | 1199 | } |
85aaf69f | 1200 | |
c30ab7b3 | 1201 | #[stable(feature = "rust1", since = "1.0.0")] |
9cc50fc6 | 1202 | impl<'a, K: 'a, V: 'a> ExactSizeIterator for Iter<'a, K, V> { |
3157f602 XL |
1203 | fn len(&self) -> usize { |
1204 | self.length | |
1205 | } | |
9cc50fc6 | 1206 | } |
1a4d82fc | 1207 | |
c30ab7b3 | 1208 | #[stable(feature = "rust1", since = "1.0.0")] |
9cc50fc6 SL |
1209 | impl<'a, K, V> Clone for Iter<'a, K, V> { |
1210 | fn clone(&self) -> Iter<'a, K, V> { | |
1211 | Iter { | |
1212 | range: self.range.clone(), | |
3157f602 | 1213 | length: self.length, |
1a4d82fc JJ |
1214 | } |
1215 | } | |
9cc50fc6 | 1216 | } |
1a4d82fc | 1217 | |
c30ab7b3 | 1218 | #[stable(feature = "rust1", since = "1.0.0")] |
9cc50fc6 SL |
1219 | impl<'a, K: 'a, V: 'a> IntoIterator for &'a mut BTreeMap<K, V> { |
1220 | type Item = (&'a K, &'a mut V); | |
1221 | type IntoIter = IterMut<'a, K, V>; | |
1222 | ||
1223 | fn into_iter(self) -> IterMut<'a, K, V> { | |
1224 | self.iter_mut() | |
1a4d82fc | 1225 | } |
9cc50fc6 | 1226 | } |
1a4d82fc | 1227 | |
c30ab7b3 | 1228 | #[stable(feature = "rust1", since = "1.0.0")] |
9cc50fc6 SL |
1229 | impl<'a, K: 'a, V: 'a> Iterator for IterMut<'a, K, V> { |
1230 | type Item = (&'a K, &'a mut V); | |
1a4d82fc | 1231 | |
9cc50fc6 SL |
1232 | fn next(&mut self) -> Option<(&'a K, &'a mut V)> { |
1233 | if self.length == 0 { | |
1234 | None | |
1235 | } else { | |
1236 | self.length -= 1; | |
1237 | unsafe { Some(self.range.next_unchecked()) } | |
1238 | } | |
1a4d82fc JJ |
1239 | } |
1240 | ||
9cc50fc6 SL |
1241 | fn size_hint(&self) -> (usize, Option<usize>) { |
1242 | (self.length, Some(self.length)) | |
1a4d82fc | 1243 | } |
9cc50fc6 | 1244 | } |
1a4d82fc | 1245 | |
c30ab7b3 | 1246 | #[stable(feature = "rust1", since = "1.0.0")] |
9cc50fc6 SL |
1247 | impl<'a, K: 'a, V: 'a> DoubleEndedIterator for IterMut<'a, K, V> { |
1248 | fn next_back(&mut self) -> Option<(&'a K, &'a mut V)> { | |
1249 | if self.length == 0 { | |
1250 | None | |
1251 | } else { | |
1252 | self.length -= 1; | |
1253 | unsafe { Some(self.range.next_back_unchecked()) } | |
1254 | } | |
1a4d82fc | 1255 | } |
9cc50fc6 | 1256 | } |
1a4d82fc | 1257 | |
c30ab7b3 | 1258 | #[stable(feature = "rust1", since = "1.0.0")] |
9cc50fc6 | 1259 | impl<'a, K: 'a, V: 'a> ExactSizeIterator for IterMut<'a, K, V> { |
3157f602 XL |
1260 | fn len(&self) -> usize { |
1261 | self.length | |
1262 | } | |
9cc50fc6 | 1263 | } |
1a4d82fc | 1264 | |
0531ce1d | 1265 | #[stable(feature = "fused", since = "1.26.0")] |
9e0c209e SL |
1266 | impl<'a, K, V> FusedIterator for IterMut<'a, K, V> {} |
1267 | ||
c30ab7b3 | 1268 | #[stable(feature = "rust1", since = "1.0.0")] |
9cc50fc6 SL |
1269 | impl<K, V> IntoIterator for BTreeMap<K, V> { |
1270 | type Item = (K, V); | |
1271 | type IntoIter = IntoIter<K, V>; | |
1a4d82fc | 1272 | |
9cc50fc6 SL |
1273 | fn into_iter(self) -> IntoIter<K, V> { |
1274 | let root1 = unsafe { ptr::read(&self.root).into_ref() }; | |
1275 | let root2 = unsafe { ptr::read(&self.root).into_ref() }; | |
1276 | let len = self.length; | |
1277 | mem::forget(self); | |
1a4d82fc | 1278 | |
9cc50fc6 SL |
1279 | IntoIter { |
1280 | front: first_leaf_edge(root1), | |
1281 | back: last_leaf_edge(root2), | |
3157f602 | 1282 | length: len, |
1a4d82fc JJ |
1283 | } |
1284 | } | |
9cc50fc6 | 1285 | } |
1a4d82fc | 1286 | |
c30ab7b3 | 1287 | #[stable(feature = "btree_drop", since = "1.7.0")] |
9cc50fc6 SL |
1288 | impl<K, V> Drop for IntoIter<K, V> { |
1289 | fn drop(&mut self) { | |
3157f602 XL |
1290 | for _ in &mut *self { |
1291 | } | |
9cc50fc6 SL |
1292 | unsafe { |
1293 | let leaf_node = ptr::read(&self.front).into_node(); | |
1294 | if let Some(first_parent) = leaf_node.deallocate_and_ascend() { | |
1295 | let mut cur_node = first_parent.into_node(); | |
1296 | while let Some(parent) = cur_node.deallocate_and_ascend() { | |
1297 | cur_node = parent.into_node() | |
1298 | } | |
1a4d82fc JJ |
1299 | } |
1300 | } | |
1301 | } | |
9cc50fc6 | 1302 | } |
1a4d82fc | 1303 | |
c30ab7b3 | 1304 | #[stable(feature = "rust1", since = "1.0.0")] |
9cc50fc6 SL |
1305 | impl<K, V> Iterator for IntoIter<K, V> { |
1306 | type Item = (K, V); | |
1a4d82fc | 1307 | |
9cc50fc6 SL |
1308 | fn next(&mut self) -> Option<(K, V)> { |
1309 | if self.length == 0 { | |
1310 | return None; | |
1311 | } else { | |
1312 | self.length -= 1; | |
1a4d82fc | 1313 | } |
1a4d82fc | 1314 | |
9cc50fc6 | 1315 | let handle = unsafe { ptr::read(&self.front) }; |
1a4d82fc | 1316 | |
9cc50fc6 SL |
1317 | let mut cur_handle = match handle.right_kv() { |
1318 | Ok(kv) => { | |
1319 | let k = unsafe { ptr::read(kv.reborrow().into_kv().0) }; | |
1320 | let v = unsafe { ptr::read(kv.reborrow().into_kv().1) }; | |
1321 | self.front = kv.right_edge(); | |
1322 | return Some((k, v)); | |
3157f602 | 1323 | } |
9cc50fc6 SL |
1324 | Err(last_edge) => unsafe { |
1325 | unwrap_unchecked(last_edge.into_node().deallocate_and_ascend()) | |
3157f602 | 1326 | }, |
9cc50fc6 | 1327 | }; |
1a4d82fc | 1328 | |
9cc50fc6 SL |
1329 | loop { |
1330 | match cur_handle.right_kv() { | |
1331 | Ok(kv) => { | |
1332 | let k = unsafe { ptr::read(kv.reborrow().into_kv().0) }; | |
1333 | let v = unsafe { ptr::read(kv.reborrow().into_kv().1) }; | |
1334 | self.front = first_leaf_edge(kv.right_edge().descend()); | |
1335 | return Some((k, v)); | |
3157f602 | 1336 | } |
9cc50fc6 SL |
1337 | Err(last_edge) => unsafe { |
1338 | cur_handle = unwrap_unchecked(last_edge.into_node().deallocate_and_ascend()); | |
3157f602 | 1339 | }, |
1a4d82fc JJ |
1340 | } |
1341 | } | |
1342 | } | |
1343 | ||
9cc50fc6 SL |
1344 | fn size_hint(&self) -> (usize, Option<usize>) { |
1345 | (self.length, Some(self.length)) | |
1346 | } | |
1347 | } | |
1348 | ||
c30ab7b3 | 1349 | #[stable(feature = "rust1", since = "1.0.0")] |
9cc50fc6 SL |
1350 | impl<K, V> DoubleEndedIterator for IntoIter<K, V> { |
1351 | fn next_back(&mut self) -> Option<(K, V)> { | |
1352 | if self.length == 0 { | |
1353 | return None; | |
1354 | } else { | |
1355 | self.length -= 1; | |
1a4d82fc JJ |
1356 | } |
1357 | ||
9cc50fc6 SL |
1358 | let handle = unsafe { ptr::read(&self.back) }; |
1359 | ||
1360 | let mut cur_handle = match handle.left_kv() { | |
1361 | Ok(kv) => { | |
1362 | let k = unsafe { ptr::read(kv.reborrow().into_kv().0) }; | |
1363 | let v = unsafe { ptr::read(kv.reborrow().into_kv().1) }; | |
1364 | self.back = kv.left_edge(); | |
1365 | return Some((k, v)); | |
3157f602 | 1366 | } |
9cc50fc6 SL |
1367 | Err(last_edge) => unsafe { |
1368 | unwrap_unchecked(last_edge.into_node().deallocate_and_ascend()) | |
3157f602 | 1369 | }, |
9cc50fc6 | 1370 | }; |
1a4d82fc | 1371 | |
9cc50fc6 SL |
1372 | loop { |
1373 | match cur_handle.left_kv() { | |
1374 | Ok(kv) => { | |
1375 | let k = unsafe { ptr::read(kv.reborrow().into_kv().0) }; | |
1376 | let v = unsafe { ptr::read(kv.reborrow().into_kv().1) }; | |
1377 | self.back = last_leaf_edge(kv.left_edge().descend()); | |
1378 | return Some((k, v)); | |
3157f602 | 1379 | } |
9cc50fc6 SL |
1380 | Err(last_edge) => unsafe { |
1381 | cur_handle = unwrap_unchecked(last_edge.into_node().deallocate_and_ascend()); | |
3157f602 | 1382 | }, |
1a4d82fc JJ |
1383 | } |
1384 | } | |
1385 | } | |
1386 | } | |
1387 | ||
c30ab7b3 | 1388 | #[stable(feature = "rust1", since = "1.0.0")] |
9cc50fc6 | 1389 | impl<K, V> ExactSizeIterator for IntoIter<K, V> { |
3157f602 XL |
1390 | fn len(&self) -> usize { |
1391 | self.length | |
1392 | } | |
1a4d82fc JJ |
1393 | } |
1394 | ||
0531ce1d | 1395 | #[stable(feature = "fused", since = "1.26.0")] |
9e0c209e SL |
1396 | impl<K, V> FusedIterator for IntoIter<K, V> {} |
1397 | ||
c30ab7b3 | 1398 | #[stable(feature = "rust1", since = "1.0.0")] |
9cc50fc6 SL |
1399 | impl<'a, K, V> Iterator for Keys<'a, K, V> { |
1400 | type Item = &'a K; | |
1401 | ||
1402 | fn next(&mut self) -> Option<&'a K> { | |
1403 | self.inner.next().map(|(k, _)| k) | |
1a4d82fc | 1404 | } |
1a4d82fc | 1405 | |
9cc50fc6 SL |
1406 | fn size_hint(&self) -> (usize, Option<usize>) { |
1407 | self.inner.size_hint() | |
62682a34 SL |
1408 | } |
1409 | } | |
1410 | ||
c30ab7b3 | 1411 | #[stable(feature = "rust1", since = "1.0.0")] |
9cc50fc6 SL |
1412 | impl<'a, K, V> DoubleEndedIterator for Keys<'a, K, V> { |
1413 | fn next_back(&mut self) -> Option<&'a K> { | |
1414 | self.inner.next_back().map(|(k, _)| k) | |
1a4d82fc JJ |
1415 | } |
1416 | } | |
1417 | ||
c30ab7b3 | 1418 | #[stable(feature = "rust1", since = "1.0.0")] |
9cc50fc6 SL |
1419 | impl<'a, K, V> ExactSizeIterator for Keys<'a, K, V> { |
1420 | fn len(&self) -> usize { | |
1421 | self.inner.len() | |
1a4d82fc JJ |
1422 | } |
1423 | } | |
1424 | ||
0531ce1d | 1425 | #[stable(feature = "fused", since = "1.26.0")] |
9e0c209e SL |
1426 | impl<'a, K, V> FusedIterator for Keys<'a, K, V> {} |
1427 | ||
c30ab7b3 | 1428 | #[stable(feature = "rust1", since = "1.0.0")] |
9cc50fc6 SL |
1429 | impl<'a, K, V> Clone for Keys<'a, K, V> { |
1430 | fn clone(&self) -> Keys<'a, K, V> { | |
3157f602 | 1431 | Keys { inner: self.inner.clone() } |
1a4d82fc JJ |
1432 | } |
1433 | } | |
1434 | ||
c30ab7b3 | 1435 | #[stable(feature = "rust1", since = "1.0.0")] |
9cc50fc6 SL |
1436 | impl<'a, K, V> Iterator for Values<'a, K, V> { |
1437 | type Item = &'a V; | |
1a4d82fc | 1438 | |
9cc50fc6 SL |
1439 | fn next(&mut self) -> Option<&'a V> { |
1440 | self.inner.next().map(|(_, v)| v) | |
1a4d82fc | 1441 | } |
1a4d82fc | 1442 | |
9cc50fc6 SL |
1443 | fn size_hint(&self) -> (usize, Option<usize>) { |
1444 | self.inner.size_hint() | |
1a4d82fc JJ |
1445 | } |
1446 | } | |
1447 | ||
c30ab7b3 | 1448 | #[stable(feature = "rust1", since = "1.0.0")] |
9cc50fc6 SL |
1449 | impl<'a, K, V> DoubleEndedIterator for Values<'a, K, V> { |
1450 | fn next_back(&mut self) -> Option<&'a V> { | |
1451 | self.inner.next_back().map(|(_, v)| v) | |
1a4d82fc JJ |
1452 | } |
1453 | } | |
1454 | ||
c30ab7b3 | 1455 | #[stable(feature = "rust1", since = "1.0.0")] |
9cc50fc6 SL |
1456 | impl<'a, K, V> ExactSizeIterator for Values<'a, K, V> { |
1457 | fn len(&self) -> usize { | |
1458 | self.inner.len() | |
1a4d82fc JJ |
1459 | } |
1460 | } | |
1461 | ||
0531ce1d | 1462 | #[stable(feature = "fused", since = "1.26.0")] |
9e0c209e SL |
1463 | impl<'a, K, V> FusedIterator for Values<'a, K, V> {} |
1464 | ||
c30ab7b3 | 1465 | #[stable(feature = "rust1", since = "1.0.0")] |
9cc50fc6 SL |
1466 | impl<'a, K, V> Clone for Values<'a, K, V> { |
1467 | fn clone(&self) -> Values<'a, K, V> { | |
3157f602 | 1468 | Values { inner: self.inner.clone() } |
1a4d82fc JJ |
1469 | } |
1470 | } | |
1471 | ||
cc61c64b | 1472 | #[stable(feature = "btree_range", since = "1.17.0")] |
9cc50fc6 SL |
1473 | impl<'a, K, V> Iterator for Range<'a, K, V> { |
1474 | type Item = (&'a K, &'a V); | |
1a4d82fc | 1475 | |
9cc50fc6 SL |
1476 | fn next(&mut self) -> Option<(&'a K, &'a V)> { |
1477 | if self.front == self.back { | |
1478 | None | |
1479 | } else { | |
1480 | unsafe { Some(self.next_unchecked()) } | |
1481 | } | |
1a4d82fc JJ |
1482 | } |
1483 | } | |
1484 | ||
a7813a04 | 1485 | #[stable(feature = "map_values_mut", since = "1.10.0")] |
54a0048b SL |
1486 | impl<'a, K, V> Iterator for ValuesMut<'a, K, V> { |
1487 | type Item = &'a mut V; | |
1488 | ||
1489 | fn next(&mut self) -> Option<&'a mut V> { | |
1490 | self.inner.next().map(|(_, v)| v) | |
1491 | } | |
1492 | ||
1493 | fn size_hint(&self) -> (usize, Option<usize>) { | |
1494 | self.inner.size_hint() | |
1495 | } | |
1496 | } | |
1497 | ||
a7813a04 | 1498 | #[stable(feature = "map_values_mut", since = "1.10.0")] |
54a0048b SL |
1499 | impl<'a, K, V> DoubleEndedIterator for ValuesMut<'a, K, V> { |
1500 | fn next_back(&mut self) -> Option<&'a mut V> { | |
1501 | self.inner.next_back().map(|(_, v)| v) | |
1502 | } | |
1503 | } | |
1504 | ||
a7813a04 | 1505 | #[stable(feature = "map_values_mut", since = "1.10.0")] |
54a0048b SL |
1506 | impl<'a, K, V> ExactSizeIterator for ValuesMut<'a, K, V> { |
1507 | fn len(&self) -> usize { | |
1508 | self.inner.len() | |
1509 | } | |
1510 | } | |
1511 | ||
0531ce1d | 1512 | #[stable(feature = "fused", since = "1.26.0")] |
9e0c209e SL |
1513 | impl<'a, K, V> FusedIterator for ValuesMut<'a, K, V> {} |
1514 | ||
1515 | ||
9cc50fc6 SL |
1516 | impl<'a, K, V> Range<'a, K, V> { |
1517 | unsafe fn next_unchecked(&mut self) -> (&'a K, &'a V) { | |
1518 | let handle = self.front; | |
1a4d82fc | 1519 | |
9cc50fc6 SL |
1520 | let mut cur_handle = match handle.right_kv() { |
1521 | Ok(kv) => { | |
1522 | let ret = kv.into_kv(); | |
1523 | self.front = kv.right_edge(); | |
1524 | return ret; | |
3157f602 | 1525 | } |
9cc50fc6 SL |
1526 | Err(last_edge) => { |
1527 | let next_level = last_edge.into_node().ascend().ok(); | |
1528 | unwrap_unchecked(next_level) | |
1529 | } | |
1530 | }; | |
1a4d82fc | 1531 | |
9cc50fc6 SL |
1532 | loop { |
1533 | match cur_handle.right_kv() { | |
1534 | Ok(kv) => { | |
1535 | let ret = kv.into_kv(); | |
1536 | self.front = first_leaf_edge(kv.right_edge().descend()); | |
1537 | return ret; | |
3157f602 | 1538 | } |
9cc50fc6 SL |
1539 | Err(last_edge) => { |
1540 | let next_level = last_edge.into_node().ascend().ok(); | |
1541 | cur_handle = unwrap_unchecked(next_level); | |
92a42be0 | 1542 | } |
1a4d82fc JJ |
1543 | } |
1544 | } | |
1545 | } | |
9cc50fc6 | 1546 | } |
1a4d82fc | 1547 | |
cc61c64b | 1548 | #[stable(feature = "btree_range", since = "1.17.0")] |
9cc50fc6 SL |
1549 | impl<'a, K, V> DoubleEndedIterator for Range<'a, K, V> { |
1550 | fn next_back(&mut self) -> Option<(&'a K, &'a V)> { | |
1551 | if self.front == self.back { | |
1552 | None | |
1553 | } else { | |
1554 | unsafe { Some(self.next_back_unchecked()) } | |
1555 | } | |
1a4d82fc JJ |
1556 | } |
1557 | } | |
1558 | ||
9cc50fc6 SL |
1559 | impl<'a, K, V> Range<'a, K, V> { |
1560 | unsafe fn next_back_unchecked(&mut self) -> (&'a K, &'a V) { | |
1561 | let handle = self.back; | |
1a4d82fc | 1562 | |
9cc50fc6 SL |
1563 | let mut cur_handle = match handle.left_kv() { |
1564 | Ok(kv) => { | |
1565 | let ret = kv.into_kv(); | |
1566 | self.back = kv.left_edge(); | |
1567 | return ret; | |
3157f602 | 1568 | } |
9cc50fc6 SL |
1569 | Err(last_edge) => { |
1570 | let next_level = last_edge.into_node().ascend().ok(); | |
1571 | unwrap_unchecked(next_level) | |
1572 | } | |
1573 | }; | |
1574 | ||
1575 | loop { | |
1576 | match cur_handle.left_kv() { | |
1577 | Ok(kv) => { | |
1578 | let ret = kv.into_kv(); | |
1579 | self.back = last_leaf_edge(kv.left_edge().descend()); | |
1580 | return ret; | |
3157f602 | 1581 | } |
9cc50fc6 SL |
1582 | Err(last_edge) => { |
1583 | let next_level = last_edge.into_node().ascend().ok(); | |
1584 | cur_handle = unwrap_unchecked(next_level); | |
92a42be0 | 1585 | } |
1a4d82fc JJ |
1586 | } |
1587 | } | |
1588 | } | |
1589 | } | |
1590 | ||
0531ce1d | 1591 | #[stable(feature = "fused", since = "1.26.0")] |
9e0c209e SL |
1592 | impl<'a, K, V> FusedIterator for Range<'a, K, V> {} |
1593 | ||
cc61c64b | 1594 | #[stable(feature = "btree_range", since = "1.17.0")] |
9cc50fc6 SL |
1595 | impl<'a, K, V> Clone for Range<'a, K, V> { |
1596 | fn clone(&self) -> Range<'a, K, V> { | |
1597 | Range { | |
1598 | front: self.front, | |
3157f602 | 1599 | back: self.back, |
9cc50fc6 | 1600 | } |
92a42be0 | 1601 | } |
1a4d82fc | 1602 | } |
1a4d82fc | 1603 | |
cc61c64b | 1604 | #[stable(feature = "btree_range", since = "1.17.0")] |
9cc50fc6 | 1605 | impl<'a, K, V> Iterator for RangeMut<'a, K, V> { |
1a4d82fc JJ |
1606 | type Item = (&'a K, &'a mut V); |
1607 | ||
92a42be0 | 1608 | fn next(&mut self) -> Option<(&'a K, &'a mut V)> { |
9cc50fc6 SL |
1609 | if self.front == self.back { |
1610 | None | |
1611 | } else { | |
3157f602 | 1612 | unsafe { Some(self.next_unchecked()) } |
9cc50fc6 | 1613 | } |
92a42be0 | 1614 | } |
1a4d82fc | 1615 | } |
1a4d82fc | 1616 | |
9cc50fc6 SL |
1617 | impl<'a, K, V> RangeMut<'a, K, V> { |
1618 | unsafe fn next_unchecked(&mut self) -> (&'a K, &'a mut V) { | |
1619 | let handle = ptr::read(&self.front); | |
1a4d82fc | 1620 | |
9cc50fc6 SL |
1621 | let mut cur_handle = match handle.right_kv() { |
1622 | Ok(kv) => { | |
1623 | let (k, v) = ptr::read(&kv).into_kv_mut(); | |
1624 | self.front = kv.right_edge(); | |
1625 | return (k, v); | |
3157f602 | 1626 | } |
9cc50fc6 SL |
1627 | Err(last_edge) => { |
1628 | let next_level = last_edge.into_node().ascend().ok(); | |
1629 | unwrap_unchecked(next_level) | |
1630 | } | |
1631 | }; | |
1a4d82fc | 1632 | |
9cc50fc6 SL |
1633 | loop { |
1634 | match cur_handle.right_kv() { | |
1635 | Ok(kv) => { | |
1636 | let (k, v) = ptr::read(&kv).into_kv_mut(); | |
1637 | self.front = first_leaf_edge(kv.right_edge().descend()); | |
1638 | return (k, v); | |
3157f602 | 1639 | } |
9cc50fc6 SL |
1640 | Err(last_edge) => { |
1641 | let next_level = last_edge.into_node().ascend().ok(); | |
1642 | cur_handle = unwrap_unchecked(next_level); | |
1643 | } | |
1644 | } | |
1645 | } | |
92a42be0 | 1646 | } |
c34b1796 | 1647 | } |
1a4d82fc | 1648 | |
cc61c64b | 1649 | #[stable(feature = "btree_range", since = "1.17.0")] |
9cc50fc6 SL |
1650 | impl<'a, K, V> DoubleEndedIterator for RangeMut<'a, K, V> { |
1651 | fn next_back(&mut self) -> Option<(&'a K, &'a mut V)> { | |
1652 | if self.front == self.back { | |
1653 | None | |
1654 | } else { | |
1655 | unsafe { Some(self.next_back_unchecked()) } | |
1656 | } | |
92a42be0 | 1657 | } |
1a4d82fc | 1658 | } |
1a4d82fc | 1659 | |
0531ce1d | 1660 | #[stable(feature = "fused", since = "1.26.0")] |
9e0c209e SL |
1661 | impl<'a, K, V> FusedIterator for RangeMut<'a, K, V> {} |
1662 | ||
9cc50fc6 SL |
1663 | impl<'a, K, V> RangeMut<'a, K, V> { |
1664 | unsafe fn next_back_unchecked(&mut self) -> (&'a K, &'a mut V) { | |
1665 | let handle = ptr::read(&self.back); | |
1a4d82fc | 1666 | |
9cc50fc6 SL |
1667 | let mut cur_handle = match handle.left_kv() { |
1668 | Ok(kv) => { | |
1669 | let (k, v) = ptr::read(&kv).into_kv_mut(); | |
1670 | self.back = kv.left_edge(); | |
1671 | return (k, v); | |
3157f602 | 1672 | } |
9cc50fc6 SL |
1673 | Err(last_edge) => { |
1674 | let next_level = last_edge.into_node().ascend().ok(); | |
1675 | unwrap_unchecked(next_level) | |
1676 | } | |
1677 | }; | |
1a4d82fc | 1678 | |
9cc50fc6 SL |
1679 | loop { |
1680 | match cur_handle.left_kv() { | |
1681 | Ok(kv) => { | |
1682 | let (k, v) = ptr::read(&kv).into_kv_mut(); | |
1683 | self.back = last_leaf_edge(kv.left_edge().descend()); | |
1684 | return (k, v); | |
3157f602 | 1685 | } |
9cc50fc6 SL |
1686 | Err(last_edge) => { |
1687 | let next_level = last_edge.into_node().ascend().ok(); | |
1688 | cur_handle = unwrap_unchecked(next_level); | |
1689 | } | |
1690 | } | |
1691 | } | |
92a42be0 | 1692 | } |
1a4d82fc | 1693 | } |
9cc50fc6 | 1694 | |
c30ab7b3 | 1695 | #[stable(feature = "rust1", since = "1.0.0")] |
9cc50fc6 | 1696 | impl<K: Ord, V> FromIterator<(K, V)> for BTreeMap<K, V> { |
3157f602 | 1697 | fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> BTreeMap<K, V> { |
9cc50fc6 SL |
1698 | let mut map = BTreeMap::new(); |
1699 | map.extend(iter); | |
1700 | map | |
92a42be0 | 1701 | } |
1a4d82fc | 1702 | } |
1a4d82fc | 1703 | |
c30ab7b3 | 1704 | #[stable(feature = "rust1", since = "1.0.0")] |
9cc50fc6 SL |
1705 | impl<K: Ord, V> Extend<(K, V)> for BTreeMap<K, V> { |
1706 | #[inline] | |
3157f602 | 1707 | fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) { |
9cc50fc6 SL |
1708 | for (k, v) in iter { |
1709 | self.insert(k, v); | |
1710 | } | |
92a42be0 | 1711 | } |
c34b1796 | 1712 | } |
85aaf69f | 1713 | |
c30ab7b3 | 1714 | #[stable(feature = "extend_ref", since = "1.2.0")] |
9cc50fc6 | 1715 | impl<'a, K: Ord + Copy, V: Copy> Extend<(&'a K, &'a V)> for BTreeMap<K, V> { |
3157f602 | 1716 | fn extend<I: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: I) { |
9cc50fc6 | 1717 | self.extend(iter.into_iter().map(|(&key, &value)| (key, value))); |
92a42be0 | 1718 | } |
85aaf69f | 1719 | } |
9cc50fc6 | 1720 | |
c30ab7b3 | 1721 | #[stable(feature = "rust1", since = "1.0.0")] |
9cc50fc6 SL |
1722 | impl<K: Hash, V: Hash> Hash for BTreeMap<K, V> { |
1723 | fn hash<H: Hasher>(&self, state: &mut H) { | |
1724 | for elt in self { | |
1725 | elt.hash(state); | |
1726 | } | |
92a42be0 | 1727 | } |
85aaf69f SL |
1728 | } |
1729 | ||
c30ab7b3 | 1730 | #[stable(feature = "rust1", since = "1.0.0")] |
9cc50fc6 | 1731 | impl<K: Ord, V> Default for BTreeMap<K, V> { |
9e0c209e | 1732 | /// Creates an empty `BTreeMap<K, V>`. |
9cc50fc6 SL |
1733 | fn default() -> BTreeMap<K, V> { |
1734 | BTreeMap::new() | |
92a42be0 | 1735 | } |
85aaf69f | 1736 | } |
9cc50fc6 | 1737 | |
c30ab7b3 | 1738 | #[stable(feature = "rust1", since = "1.0.0")] |
9cc50fc6 SL |
1739 | impl<K: PartialEq, V: PartialEq> PartialEq for BTreeMap<K, V> { |
1740 | fn eq(&self, other: &BTreeMap<K, V>) -> bool { | |
3157f602 | 1741 | self.len() == other.len() && self.iter().zip(other).all(|(a, b)| a == b) |
92a42be0 | 1742 | } |
85aaf69f SL |
1743 | } |
1744 | ||
c30ab7b3 | 1745 | #[stable(feature = "rust1", since = "1.0.0")] |
9cc50fc6 | 1746 | impl<K: Eq, V: Eq> Eq for BTreeMap<K, V> {} |
c34b1796 | 1747 | |
c30ab7b3 | 1748 | #[stable(feature = "rust1", since = "1.0.0")] |
9cc50fc6 SL |
1749 | impl<K: PartialOrd, V: PartialOrd> PartialOrd for BTreeMap<K, V> { |
1750 | #[inline] | |
1751 | fn partial_cmp(&self, other: &BTreeMap<K, V>) -> Option<Ordering> { | |
1752 | self.iter().partial_cmp(other.iter()) | |
c34b1796 | 1753 | } |
1a4d82fc JJ |
1754 | } |
1755 | ||
c30ab7b3 | 1756 | #[stable(feature = "rust1", since = "1.0.0")] |
9cc50fc6 SL |
1757 | impl<K: Ord, V: Ord> Ord for BTreeMap<K, V> { |
1758 | #[inline] | |
1759 | fn cmp(&self, other: &BTreeMap<K, V>) -> Ordering { | |
1760 | self.iter().cmp(other.iter()) | |
1a4d82fc JJ |
1761 | } |
1762 | } | |
1763 | ||
c30ab7b3 | 1764 | #[stable(feature = "rust1", since = "1.0.0")] |
9cc50fc6 SL |
1765 | impl<K: Debug, V: Debug> Debug for BTreeMap<K, V> { |
1766 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
1767 | f.debug_map().entries(self.iter()).finish() | |
1a4d82fc | 1768 | } |
9cc50fc6 | 1769 | } |
1a4d82fc | 1770 | |
c30ab7b3 | 1771 | #[stable(feature = "rust1", since = "1.0.0")] |
9cc50fc6 | 1772 | impl<'a, K: Ord, Q: ?Sized, V> Index<&'a Q> for BTreeMap<K, V> |
3157f602 XL |
1773 | where K: Borrow<Q>, |
1774 | Q: Ord | |
9cc50fc6 SL |
1775 | { |
1776 | type Output = V; | |
1a4d82fc | 1777 | |
2c00a5a8 XL |
1778 | /// Returns a reference to the value corresponding to the supplied key. |
1779 | /// | |
1780 | /// # Panics | |
1781 | /// | |
1782 | /// Panics if the key is not present in the `BTreeMap`. | |
9cc50fc6 SL |
1783 | #[inline] |
1784 | fn index(&self, key: &Q) -> &V { | |
1785 | self.get(key).expect("no entry found for key") | |
1a4d82fc | 1786 | } |
9cc50fc6 | 1787 | } |
1a4d82fc | 1788 | |
3157f602 XL |
1789 | fn first_leaf_edge<BorrowType, K, V> |
1790 | (mut node: NodeRef<BorrowType, K, V, marker::LeafOrInternal>) | |
1791 | -> Handle<NodeRef<BorrowType, K, V, marker::Leaf>, marker::Edge> { | |
9cc50fc6 SL |
1792 | loop { |
1793 | match node.force() { | |
1794 | Leaf(leaf) => return leaf.first_edge(), | |
1795 | Internal(internal) => { | |
1796 | node = internal.first_edge().descend(); | |
1797 | } | |
1798 | } | |
1a4d82fc | 1799 | } |
9cc50fc6 | 1800 | } |
1a4d82fc | 1801 | |
3157f602 XL |
1802 | fn last_leaf_edge<BorrowType, K, V> |
1803 | (mut node: NodeRef<BorrowType, K, V, marker::LeafOrInternal>) | |
1804 | -> Handle<NodeRef<BorrowType, K, V, marker::Leaf>, marker::Edge> { | |
9cc50fc6 SL |
1805 | loop { |
1806 | match node.force() { | |
1807 | Leaf(leaf) => return leaf.last_edge(), | |
1808 | Internal(internal) => { | |
1809 | node = internal.last_edge().descend(); | |
1810 | } | |
1811 | } | |
1a4d82fc JJ |
1812 | } |
1813 | } | |
1814 | ||
0531ce1d | 1815 | fn range_search<BorrowType, K, V, Q: ?Sized, R: RangeBounds<Q>>( |
8bb4bdeb XL |
1816 | root1: NodeRef<BorrowType, K, V, marker::LeafOrInternal>, |
1817 | root2: NodeRef<BorrowType, K, V, marker::LeafOrInternal>, | |
1818 | range: R | |
1819 | )-> (Handle<NodeRef<BorrowType, K, V, marker::Leaf>, marker::Edge>, | |
1820 | Handle<NodeRef<BorrowType, K, V, marker::Leaf>, marker::Edge>) | |
1821 | where Q: Ord, K: Borrow<Q> | |
1822 | { | |
1823 | match (range.start(), range.end()) { | |
1824 | (Excluded(s), Excluded(e)) if s==e => | |
1825 | panic!("range start and end are equal and excluded in BTreeMap"), | |
1826 | (Included(s), Included(e)) | | |
1827 | (Included(s), Excluded(e)) | | |
1828 | (Excluded(s), Included(e)) | | |
1829 | (Excluded(s), Excluded(e)) if s>e => | |
1830 | panic!("range start is greater than range end in BTreeMap"), | |
1831 | _ => {}, | |
1832 | }; | |
1833 | ||
1834 | let mut min_node = root1; | |
1835 | let mut max_node = root2; | |
1836 | let mut min_found = false; | |
1837 | let mut max_found = false; | |
1838 | let mut diverged = false; | |
1839 | ||
1840 | loop { | |
1841 | let min_edge = match (min_found, range.start()) { | |
1842 | (false, Included(key)) => match search::search_linear(&min_node, key) { | |
1843 | (i, true) => { min_found = true; i }, | |
1844 | (i, false) => i, | |
1845 | }, | |
1846 | (false, Excluded(key)) => match search::search_linear(&min_node, key) { | |
1847 | (i, true) => { min_found = true; i+1 }, | |
1848 | (i, false) => i, | |
1849 | }, | |
1850 | (_, Unbounded) => 0, | |
1851 | (true, Included(_)) => min_node.keys().len(), | |
1852 | (true, Excluded(_)) => 0, | |
1853 | }; | |
1854 | ||
1855 | let max_edge = match (max_found, range.end()) { | |
1856 | (false, Included(key)) => match search::search_linear(&max_node, key) { | |
1857 | (i, true) => { max_found = true; i+1 }, | |
1858 | (i, false) => i, | |
1859 | }, | |
1860 | (false, Excluded(key)) => match search::search_linear(&max_node, key) { | |
1861 | (i, true) => { max_found = true; i }, | |
1862 | (i, false) => i, | |
1863 | }, | |
1864 | (_, Unbounded) => max_node.keys().len(), | |
1865 | (true, Included(_)) => 0, | |
1866 | (true, Excluded(_)) => max_node.keys().len(), | |
1867 | }; | |
1868 | ||
1869 | if !diverged { | |
1870 | if max_edge < min_edge { panic!("Ord is ill-defined in BTreeMap range") } | |
1871 | if min_edge != max_edge { diverged = true; } | |
1872 | } | |
1873 | ||
1874 | let front = Handle::new_edge(min_node, min_edge); | |
1875 | let back = Handle::new_edge(max_node, max_edge); | |
1876 | match (front.force(), back.force()) { | |
1877 | (Leaf(f), Leaf(b)) => { | |
1878 | return (f, b); | |
1879 | }, | |
1880 | (Internal(min_int), Internal(max_int)) => { | |
1881 | min_node = min_int.descend(); | |
1882 | max_node = max_int.descend(); | |
1883 | }, | |
1884 | _ => unreachable!("BTreeMap has different depths"), | |
1885 | }; | |
1886 | } | |
1887 | } | |
1888 | ||
9cc50fc6 SL |
1889 | #[inline(always)] |
1890 | unsafe fn unwrap_unchecked<T>(val: Option<T>) -> T { | |
1891 | val.unwrap_or_else(|| { | |
1892 | if cfg!(debug_assertions) { | |
1893 | panic!("'unchecked' unwrap on None in BTreeMap"); | |
1894 | } else { | |
1895 | intrinsics::unreachable(); | |
1896 | } | |
1897 | }) | |
1898 | } | |
1899 | ||
1a4d82fc | 1900 | impl<K, V> BTreeMap<K, V> { |
7453a54e | 1901 | /// Gets an iterator over the entries of the map, sorted by key. |
1a4d82fc | 1902 | /// |
c34b1796 | 1903 | /// # Examples |
1a4d82fc | 1904 | /// |
54a0048b SL |
1905 | /// Basic usage: |
1906 | /// | |
1a4d82fc JJ |
1907 | /// ``` |
1908 | /// use std::collections::BTreeMap; | |
1909 | /// | |
1910 | /// let mut map = BTreeMap::new(); | |
85aaf69f | 1911 | /// map.insert(3, "c"); |
7453a54e SL |
1912 | /// map.insert(2, "b"); |
1913 | /// map.insert(1, "a"); | |
1a4d82fc JJ |
1914 | /// |
1915 | /// for (key, value) in map.iter() { | |
1916 | /// println!("{}: {}", key, value); | |
1917 | /// } | |
1918 | /// | |
1919 | /// let (first_key, first_value) = map.iter().next().unwrap(); | |
85aaf69f | 1920 | /// assert_eq!((*first_key, *first_value), (1, "a")); |
1a4d82fc | 1921 | /// ``` |
85aaf69f | 1922 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc | 1923 | pub fn iter(&self) -> Iter<K, V> { |
1a4d82fc | 1924 | Iter { |
9cc50fc6 SL |
1925 | range: Range { |
1926 | front: first_leaf_edge(self.root.as_ref()), | |
3157f602 | 1927 | back: last_leaf_edge(self.root.as_ref()), |
92a42be0 | 1928 | }, |
3157f602 | 1929 | length: self.length, |
1a4d82fc JJ |
1930 | } |
1931 | } | |
1932 | ||
7453a54e | 1933 | /// Gets a mutable iterator over the entries of the map, sorted by key. |
1a4d82fc JJ |
1934 | /// |
1935 | /// # Examples | |
1936 | /// | |
54a0048b SL |
1937 | /// Basic usage: |
1938 | /// | |
1a4d82fc JJ |
1939 | /// ``` |
1940 | /// use std::collections::BTreeMap; | |
1941 | /// | |
1942 | /// let mut map = BTreeMap::new(); | |
85aaf69f SL |
1943 | /// map.insert("a", 1); |
1944 | /// map.insert("b", 2); | |
1945 | /// map.insert("c", 3); | |
1a4d82fc JJ |
1946 | /// |
1947 | /// // add 10 to the value if the key isn't "a" | |
1948 | /// for (key, value) in map.iter_mut() { | |
1949 | /// if key != &"a" { | |
1950 | /// *value += 10; | |
1951 | /// } | |
1952 | /// } | |
1953 | /// ``` | |
85aaf69f | 1954 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc | 1955 | pub fn iter_mut(&mut self) -> IterMut<K, V> { |
9cc50fc6 SL |
1956 | let root1 = self.root.as_mut(); |
1957 | let root2 = unsafe { ptr::read(&root1) }; | |
1a4d82fc | 1958 | IterMut { |
9cc50fc6 SL |
1959 | range: RangeMut { |
1960 | front: first_leaf_edge(root1), | |
1961 | back: last_leaf_edge(root2), | |
1962 | _marker: PhantomData, | |
92a42be0 | 1963 | }, |
3157f602 | 1964 | length: self.length, |
1a4d82fc JJ |
1965 | } |
1966 | } | |
1967 | ||
7453a54e | 1968 | /// Gets an iterator over the keys of the map, in sorted order. |
1a4d82fc JJ |
1969 | /// |
1970 | /// # Examples | |
1971 | /// | |
54a0048b SL |
1972 | /// Basic usage: |
1973 | /// | |
1a4d82fc JJ |
1974 | /// ``` |
1975 | /// use std::collections::BTreeMap; | |
1976 | /// | |
1977 | /// let mut a = BTreeMap::new(); | |
85aaf69f | 1978 | /// a.insert(2, "b"); |
7453a54e | 1979 | /// a.insert(1, "a"); |
1a4d82fc | 1980 | /// |
62682a34 | 1981 | /// let keys: Vec<_> = a.keys().cloned().collect(); |
c34b1796 | 1982 | /// assert_eq!(keys, [1, 2]); |
1a4d82fc | 1983 | /// ``` |
85aaf69f | 1984 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc | 1985 | pub fn keys<'a>(&'a self) -> Keys<'a, K, V> { |
9cc50fc6 | 1986 | Keys { inner: self.iter() } |
1a4d82fc JJ |
1987 | } |
1988 | ||
7453a54e | 1989 | /// Gets an iterator over the values of the map, in order by key. |
1a4d82fc JJ |
1990 | /// |
1991 | /// # Examples | |
1992 | /// | |
54a0048b SL |
1993 | /// Basic usage: |
1994 | /// | |
1a4d82fc JJ |
1995 | /// ``` |
1996 | /// use std::collections::BTreeMap; | |
1997 | /// | |
1998 | /// let mut a = BTreeMap::new(); | |
7453a54e SL |
1999 | /// a.insert(1, "hello"); |
2000 | /// a.insert(2, "goodbye"); | |
1a4d82fc JJ |
2001 | /// |
2002 | /// let values: Vec<&str> = a.values().cloned().collect(); | |
7453a54e | 2003 | /// assert_eq!(values, ["hello", "goodbye"]); |
1a4d82fc | 2004 | /// ``` |
85aaf69f | 2005 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc | 2006 | pub fn values<'a>(&'a self) -> Values<'a, K, V> { |
9cc50fc6 | 2007 | Values { inner: self.iter() } |
1a4d82fc JJ |
2008 | } |
2009 | ||
54a0048b SL |
2010 | /// Gets a mutable iterator over the values of the map, in order by key. |
2011 | /// | |
2012 | /// # Examples | |
2013 | /// | |
2014 | /// Basic usage: | |
2015 | /// | |
2016 | /// ``` | |
54a0048b SL |
2017 | /// use std::collections::BTreeMap; |
2018 | /// | |
2019 | /// let mut a = BTreeMap::new(); | |
2020 | /// a.insert(1, String::from("hello")); | |
2021 | /// a.insert(2, String::from("goodbye")); | |
2022 | /// | |
2023 | /// for value in a.values_mut() { | |
2024 | /// value.push_str("!"); | |
2025 | /// } | |
2026 | /// | |
2027 | /// let values: Vec<String> = a.values().cloned().collect(); | |
2028 | /// assert_eq!(values, [String::from("hello!"), | |
2029 | /// String::from("goodbye!")]); | |
2030 | /// ``` | |
a7813a04 XL |
2031 | #[stable(feature = "map_values_mut", since = "1.10.0")] |
2032 | pub fn values_mut(&mut self) -> ValuesMut<K, V> { | |
54a0048b SL |
2033 | ValuesMut { inner: self.iter_mut() } |
2034 | } | |
2035 | ||
9346a6ac | 2036 | /// Returns the number of elements in the map. |
1a4d82fc JJ |
2037 | /// |
2038 | /// # Examples | |
2039 | /// | |
54a0048b SL |
2040 | /// Basic usage: |
2041 | /// | |
1a4d82fc JJ |
2042 | /// ``` |
2043 | /// use std::collections::BTreeMap; | |
2044 | /// | |
2045 | /// let mut a = BTreeMap::new(); | |
2046 | /// assert_eq!(a.len(), 0); | |
85aaf69f | 2047 | /// a.insert(1, "a"); |
1a4d82fc JJ |
2048 | /// assert_eq!(a.len(), 1); |
2049 | /// ``` | |
85aaf69f | 2050 | #[stable(feature = "rust1", since = "1.0.0")] |
92a42be0 SL |
2051 | pub fn len(&self) -> usize { |
2052 | self.length | |
2053 | } | |
1a4d82fc | 2054 | |
cc61c64b | 2055 | /// Returns `true` if the map contains no elements. |
1a4d82fc JJ |
2056 | /// |
2057 | /// # Examples | |
2058 | /// | |
54a0048b SL |
2059 | /// Basic usage: |
2060 | /// | |
1a4d82fc JJ |
2061 | /// ``` |
2062 | /// use std::collections::BTreeMap; | |
2063 | /// | |
2064 | /// let mut a = BTreeMap::new(); | |
2065 | /// assert!(a.is_empty()); | |
85aaf69f | 2066 | /// a.insert(1, "a"); |
1a4d82fc JJ |
2067 | /// assert!(!a.is_empty()); |
2068 | /// ``` | |
85aaf69f | 2069 | #[stable(feature = "rust1", since = "1.0.0")] |
92a42be0 SL |
2070 | pub fn is_empty(&self) -> bool { |
2071 | self.len() == 0 | |
2072 | } | |
1a4d82fc JJ |
2073 | } |
2074 | ||
9cc50fc6 SL |
2075 | impl<'a, K: Ord, V> Entry<'a, K, V> { |
2076 | /// Ensures a value is in the entry by inserting the default if empty, and returns | |
2077 | /// a mutable reference to the value in the entry. | |
5bcae85e SL |
2078 | /// |
2079 | /// # Examples | |
2080 | /// | |
2081 | /// ``` | |
2082 | /// use std::collections::BTreeMap; | |
2083 | /// | |
2084 | /// let mut map: BTreeMap<&str, usize> = BTreeMap::new(); | |
2085 | /// map.entry("poneyland").or_insert(12); | |
2086 | /// | |
2087 | /// assert_eq!(map["poneyland"], 12); | |
2088 | /// ``` | |
9cc50fc6 SL |
2089 | #[stable(feature = "rust1", since = "1.0.0")] |
2090 | pub fn or_insert(self, default: V) -> &'a mut V { | |
2091 | match self { | |
2092 | Occupied(entry) => entry.into_mut(), | |
2093 | Vacant(entry) => entry.insert(default), | |
2094 | } | |
2095 | } | |
85aaf69f | 2096 | |
9cc50fc6 SL |
2097 | /// Ensures a value is in the entry by inserting the result of the default function if empty, |
2098 | /// and returns a mutable reference to the value in the entry. | |
5bcae85e SL |
2099 | /// |
2100 | /// # Examples | |
2101 | /// | |
2102 | /// ``` | |
2103 | /// use std::collections::BTreeMap; | |
2104 | /// | |
2105 | /// let mut map: BTreeMap<&str, String> = BTreeMap::new(); | |
32a655c1 | 2106 | /// let s = "hoho".to_string(); |
5bcae85e SL |
2107 | /// |
2108 | /// map.entry("poneyland").or_insert_with(|| s); | |
2109 | /// | |
32a655c1 | 2110 | /// assert_eq!(map["poneyland"], "hoho".to_string()); |
5bcae85e | 2111 | /// ``` |
9cc50fc6 SL |
2112 | #[stable(feature = "rust1", since = "1.0.0")] |
2113 | pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V { | |
2114 | match self { | |
2115 | Occupied(entry) => entry.into_mut(), | |
2116 | Vacant(entry) => entry.insert(default()), | |
2117 | } | |
2118 | } | |
a7813a04 XL |
2119 | |
2120 | /// Returns a reference to this entry's key. | |
5bcae85e SL |
2121 | /// |
2122 | /// # Examples | |
2123 | /// | |
2124 | /// ``` | |
2125 | /// use std::collections::BTreeMap; | |
2126 | /// | |
2127 | /// let mut map: BTreeMap<&str, usize> = BTreeMap::new(); | |
2128 | /// assert_eq!(map.entry("poneyland").key(), &"poneyland"); | |
2129 | /// ``` | |
a7813a04 XL |
2130 | #[stable(feature = "map_entry_keys", since = "1.10.0")] |
2131 | pub fn key(&self) -> &K { | |
2132 | match *self { | |
2133 | Occupied(ref entry) => entry.key(), | |
2134 | Vacant(ref entry) => entry.key(), | |
2135 | } | |
2136 | } | |
ea8adc8c XL |
2137 | |
2138 | /// Provides in-place mutable access to an occupied entry before any | |
2139 | /// potential inserts into the map. | |
2140 | /// | |
2141 | /// # Examples | |
2142 | /// | |
2143 | /// ``` | |
ea8adc8c XL |
2144 | /// use std::collections::BTreeMap; |
2145 | /// | |
2146 | /// let mut map: BTreeMap<&str, usize> = BTreeMap::new(); | |
2147 | /// | |
2148 | /// map.entry("poneyland") | |
2149 | /// .and_modify(|e| { *e += 1 }) | |
2150 | /// .or_insert(42); | |
2151 | /// assert_eq!(map["poneyland"], 42); | |
2152 | /// | |
2153 | /// map.entry("poneyland") | |
2154 | /// .and_modify(|e| { *e += 1 }) | |
2155 | /// .or_insert(42); | |
2156 | /// assert_eq!(map["poneyland"], 43); | |
2157 | /// ``` | |
0531ce1d XL |
2158 | #[stable(feature = "entry_and_modify", since = "1.26.0")] |
2159 | pub fn and_modify<F>(self, f: F) -> Self | |
2160 | where F: FnOnce(&mut V) | |
ea8adc8c XL |
2161 | { |
2162 | match self { | |
2163 | Occupied(mut entry) => { | |
2164 | f(entry.get_mut()); | |
2165 | Occupied(entry) | |
2166 | }, | |
2167 | Vacant(entry) => Vacant(entry), | |
2168 | } | |
2169 | } | |
2170 | } | |
2171 | ||
2172 | impl<'a, K: Ord, V: Default> Entry<'a, K, V> { | |
2173 | #[unstable(feature = "entry_or_default", issue = "44324")] | |
2174 | /// Ensures a value is in the entry by inserting the default value if empty, | |
2175 | /// and returns a mutable reference to the value in the entry. | |
2176 | /// | |
2177 | /// # Examples | |
2178 | /// | |
2179 | /// ``` | |
2180 | /// #![feature(entry_or_default)] | |
2181 | /// # fn main() { | |
2182 | /// use std::collections::BTreeMap; | |
2183 | /// | |
2184 | /// let mut map: BTreeMap<&str, Option<usize>> = BTreeMap::new(); | |
2185 | /// map.entry("poneyland").or_default(); | |
2186 | /// | |
2187 | /// assert_eq!(map["poneyland"], None); | |
2188 | /// # } | |
2189 | /// ``` | |
2190 | pub fn or_default(self) -> &'a mut V { | |
2191 | match self { | |
2192 | Occupied(entry) => entry.into_mut(), | |
2193 | Vacant(entry) => entry.insert(Default::default()), | |
2194 | } | |
2195 | } | |
2196 | ||
9cc50fc6 | 2197 | } |
85aaf69f | 2198 | |
9cc50fc6 | 2199 | impl<'a, K: Ord, V> VacantEntry<'a, K, V> { |
54a0048b SL |
2200 | /// Gets a reference to the key that would be used when inserting a value |
2201 | /// through the VacantEntry. | |
5bcae85e SL |
2202 | /// |
2203 | /// # Examples | |
2204 | /// | |
2205 | /// ``` | |
2206 | /// use std::collections::BTreeMap; | |
2207 | /// | |
2208 | /// let mut map: BTreeMap<&str, usize> = BTreeMap::new(); | |
2209 | /// assert_eq!(map.entry("poneyland").key(), &"poneyland"); | |
2210 | /// ``` | |
a7813a04 | 2211 | #[stable(feature = "map_entry_keys", since = "1.10.0")] |
54a0048b SL |
2212 | pub fn key(&self) -> &K { |
2213 | &self.key | |
2214 | } | |
2215 | ||
3157f602 | 2216 | /// Take ownership of the key. |
5bcae85e SL |
2217 | /// |
2218 | /// # Examples | |
2219 | /// | |
2220 | /// ``` | |
2221 | /// use std::collections::BTreeMap; | |
2222 | /// use std::collections::btree_map::Entry; | |
2223 | /// | |
2224 | /// let mut map: BTreeMap<&str, usize> = BTreeMap::new(); | |
2225 | /// | |
2226 | /// if let Entry::Vacant(v) = map.entry("poneyland") { | |
2227 | /// v.into_key(); | |
2228 | /// } | |
2229 | /// ``` | |
2230 | #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")] | |
3157f602 XL |
2231 | pub fn into_key(self) -> K { |
2232 | self.key | |
2233 | } | |
2234 | ||
9e0c209e | 2235 | /// Sets the value of the entry with the `VacantEntry`'s key, |
9cc50fc6 | 2236 | /// and returns a mutable reference to it. |
5bcae85e SL |
2237 | /// |
2238 | /// # Examples | |
2239 | /// | |
2240 | /// ``` | |
2241 | /// use std::collections::BTreeMap; | |
2242 | /// | |
2243 | /// let mut count: BTreeMap<&str, usize> = BTreeMap::new(); | |
2244 | /// | |
2245 | /// // count the number of occurrences of letters in the vec | |
2246 | /// for x in vec!["a","b","a","c","a","b"] { | |
2247 | /// *count.entry(x).or_insert(0) += 1; | |
2248 | /// } | |
2249 | /// | |
2250 | /// assert_eq!(count["a"], 3); | |
2251 | /// ``` | |
9cc50fc6 SL |
2252 | #[stable(feature = "rust1", since = "1.0.0")] |
2253 | pub fn insert(self, value: V) -> &'a mut V { | |
2254 | *self.length += 1; | |
2255 | ||
2256 | let out_ptr; | |
2257 | ||
2258 | let mut ins_k; | |
2259 | let mut ins_v; | |
2260 | let mut ins_edge; | |
2261 | ||
2262 | let mut cur_parent = match self.handle.insert(self.key, value) { | |
2263 | (Fit(handle), _) => return handle.into_kv_mut().1, | |
2264 | (Split(left, k, v, right), ptr) => { | |
2265 | ins_k = k; | |
2266 | ins_v = v; | |
2267 | ins_edge = right; | |
2268 | out_ptr = ptr; | |
2269 | left.ascend().map_err(|n| n.into_root_mut()) | |
85aaf69f | 2270 | } |
9cc50fc6 | 2271 | }; |
85aaf69f | 2272 | |
9cc50fc6 SL |
2273 | loop { |
2274 | match cur_parent { | |
3157f602 XL |
2275 | Ok(parent) => { |
2276 | match parent.insert(ins_k, ins_v, ins_edge) { | |
2277 | Fit(_) => return unsafe { &mut *out_ptr }, | |
2278 | Split(left, k, v, right) => { | |
2279 | ins_k = k; | |
2280 | ins_v = v; | |
2281 | ins_edge = right; | |
2282 | cur_parent = left.ascend().map_err(|n| n.into_root_mut()); | |
2283 | } | |
9cc50fc6 | 2284 | } |
3157f602 | 2285 | } |
9cc50fc6 SL |
2286 | Err(root) => { |
2287 | root.push_level().push(ins_k, ins_v, ins_edge); | |
2288 | return unsafe { &mut *out_ptr }; | |
85aaf69f SL |
2289 | } |
2290 | } | |
2291 | } | |
9cc50fc6 | 2292 | } |
85aaf69f SL |
2293 | } |
2294 | ||
9cc50fc6 | 2295 | impl<'a, K: Ord, V> OccupiedEntry<'a, K, V> { |
54a0048b | 2296 | /// Gets a reference to the key in the entry. |
5bcae85e SL |
2297 | /// |
2298 | /// # Examples | |
2299 | /// | |
2300 | /// ``` | |
2301 | /// use std::collections::BTreeMap; | |
2302 | /// | |
2303 | /// let mut map: BTreeMap<&str, usize> = BTreeMap::new(); | |
2304 | /// map.entry("poneyland").or_insert(12); | |
2305 | /// assert_eq!(map.entry("poneyland").key(), &"poneyland"); | |
2306 | /// ``` | |
a7813a04 | 2307 | #[stable(feature = "map_entry_keys", since = "1.10.0")] |
54a0048b SL |
2308 | pub fn key(&self) -> &K { |
2309 | self.handle.reborrow().into_kv().0 | |
2310 | } | |
2311 | ||
5bcae85e SL |
2312 | /// Take ownership of the key and value from the map. |
2313 | /// | |
2314 | /// # Examples | |
2315 | /// | |
2316 | /// ``` | |
2317 | /// use std::collections::BTreeMap; | |
2318 | /// use std::collections::btree_map::Entry; | |
2319 | /// | |
2320 | /// let mut map: BTreeMap<&str, usize> = BTreeMap::new(); | |
2321 | /// map.entry("poneyland").or_insert(12); | |
2322 | /// | |
2323 | /// if let Entry::Occupied(o) = map.entry("poneyland") { | |
2324 | /// // We delete the entry from the map. | |
2325 | /// o.remove_entry(); | |
2326 | /// } | |
2327 | /// | |
2328 | /// // If now try to get the value, it will panic: | |
2329 | /// // println!("{}", map["poneyland"]); | |
2330 | /// ``` | |
2331 | #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")] | |
2332 | pub fn remove_entry(self) -> (K, V) { | |
3157f602 XL |
2333 | self.remove_kv() |
2334 | } | |
2335 | ||
9cc50fc6 | 2336 | /// Gets a reference to the value in the entry. |
5bcae85e SL |
2337 | /// |
2338 | /// # Examples | |
2339 | /// | |
2340 | /// ``` | |
2341 | /// use std::collections::BTreeMap; | |
2342 | /// use std::collections::btree_map::Entry; | |
2343 | /// | |
2344 | /// let mut map: BTreeMap<&str, usize> = BTreeMap::new(); | |
2345 | /// map.entry("poneyland").or_insert(12); | |
2346 | /// | |
2347 | /// if let Entry::Occupied(o) = map.entry("poneyland") { | |
2348 | /// assert_eq!(o.get(), &12); | |
2349 | /// } | |
2350 | /// ``` | |
9cc50fc6 SL |
2351 | #[stable(feature = "rust1", since = "1.0.0")] |
2352 | pub fn get(&self) -> &V { | |
2353 | self.handle.reborrow().into_kv().1 | |
85aaf69f SL |
2354 | } |
2355 | ||
9cc50fc6 | 2356 | /// Gets a mutable reference to the value in the entry. |
5bcae85e SL |
2357 | /// |
2358 | /// # Examples | |
2359 | /// | |
2360 | /// ``` | |
2361 | /// use std::collections::BTreeMap; | |
2362 | /// use std::collections::btree_map::Entry; | |
2363 | /// | |
2364 | /// let mut map: BTreeMap<&str, usize> = BTreeMap::new(); | |
2365 | /// map.entry("poneyland").or_insert(12); | |
2366 | /// | |
2367 | /// assert_eq!(map["poneyland"], 12); | |
2368 | /// if let Entry::Occupied(mut o) = map.entry("poneyland") { | |
2369 | /// *o.get_mut() += 10; | |
2370 | /// } | |
2371 | /// assert_eq!(map["poneyland"], 22); | |
2372 | /// ``` | |
9cc50fc6 SL |
2373 | #[stable(feature = "rust1", since = "1.0.0")] |
2374 | pub fn get_mut(&mut self) -> &mut V { | |
2375 | self.handle.kv_mut().1 | |
85aaf69f SL |
2376 | } |
2377 | ||
9cc50fc6 | 2378 | /// Converts the entry into a mutable reference to its value. |
5bcae85e SL |
2379 | /// |
2380 | /// # Examples | |
2381 | /// | |
2382 | /// ``` | |
2383 | /// use std::collections::BTreeMap; | |
2384 | /// use std::collections::btree_map::Entry; | |
2385 | /// | |
2386 | /// let mut map: BTreeMap<&str, usize> = BTreeMap::new(); | |
2387 | /// map.entry("poneyland").or_insert(12); | |
2388 | /// | |
2389 | /// assert_eq!(map["poneyland"], 12); | |
2390 | /// if let Entry::Occupied(o) = map.entry("poneyland") { | |
2391 | /// *o.into_mut() += 10; | |
2392 | /// } | |
2393 | /// assert_eq!(map["poneyland"], 22); | |
2394 | /// ``` | |
85aaf69f | 2395 | #[stable(feature = "rust1", since = "1.0.0")] |
9cc50fc6 SL |
2396 | pub fn into_mut(self) -> &'a mut V { |
2397 | self.handle.into_kv_mut().1 | |
1a4d82fc | 2398 | } |
e9174d1e | 2399 | |
9e0c209e | 2400 | /// Sets the value of the entry with the `OccupiedEntry`'s key, |
9cc50fc6 | 2401 | /// and returns the entry's old value. |
5bcae85e SL |
2402 | /// |
2403 | /// # Examples | |
2404 | /// | |
2405 | /// ``` | |
2406 | /// use std::collections::BTreeMap; | |
2407 | /// use std::collections::btree_map::Entry; | |
2408 | /// | |
2409 | /// let mut map: BTreeMap<&str, usize> = BTreeMap::new(); | |
2410 | /// map.entry("poneyland").or_insert(12); | |
2411 | /// | |
2412 | /// if let Entry::Occupied(mut o) = map.entry("poneyland") { | |
2413 | /// assert_eq!(o.insert(15), 12); | |
2414 | /// } | |
2415 | /// assert_eq!(map["poneyland"], 15); | |
2416 | /// ``` | |
9cc50fc6 SL |
2417 | #[stable(feature = "rust1", since = "1.0.0")] |
2418 | pub fn insert(&mut self, value: V) -> V { | |
2419 | mem::replace(self.get_mut(), value) | |
2420 | } | |
e9174d1e | 2421 | |
9cc50fc6 | 2422 | /// Takes the value of the entry out of the map, and returns it. |
5bcae85e SL |
2423 | /// |
2424 | /// # Examples | |
2425 | /// | |
2426 | /// ``` | |
2427 | /// use std::collections::BTreeMap; | |
2428 | /// use std::collections::btree_map::Entry; | |
2429 | /// | |
2430 | /// let mut map: BTreeMap<&str, usize> = BTreeMap::new(); | |
2431 | /// map.entry("poneyland").or_insert(12); | |
2432 | /// | |
2433 | /// if let Entry::Occupied(o) = map.entry("poneyland") { | |
2434 | /// assert_eq!(o.remove(), 12); | |
2435 | /// } | |
2436 | /// // If we try to get "poneyland"'s value, it'll panic: | |
2437 | /// // println!("{}", map["poneyland"]); | |
2438 | /// ``` | |
9cc50fc6 SL |
2439 | #[stable(feature = "rust1", since = "1.0.0")] |
2440 | pub fn remove(self) -> V { | |
2441 | self.remove_kv().1 | |
e9174d1e SL |
2442 | } |
2443 | ||
9cc50fc6 SL |
2444 | fn remove_kv(self) -> (K, V) { |
2445 | *self.length -= 1; | |
e9174d1e | 2446 | |
9cc50fc6 SL |
2447 | let (small_leaf, old_key, old_val) = match self.handle.force() { |
2448 | Leaf(leaf) => { | |
2449 | let (hole, old_key, old_val) = leaf.remove(); | |
2450 | (hole.into_node(), old_key, old_val) | |
3157f602 | 2451 | } |
9cc50fc6 SL |
2452 | Internal(mut internal) => { |
2453 | let key_loc = internal.kv_mut().0 as *mut K; | |
2454 | let val_loc = internal.kv_mut().1 as *mut V; | |
2455 | ||
2456 | let to_remove = first_leaf_edge(internal.right_edge().descend()).right_kv().ok(); | |
2457 | let to_remove = unsafe { unwrap_unchecked(to_remove) }; | |
2458 | ||
2459 | let (hole, key, val) = to_remove.remove(); | |
2460 | ||
3157f602 XL |
2461 | let old_key = unsafe { mem::replace(&mut *key_loc, key) }; |
2462 | let old_val = unsafe { mem::replace(&mut *val_loc, val) }; | |
9cc50fc6 SL |
2463 | |
2464 | (hole.into_node(), old_key, old_val) | |
2465 | } | |
2466 | }; | |
2467 | ||
2468 | // Handle underflow | |
2469 | let mut cur_node = small_leaf.forget_type(); | |
2470 | while cur_node.len() < node::CAPACITY / 2 { | |
2471 | match handle_underfull_node(cur_node) { | |
2472 | AtRoot => break, | |
2473 | EmptyParent(_) => unreachable!(), | |
3157f602 XL |
2474 | Merged(parent) => { |
2475 | if parent.len() == 0 { | |
2476 | // We must be at the root | |
2477 | parent.into_root_mut().pop_level(); | |
2478 | break; | |
2479 | } else { | |
2480 | cur_node = parent.forget_type(); | |
2481 | } | |
2482 | } | |
2483 | Stole(_) => break, | |
e9174d1e SL |
2484 | } |
2485 | } | |
9cc50fc6 SL |
2486 | |
2487 | (old_key, old_val) | |
e9174d1e | 2488 | } |
9cc50fc6 | 2489 | } |
e9174d1e | 2490 | |
9cc50fc6 SL |
2491 | enum UnderflowResult<'a, K, V> { |
2492 | AtRoot, | |
2493 | EmptyParent(NodeRef<marker::Mut<'a>, K, V, marker::Internal>), | |
2494 | Merged(NodeRef<marker::Mut<'a>, K, V, marker::Internal>), | |
3157f602 | 2495 | Stole(NodeRef<marker::Mut<'a>, K, V, marker::Internal>), |
9cc50fc6 SL |
2496 | } |
2497 | ||
3157f602 XL |
2498 | fn handle_underfull_node<'a, K, V>(node: NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal>) |
2499 | -> UnderflowResult<'a, K, V> { | |
9cc50fc6 SL |
2500 | let parent = if let Ok(parent) = node.ascend() { |
2501 | parent | |
2502 | } else { | |
2503 | return AtRoot; | |
2504 | }; | |
2505 | ||
2506 | let (is_left, mut handle) = match parent.left_kv() { | |
2507 | Ok(left) => (true, left), | |
3157f602 XL |
2508 | Err(parent) => { |
2509 | match parent.right_kv() { | |
2510 | Ok(right) => (false, right), | |
2511 | Err(parent) => { | |
2512 | return EmptyParent(parent.into_node()); | |
2513 | } | |
9cc50fc6 SL |
2514 | } |
2515 | } | |
2516 | }; | |
2517 | ||
2518 | if handle.can_merge() { | |
a7813a04 | 2519 | Merged(handle.merge().into_node()) |
9cc50fc6 | 2520 | } else { |
a7813a04 XL |
2521 | if is_left { |
2522 | handle.steal_left(); | |
2523 | } else { | |
2524 | handle.steal_right(); | |
2525 | } | |
2526 | Stole(handle.into_node()) | |
2527 | } | |
2528 | } | |
e9174d1e | 2529 | |
3157f602 | 2530 | impl<K: Ord, V, I: Iterator<Item = (K, V)>> Iterator for MergeIter<K, V, I> { |
a7813a04 | 2531 | type Item = (K, V); |
e9174d1e | 2532 | |
a7813a04 XL |
2533 | fn next(&mut self) -> Option<(K, V)> { |
2534 | let res = match (self.left.peek(), self.right.peek()) { | |
2535 | (Some(&(ref left_key, _)), Some(&(ref right_key, _))) => left_key.cmp(right_key), | |
2536 | (Some(_), None) => Ordering::Less, | |
2537 | (None, Some(_)) => Ordering::Greater, | |
2538 | (None, None) => return None, | |
2539 | }; | |
9cc50fc6 | 2540 | |
a7813a04 XL |
2541 | // Check which elements comes first and only advance the corresponding iterator. |
2542 | // If two keys are equal, take the value from `right`. | |
2543 | match res { | |
3157f602 XL |
2544 | Ordering::Less => self.left.next(), |
2545 | Ordering::Greater => self.right.next(), | |
a7813a04 XL |
2546 | Ordering::Equal => { |
2547 | self.left.next(); | |
2548 | self.right.next() | |
3157f602 | 2549 | } |
a7813a04 | 2550 | } |
e9174d1e SL |
2551 | } |
2552 | } |