Debian Codegraph @

debian/missing-sources/fallible_collections/src/btree/map.rs

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