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