copse/liballoc/collections/btree/map.rs
1use alloc::vec::Vec;
2use cfg_if::cfg_if;
3use core::cmp::Ordering;
4use core::fmt::{self, Debug};
5use core::hash::{Hash, Hasher};
6use core::iter::{FromIterator, FusedIterator};
7use core::marker::PhantomData;
8use core::mem::{self, ManuallyDrop};
9use core::ops::{Bound, Index, RangeBounds};
10use core::ptr;
11
12use crate::{
13 default::{OrdStoredKey, OrdTotalOrder},
14 polyfill::*,
15 SortableBy, TotalOrder,
16};
17
18use super::borrow::DormantMutRef;
19use super::dedup_sorted_iter::DedupSortedIter;
20use super::navigate::{LazyLeafRange, LeafRange};
21use super::node::{self, marker, ForceResult::*, Handle, NodeRef, Root};
22use super::search::{SearchBound, SearchResult::*};
23use super::set_val::SetValZST;
24
25mod entry;
26
27#[cfg(feature = "map_try_insert")]
28pub use entry::OccupiedError;
29pub use entry::{Entry, OccupiedEntry, VacantEntry};
30
31use Entry::*;
32
33/// Minimum number of elements in a node that is not a root.
34/// We might temporarily have fewer elements during methods.
35pub(super) const MIN_LEN: usize = node::MIN_LEN_AFTER_SPLIT;
36
37// A tree in a `BTreeMap` is a tree in the `node` module with additional invariants:
38// - Keys must appear in ascending order (according to the key's type).
39// - Every non-leaf node contains at least 1 element (has at least 2 children).
40// - Every non-root node contains at least MIN_LEN elements.
41//
42// An empty map is represented either by the absence of a root node or by a
43// root node that is an empty leaf.
44
45/// An ordered map based on a [B-Tree].
46///
47/// B-Trees represent a fundamental compromise between cache-efficiency and actually minimizing
48/// the amount of work performed in a search. In theory, a binary search tree (BST) is the optimal
49/// choice for a sorted map, as a perfectly balanced BST performs the theoretical minimum amount of
50/// comparisons necessary to find an element (log<sub>2</sub>n). However, in practice the way this
51/// is done is *very* inefficient for modern computer architectures. In particular, every element
52/// is stored in its own individually heap-allocated node. This means that every single insertion
53/// triggers a heap-allocation, and every single comparison should be a cache-miss. Since these
54/// are both notably expensive things to do in practice, we are forced to, at the very least,
55/// reconsider the BST strategy.
56///
57/// A B-Tree instead makes each node contain B-1 to 2B-1 elements in a contiguous array. By doing
58/// this, we reduce the number of allocations by a factor of B, and improve cache efficiency in
59/// searches. However, this does mean that searches will have to do *more* comparisons on average.
60/// The precise number of comparisons depends on the node search strategy used. For optimal cache
61/// efficiency, one could search the nodes linearly. For optimal comparisons, one could search
62/// the node using binary search. As a compromise, one could also perform a linear search
63/// that initially only checks every i<sup>th</sup> element for some choice of i.
64///
65/// Currently, our implementation simply performs naive linear search. This provides excellent
66/// performance on *small* nodes of elements which are cheap to compare. However in the future we
67/// would like to further explore choosing the optimal search strategy based on the choice of B,
68/// and possibly other factors. Using linear search, searching for a random element is expected
69/// to take B * log(n) comparisons, which is generally worse than a BST. In practice,
70/// however, performance is excellent.
71///
72/// It is a logic error for a key or total order to be modified in such a way that the key's
73/// ordering relative to any other key, as determined by that total order, changes while they are
74/// in the map. This is normally only possible through [`Cell`], [`RefCell`], global state, I/O,
75/// or unsafe code. The behavior resulting from such a logic error is not specified, but will be
76/// encapsulated to the `BTreeMap` that observed the logic error and not result in undefined
77/// behavior. This could include panics, incorrect results, aborts, memory leaks, and
78/// non-termination.
79///
80/// Iterators obtained from functions such as [`BTreeMap::iter`], [`BTreeMap::values`], or
81/// [`BTreeMap::keys`] produce their items in order by key, and take worst-case logarithmic and
82/// amortized constant time per item returned.
83///
84/// [B-Tree]: https://en.wikipedia.org/wiki/B-tree
85/// [`Cell`]: core::cell::Cell
86/// [`RefCell`]: core::cell::RefCell
87///
88/// # Examples
89///
90/// ```
91/// use copse::BTreeMap;
92///
93/// // type inference lets us omit an explicit type signature (which
94/// // would be `BTreeMap<&str, &str>` in this example).
95/// let mut movie_reviews = BTreeMap::default();
96///
97/// // review some movies.
98/// movie_reviews.insert("Office Space", "Deals with real issues in the workplace.");
99/// movie_reviews.insert("Pulp Fiction", "Masterpiece.");
100/// movie_reviews.insert("The Godfather", "Very enjoyable.");
101/// movie_reviews.insert("The Blues Brothers", "Eye lyked it a lot.");
102///
103/// // check for a specific one.
104/// if !movie_reviews.contains_key("Les Misérables") {
105/// println!("We've got {} reviews, but Les Misérables ain't one.",
106/// movie_reviews.len());
107/// }
108///
109/// // oops, this review has a lot of spelling mistakes, let's delete it.
110/// movie_reviews.remove("The Blues Brothers");
111///
112/// // look up the values associated with some keys.
113/// let to_find = ["Up!", "Office Space"];
114/// for movie in &to_find {
115/// match movie_reviews.get(movie) {
116/// Some(review) => println!("{movie}: {review}"),
117/// None => println!("{movie} is unreviewed.")
118/// }
119/// }
120///
121/// // Look up the value for a key (will panic if the key is not found).
122/// println!("Movie review: {}", movie_reviews["Office Space"]);
123///
124/// // iterate over everything.
125/// for (movie, review) in &movie_reviews {
126/// println!("{movie}: \"{review}\"");
127/// }
128/// ```
129///
130/// A `BTreeMap` with a known list of items can be initialized from an array:
131///
132/// ```
133/// use copse::BTreeMap;
134///
135/// let solar_distance = BTreeMap::<_, _>::from([
136/// ("Mercury", 0.4),
137/// ("Venus", 0.7),
138/// ("Earth", 1.0),
139/// ("Mars", 1.5),
140/// ]);
141/// ```
142///
143/// `BTreeMap` implements an [`Entry API`], which allows for complex
144/// methods of getting, setting, updating and removing keys and their values:
145///
146/// [`Entry API`]: BTreeMap::entry
147///
148/// ```
149/// use copse::BTreeMap;
150///
151/// // type inference lets us omit an explicit type signature (which
152/// // would be `BTreeMap<&str, u8>` in this example).
153/// let mut player_stats = BTreeMap::<_, _>::default();
154///
155/// fn random_stat_buff() -> u8 {
156/// // could actually return some random value here - let's just return
157/// // some fixed value for now
158/// 42
159/// }
160///
161/// // insert a key only if it doesn't already exist
162/// player_stats.entry("health").or_insert(100);
163///
164/// // insert a key using a function that provides a new value only if it
165/// // doesn't already exist
166/// player_stats.entry("defence").or_insert_with(random_stat_buff);
167///
168/// // update a key, guarding against the key possibly not being set
169/// let stat = player_stats.entry("attack").or_insert(100);
170/// *stat += random_stat_buff();
171///
172/// // modify an entry before an insert with in-place mutation
173/// player_stats.entry("mana").and_modify(|mana| *mana += 200).or_insert(100);
174/// ```
175#[cfg_attr(feature = "rustc_attrs", rustc_insignificant_dtor)]
176pub struct BTreeMap<
177 K,
178 V,
179 O = OrdTotalOrder<<K as OrdStoredKey>::OrdKeyType>,
180 A: Allocator + Clone = Global,
181> {
182 root: Option<Root<K, V>>,
183 length: usize,
184 pub(super) order: O,
185 /// `ManuallyDrop` to control drop order (needs to be dropped after all the nodes).
186 pub(super) alloc: ManuallyDrop<A>,
187 // For dropck; the `Box` avoids making the `Unpin` impl more strict than before
188 _marker: PhantomData<alloc::boxed::Box<(K, V)>>,
189}
190
191cfg_if! {
192 if #[cfg(feature = "dropck_eyepatch")] {
193 unsafe impl<#[may_dangle] K, #[may_dangle] V, O, A: Allocator + Clone> Drop
194 for BTreeMap<K, V, O, A>
195 {
196 fn drop(&mut self) {
197 drop(unsafe { ptr::read(self) }.into_iter())
198 }
199 }
200 } else {
201 impl<K, V, O, A: Allocator + Clone> Drop for BTreeMap<K, V, O, A> {
202 fn drop(&mut self) {
203 drop(unsafe { ptr::read(self) }.into_iter())
204 }
205 }
206 }
207}
208
209// FIXME: This implementation is "wrong", but changing it would be a breaking change.
210// (The bounds of the automatic `UnwindSafe` implementation have been like this since Rust 1.50.)
211// Maybe we can fix it nonetheless with a crater run, or if the `UnwindSafe`
212// traits are deprecated, or disarmed (no longer causing hard errors) in the future.
213impl<K, V, O, A: Allocator + Clone> core::panic::UnwindSafe for BTreeMap<K, V, O, A>
214where
215 A: core::panic::UnwindSafe,
216 K: core::panic::RefUnwindSafe,
217 V: core::panic::RefUnwindSafe,
218{
219}
220
221impl<K: Clone, V: Clone, O: Clone, A: Allocator + Clone> Clone for BTreeMap<K, V, O, A> {
222 fn clone(&self) -> BTreeMap<K, V, O, A> {
223 fn clone_subtree<'a, K: Clone, V: Clone, O: Clone, A: Allocator + Clone>(
224 node: NodeRef<marker::Immut<'a>, K, V, marker::LeafOrInternal>,
225 order: &O,
226 alloc: A,
227 ) -> BTreeMap<K, V, O, A>
228 where
229 K: 'a,
230 V: 'a,
231 {
232 match node.force() {
233 Leaf(leaf) => {
234 let mut out_tree = BTreeMap {
235 root: Some(Root::new(alloc.clone())),
236 length: 0,
237 order: order.clone(),
238 alloc: ManuallyDrop::new(alloc),
239 _marker: PhantomData,
240 };
241
242 {
243 let root = out_tree.root.as_mut().unwrap(); // unwrap succeeds because we just wrapped
244 let mut out_node = match root.borrow_mut().force() {
245 Leaf(leaf) => leaf,
246 Internal(_) => unreachable!(),
247 };
248
249 let mut in_edge = leaf.first_edge();
250 while let Ok(kv) = in_edge.right_kv() {
251 let (k, v) = kv.into_kv();
252 in_edge = kv.right_edge();
253
254 out_node.push(k.clone(), v.clone());
255 out_tree.length += 1;
256 }
257 }
258
259 out_tree
260 }
261 Internal(internal) => {
262 let mut out_tree =
263 clone_subtree(internal.first_edge().descend(), order, alloc.clone());
264
265 {
266 let out_root = out_tree.root.as_mut().unwrap();
267 let mut out_node = out_root.push_internal_level(alloc.clone());
268 let mut in_edge = internal.first_edge();
269 while let Ok(kv) = in_edge.right_kv() {
270 let (k, v) = kv.into_kv();
271 in_edge = kv.right_edge();
272
273 let k = (*k).clone();
274 let v = (*v).clone();
275 let subtree = clone_subtree(in_edge.descend(), order, alloc.clone());
276
277 // We can't destructure subtree directly
278 // because BTreeMap implements Drop
279 let (subroot, sublength) = unsafe {
280 let subtree = ManuallyDrop::new(subtree);
281 let root = ptr::read(&subtree.root);
282 let length = subtree.length;
283 (root, length)
284 };
285
286 out_node.push(
287 k,
288 v,
289 subroot.unwrap_or_else(|| Root::new(alloc.clone())),
290 );
291 out_tree.length += 1 + sublength;
292 }
293 }
294
295 out_tree
296 }
297 }
298 }
299
300 if self.is_empty() {
301 BTreeMap::new_in(self.order.clone(), (*self.alloc).clone())
302 } else {
303 clone_subtree(
304 self.root.as_ref().unwrap().reborrow(),
305 &self.order,
306 (*self.alloc).clone(),
307 ) // unwrap succeeds because not empty
308 }
309 }
310}
311
312impl<K, Q: ?Sized, O, A: Allocator + Clone> super::Recover<Q> for BTreeMap<K, SetValZST, O, A>
313where
314 K: SortableBy<O>,
315 Q: SortableBy<O>,
316 O: TotalOrder,
317{
318 type Key = K;
319
320 fn get(&self, key: &Q) -> Option<&K> {
321 let root_node = self.root.as_ref()?.reborrow();
322 match root_node.search_tree(key, &self.order) {
323 Found(handle) => Some(handle.into_kv().0),
324 GoDown(_) => None,
325 }
326 }
327
328 fn take(&mut self, key: &Q) -> Option<K> {
329 let (map, dormant_map) = DormantMutRef::new(self);
330 let root_node = map.root.as_mut()?.borrow_mut();
331 match root_node.search_tree(key, &map.order) {
332 Found(handle) => Some(
333 OccupiedEntry {
334 handle,
335 dormant_map,
336 alloc: (*map.alloc).clone(),
337 _marker: PhantomData,
338 }
339 .remove_kv()
340 .0,
341 ),
342 GoDown(_) => None,
343 }
344 }
345
346 fn replace(&mut self, key: K) -> Option<K> {
347 let (map, dormant_map) = DormantMutRef::new(self);
348 let root_node =
349 map.root.get_or_insert_with(|| Root::new((*map.alloc).clone())).borrow_mut();
350 match root_node.search_tree(&key, &map.order) {
351 Found(mut kv) => Some(mem::replace(kv.key_mut(), key)),
352 GoDown(handle) => {
353 VacantEntry {
354 key,
355 handle: Some(handle),
356 dormant_map,
357 alloc: (*map.alloc).clone(),
358 _marker: PhantomData,
359 }
360 .insert(SetValZST::default());
361 None
362 }
363 }
364 }
365}
366
367/// An iterator over the entries of a `BTreeMap`.
368///
369/// This `struct` is created by the [`iter`] method on [`BTreeMap`]. See its
370/// documentation for more.
371///
372/// [`iter`]: BTreeMap::iter
373#[must_use = "iterators are lazy and do nothing unless consumed"]
374pub struct Iter<'a, K: 'a, V: 'a> {
375 range: LazyLeafRange<marker::Immut<'a>, K, V>,
376 length: usize,
377}
378
379impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for Iter<'_, K, V> {
380 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
381 f.debug_list().entries(self.clone()).finish()
382 }
383}
384
385/// A mutable iterator over the entries of a `BTreeMap`.
386///
387/// This `struct` is created by the [`iter_mut`] method on [`BTreeMap`]. See its
388/// documentation for more.
389///
390/// [`iter_mut`]: BTreeMap::iter_mut
391pub struct IterMut<'a, K: 'a, V: 'a> {
392 range: LazyLeafRange<marker::ValMut<'a>, K, V>,
393 length: usize,
394
395 // Be invariant in `K` and `V`
396 _marker: PhantomData<&'a mut (K, V)>,
397}
398
399#[must_use = "iterators are lazy and do nothing unless consumed"]
400impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for IterMut<'_, K, V> {
401 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
402 let range = Iter { range: self.range.reborrow(), length: self.length };
403 f.debug_list().entries(range).finish()
404 }
405}
406
407/// An owning iterator over the entries of a `BTreeMap`.
408///
409/// This `struct` is created by the [`into_iter`] method on [`BTreeMap`]
410/// (provided by the [`IntoIterator`] trait). See its documentation for more.
411///
412/// [`into_iter`]: IntoIterator::into_iter
413/// [`IntoIterator`]: core::iter::IntoIterator
414#[cfg_attr(feature = "rustc_attrs", rustc_insignificant_dtor)]
415pub struct IntoIter<K, V, A: Allocator + Clone = Global> {
416 range: LazyLeafRange<marker::Dying, K, V>,
417 length: usize,
418 /// The BTreeMap will outlive this IntoIter so we don't care about drop order for `alloc`.
419 alloc: A,
420}
421
422impl<K, V, A: Allocator + Clone> IntoIter<K, V, A> {
423 /// Returns an iterator of references over the remaining items.
424 #[inline]
425 pub(super) fn iter(&self) -> Iter<'_, K, V> {
426 Iter { range: self.range.reborrow(), length: self.length }
427 }
428}
429
430impl<K: Debug, V: Debug, A: Allocator + Clone> Debug for IntoIter<K, V, A> {
431 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
432 f.debug_list().entries(self.iter()).finish()
433 }
434}
435
436/// An iterator over the keys of a `BTreeMap`.
437///
438/// This `struct` is created by the [`keys`] method on [`BTreeMap`]. See its
439/// documentation for more.
440///
441/// [`keys`]: BTreeMap::keys
442#[must_use = "iterators are lazy and do nothing unless consumed"]
443pub struct Keys<'a, K, V> {
444 inner: Iter<'a, K, V>,
445}
446
447impl<K: fmt::Debug, V> fmt::Debug for Keys<'_, K, V> {
448 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
449 f.debug_list().entries(self.clone()).finish()
450 }
451}
452
453/// An iterator over the values of a `BTreeMap`.
454///
455/// This `struct` is created by the [`values`] method on [`BTreeMap`]. See its
456/// documentation for more.
457///
458/// [`values`]: BTreeMap::values
459#[must_use = "iterators are lazy and do nothing unless consumed"]
460pub struct Values<'a, K, V> {
461 inner: Iter<'a, K, V>,
462}
463
464impl<K, V: fmt::Debug> fmt::Debug for Values<'_, K, V> {
465 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
466 f.debug_list().entries(self.clone()).finish()
467 }
468}
469
470/// A mutable iterator over the values of a `BTreeMap`.
471///
472/// This `struct` is created by the [`values_mut`] method on [`BTreeMap`]. See its
473/// documentation for more.
474///
475/// [`values_mut`]: BTreeMap::values_mut
476#[must_use = "iterators are lazy and do nothing unless consumed"]
477pub struct ValuesMut<'a, K, V> {
478 inner: IterMut<'a, K, V>,
479}
480
481impl<K, V: fmt::Debug> fmt::Debug for ValuesMut<'_, K, V> {
482 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
483 f.debug_list().entries(self.inner.iter().map(|(_, val)| val)).finish()
484 }
485}
486
487/// An owning iterator over the keys of a `BTreeMap`.
488///
489/// This `struct` is created by the [`into_keys`] method on [`BTreeMap`].
490/// See its documentation for more.
491///
492/// [`into_keys`]: BTreeMap::into_keys
493#[must_use = "iterators are lazy and do nothing unless consumed"]
494pub struct IntoKeys<K, V, A: Allocator + Clone = Global> {
495 inner: IntoIter<K, V, A>,
496}
497
498impl<K: fmt::Debug, V, A: Allocator + Clone> fmt::Debug for IntoKeys<K, V, A> {
499 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
500 f.debug_list().entries(self.inner.iter().map(|(key, _)| key)).finish()
501 }
502}
503
504/// An owning iterator over the values of a `BTreeMap`.
505///
506/// This `struct` is created by the [`into_values`] method on [`BTreeMap`].
507/// See its documentation for more.
508///
509/// [`into_values`]: BTreeMap::into_values
510#[must_use = "iterators are lazy and do nothing unless consumed"]
511pub struct IntoValues<K, V, A: Allocator + Clone = Global> {
512 inner: IntoIter<K, V, A>,
513}
514
515impl<K, V: fmt::Debug, A: Allocator + Clone> fmt::Debug for IntoValues<K, V, A> {
516 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
517 f.debug_list().entries(self.inner.iter().map(|(_, val)| val)).finish()
518 }
519}
520
521/// An iterator over a sub-range of entries in a `BTreeMap`.
522///
523/// This `struct` is created by the [`range`] method on [`BTreeMap`]. See its
524/// documentation for more.
525///
526/// [`range`]: BTreeMap::range
527#[must_use = "iterators are lazy and do nothing unless consumed"]
528pub struct Range<'a, K: 'a, V: 'a> {
529 inner: LeafRange<marker::Immut<'a>, K, V>,
530}
531
532impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for Range<'_, K, V> {
533 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
534 f.debug_list().entries(self.clone()).finish()
535 }
536}
537
538/// A mutable iterator over a sub-range of entries in a `BTreeMap`.
539///
540/// This `struct` is created by the [`range_mut`] method on [`BTreeMap`]. See its
541/// documentation for more.
542///
543/// [`range_mut`]: BTreeMap::range_mut
544#[must_use = "iterators are lazy and do nothing unless consumed"]
545pub struct RangeMut<'a, K: 'a, V: 'a> {
546 inner: LeafRange<marker::ValMut<'a>, K, V>,
547
548 // Be invariant in `K` and `V`
549 _marker: PhantomData<&'a mut (K, V)>,
550}
551
552impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for RangeMut<'_, K, V> {
553 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
554 let range = Range { inner: self.inner.reborrow() };
555 f.debug_list().entries(range).finish()
556 }
557}
558
559impl<K, V, O> BTreeMap<K, V, O> {
560 /// Makes a new, empty `BTreeMap` ordered by the given `order`.
561 ///
562 /// Does not allocate anything on its own.
563 ///
564 /// # Examples
565 ///
566 /// Basic usage:
567 ///
568 /// ```
569 /// # use copse::{BTreeMap, SortableBy, TotalOrder};
570 /// # use std::cmp::Ordering;
571 /// #
572 /// // define a total order
573 /// struct OrderByNthByte {
574 /// n: usize, // runtime state
575 /// }
576 ///
577 /// impl TotalOrder for OrderByNthByte {
578 /// // etc
579 /// # type OrderedType = [u8];
580 /// # fn cmp(&self, this: &[u8], that: &[u8]) -> Ordering {
581 /// # this.get(self.n).cmp(&that.get(self.n))
582 /// # }
583 /// }
584 ///
585 /// // define lookup key types for collections sorted by our total order
586 /// # impl SortableBy<OrderByNthByte> for [u8] {
587 /// # fn sort_key(&self) -> &[u8] { self }
588 /// # }
589 /// # impl SortableBy<OrderByNthByte> for str {
590 /// # fn sort_key(&self) -> &[u8] { self.as_bytes() }
591 /// # }
592 /// impl SortableBy<OrderByNthByte> for String {
593 /// // etc
594 /// # fn sort_key(&self) -> &[u8] { SortableBy::<OrderByNthByte>::sort_key(self.as_str()) }
595 /// }
596 ///
597 /// // create a map using our total order
598 /// let mut map = BTreeMap::new(OrderByNthByte { n: 9 });
599 ///
600 /// // entries can now be inserted into the empty map
601 /// assert!(map.insert("abcdefghij".to_string(), ()).is_none());
602 /// ```
603 #[must_use]
604 pub const fn new(order: O) -> BTreeMap<K, V, O> {
605 BTreeMap {
606 root: None,
607 length: 0,
608 order,
609 alloc: ManuallyDrop::new(Global),
610 _marker: PhantomData,
611 }
612 }
613}
614
615impl<K, V, O, A: Allocator + Clone> BTreeMap<K, V, O, A> {
616 /// Clears the map, removing all elements.
617 ///
618 /// # Examples
619 ///
620 /// Basic usage:
621 ///
622 /// ```
623 /// use copse::BTreeMap;
624 ///
625 /// let mut a = BTreeMap::default();
626 /// a.insert(1, "a");
627 /// a.clear();
628 /// assert!(a.is_empty());
629 /// ```
630 pub fn clear(&mut self)
631 where
632 O: Clone,
633 {
634 // avoid moving the allocator
635 mem::drop(BTreeMap {
636 root: mem::replace(&mut self.root, None),
637 length: mem::replace(&mut self.length, 0),
638 order: self.order.clone(),
639 alloc: self.alloc.clone(),
640 _marker: PhantomData,
641 });
642 }
643
644 decorate_if! {
645 if #[cfg(feature = "btreemap_alloc")] {
646 /// Makes a new empty BTreeMap with a reasonable choice for B, ordered by the given `order`.
647 ///
648 /// # Examples
649 ///
650 /// Basic usage:
651 ///
652 /// ```
653 /// # #![feature(allocator_api)]
654 /// use copse::{BTreeMap, default::OrdTotalOrder};
655 /// use std::alloc::Global;
656 ///
657 /// let mut map = BTreeMap::new_in(OrdTotalOrder::default(), Global);
658 ///
659 /// // entries can now be inserted into the empty map
660 /// map.insert(1, "a");
661 /// ```
662 pub
663 }
664 fn new_in(order: O, alloc: A) -> BTreeMap<K, V, O, A> {
665 BTreeMap {
666 root: None,
667 length: 0,
668 order,
669 alloc: ManuallyDrop::new(alloc),
670 _marker: PhantomData,
671 }
672 }
673 }
674}
675
676impl<K, V, O, A: Allocator + Clone> BTreeMap<K, V, O, A> {
677 /// Returns a reference to the value corresponding to the key.
678 ///
679 /// The key may be any borrowed form of the map's key type, but the ordering
680 /// on the borrowed form *must* match the ordering on the key type.
681 ///
682 /// # Examples
683 ///
684 /// Basic usage:
685 ///
686 /// ```
687 /// use copse::BTreeMap;
688 ///
689 /// let mut map = BTreeMap::default();
690 /// map.insert(1, "a");
691 /// assert_eq!(map.get(&1), Some(&"a"));
692 /// assert_eq!(map.get(&2), None);
693 /// ```
694 pub fn get<Q: ?Sized>(&self, key: &Q) -> Option<&V>
695 where
696 K: SortableBy<O>,
697 Q: SortableBy<O>,
698 O: TotalOrder,
699 {
700 let root_node = self.root.as_ref()?.reborrow();
701 match root_node.search_tree(key, &self.order) {
702 Found(handle) => Some(handle.into_kv().1),
703 GoDown(_) => None,
704 }
705 }
706
707 /// Returns the key-value pair corresponding to the supplied key.
708 ///
709 /// The supplied key may be any borrowed form of the map's key type, but the ordering
710 /// on the borrowed form *must* match the ordering on the key type.
711 ///
712 /// # Examples
713 ///
714 /// ```
715 /// use copse::BTreeMap;
716 ///
717 /// let mut map = BTreeMap::default();
718 /// map.insert(1, "a");
719 /// assert_eq!(map.get_key_value(&1), Some((&1, &"a")));
720 /// assert_eq!(map.get_key_value(&2), None);
721 /// ```
722 pub fn get_key_value<Q: ?Sized>(&self, k: &Q) -> Option<(&K, &V)>
723 where
724 K: SortableBy<O>,
725 Q: SortableBy<O>,
726 O: TotalOrder,
727 {
728 let root_node = self.root.as_ref()?.reborrow();
729 match root_node.search_tree(k, &self.order) {
730 Found(handle) => Some(handle.into_kv()),
731 GoDown(_) => None,
732 }
733 }
734
735 /// Returns the first key-value pair in the map.
736 /// The key in this pair is the minimum key in the map.
737 ///
738 /// # Examples
739 ///
740 /// Basic usage:
741 ///
742 /// ```
743 /// use copse::BTreeMap;
744 ///
745 /// let mut map = BTreeMap::default();
746 /// assert_eq!(map.first_key_value(), None);
747 /// map.insert(1, "b");
748 /// map.insert(2, "a");
749 /// assert_eq!(map.first_key_value(), Some((&1, &"b")));
750 /// ```
751 pub fn first_key_value(&self) -> Option<(&K, &V)>
752 where
753 K: SortableBy<O>,
754 O: TotalOrder,
755 {
756 let root_node = self.root.as_ref()?.reborrow();
757 root_node.first_leaf_edge().right_kv().ok().map(Handle::into_kv)
758 }
759
760 /// Returns the first entry in the map for in-place manipulation.
761 /// The key of this entry is the minimum key in the map.
762 ///
763 /// # Examples
764 ///
765 /// ```
766 /// use copse::BTreeMap;
767 ///
768 /// let mut map = BTreeMap::default();
769 /// map.insert(1, "a");
770 /// map.insert(2, "b");
771 /// if let Some(mut entry) = map.first_entry() {
772 /// if *entry.key() > 0 {
773 /// entry.insert("first");
774 /// }
775 /// }
776 /// assert_eq!(*map.get(&1).unwrap(), "first");
777 /// assert_eq!(*map.get(&2).unwrap(), "b");
778 /// ```
779 pub fn first_entry(&mut self) -> Option<OccupiedEntry<'_, K, V, O, A>>
780 where
781 K: SortableBy<O>,
782 O: TotalOrder,
783 {
784 let (map, dormant_map) = DormantMutRef::new(self);
785 let root_node = map.root.as_mut()?.borrow_mut();
786 let kv = root_node.first_leaf_edge().right_kv().ok()?;
787 Some(OccupiedEntry {
788 handle: kv.forget_node_type(),
789 dormant_map,
790 alloc: (*map.alloc).clone(),
791 _marker: PhantomData,
792 })
793 }
794
795 /// Removes and returns the first element in the map.
796 /// The key of this element is the minimum key that was in the map.
797 ///
798 /// # Examples
799 ///
800 /// Draining elements in ascending order, while keeping a usable map each iteration.
801 ///
802 /// ```
803 /// use copse::BTreeMap;
804 ///
805 /// let mut map = BTreeMap::default();
806 /// map.insert(1, "a");
807 /// map.insert(2, "b");
808 /// while let Some((key, _val)) = map.pop_first() {
809 /// assert!(map.iter().all(|(k, _v)| *k > key));
810 /// }
811 /// assert!(map.is_empty());
812 /// ```
813 pub fn pop_first(&mut self) -> Option<(K, V)>
814 where
815 K: SortableBy<O>,
816 O: TotalOrder,
817 {
818 self.first_entry().map(|entry| entry.remove_entry())
819 }
820
821 /// Returns the last key-value pair in the map.
822 /// The key in this pair is the maximum key in the map.
823 ///
824 /// # Examples
825 ///
826 /// Basic usage:
827 ///
828 /// ```
829 /// use copse::BTreeMap;
830 ///
831 /// let mut map = BTreeMap::default();
832 /// map.insert(1, "b");
833 /// map.insert(2, "a");
834 /// assert_eq!(map.last_key_value(), Some((&2, &"a")));
835 /// ```
836 pub fn last_key_value(&self) -> Option<(&K, &V)>
837 where
838 K: SortableBy<O>,
839 O: TotalOrder,
840 {
841 let root_node = self.root.as_ref()?.reborrow();
842 root_node.last_leaf_edge().left_kv().ok().map(Handle::into_kv)
843 }
844
845 /// Returns the last entry in the map for in-place manipulation.
846 /// The key of this entry is the maximum key in the map.
847 ///
848 /// # Examples
849 ///
850 /// ```
851 /// use copse::BTreeMap;
852 ///
853 /// let mut map = BTreeMap::default();
854 /// map.insert(1, "a");
855 /// map.insert(2, "b");
856 /// if let Some(mut entry) = map.last_entry() {
857 /// if *entry.key() > 0 {
858 /// entry.insert("last");
859 /// }
860 /// }
861 /// assert_eq!(*map.get(&1).unwrap(), "a");
862 /// assert_eq!(*map.get(&2).unwrap(), "last");
863 /// ```
864 pub fn last_entry(&mut self) -> Option<OccupiedEntry<'_, K, V, O, A>>
865 where
866 K: SortableBy<O>,
867 O: TotalOrder,
868 {
869 let (map, dormant_map) = DormantMutRef::new(self);
870 let root_node = map.root.as_mut()?.borrow_mut();
871 let kv = root_node.last_leaf_edge().left_kv().ok()?;
872 Some(OccupiedEntry {
873 handle: kv.forget_node_type(),
874 dormant_map,
875 alloc: (*map.alloc).clone(),
876 _marker: PhantomData,
877 })
878 }
879
880 /// Removes and returns the last element in the map.
881 /// The key of this element is the maximum key that was in the map.
882 ///
883 /// # Examples
884 ///
885 /// Draining elements in descending order, while keeping a usable map each iteration.
886 ///
887 /// ```
888 /// use copse::BTreeMap;
889 ///
890 /// let mut map = BTreeMap::default();
891 /// map.insert(1, "a");
892 /// map.insert(2, "b");
893 /// while let Some((key, _val)) = map.pop_last() {
894 /// assert!(map.iter().all(|(k, _v)| *k < key));
895 /// }
896 /// assert!(map.is_empty());
897 /// ```
898 pub fn pop_last(&mut self) -> Option<(K, V)>
899 where
900 K: SortableBy<O>,
901 O: TotalOrder,
902 {
903 self.last_entry().map(|entry| entry.remove_entry())
904 }
905
906 /// Returns `true` if the map contains a value for the specified key.
907 ///
908 /// The key may be any borrowed form of the map's key type, but the ordering
909 /// on the borrowed form *must* match the ordering on the key type.
910 ///
911 /// # Examples
912 ///
913 /// Basic usage:
914 ///
915 /// ```
916 /// use copse::BTreeMap;
917 ///
918 /// let mut map = BTreeMap::default();
919 /// map.insert(1, "a");
920 /// assert_eq!(map.contains_key(&1), true);
921 /// assert_eq!(map.contains_key(&2), false);
922 /// ```
923 pub fn contains_key<Q: ?Sized>(&self, key: &Q) -> bool
924 where
925 K: SortableBy<O>,
926 Q: SortableBy<O>,
927 O: TotalOrder,
928 {
929 self.get(key).is_some()
930 }
931
932 /// Returns a mutable reference to the value corresponding to the key.
933 ///
934 /// The key may be any borrowed form of the map's key type, but the ordering
935 /// on the borrowed form *must* match the ordering on the key type.
936 ///
937 /// # Examples
938 ///
939 /// Basic usage:
940 ///
941 /// ```
942 /// use copse::BTreeMap;
943 ///
944 /// let mut map = BTreeMap::default();
945 /// map.insert(1, "a");
946 /// if let Some(x) = map.get_mut(&1) {
947 /// *x = "b";
948 /// }
949 /// assert_eq!(map[&1], "b");
950 /// ```
951 // See `get` for implementation notes, this is basically a copy-paste with mut's added
952 pub fn get_mut<Q: ?Sized>(&mut self, key: &Q) -> Option<&mut V>
953 where
954 K: SortableBy<O>,
955 Q: SortableBy<O>,
956 O: TotalOrder,
957 {
958 let root_node = self.root.as_mut()?.borrow_mut();
959 match root_node.search_tree(key, &self.order) {
960 Found(handle) => Some(handle.into_val_mut()),
961 GoDown(_) => None,
962 }
963 }
964
965 /// Inserts a key-value pair into the map.
966 ///
967 /// If the map did not have this key present, `None` is returned.
968 ///
969 /// If the map did have this key present, the value is updated, and the old
970 /// value is returned. The key is not updated, though; this matters for
971 /// types that can be `==` without being identical. See the [module-level
972 /// documentation] for more.
973 ///
974 /// [module-level documentation]: index.html#insert-and-complex-keys
975 ///
976 /// # Examples
977 ///
978 /// Basic usage:
979 ///
980 /// ```
981 /// use copse::BTreeMap;
982 ///
983 /// let mut map = BTreeMap::default();
984 /// assert_eq!(map.insert(37, "a"), None);
985 /// assert_eq!(map.is_empty(), false);
986 ///
987 /// map.insert(37, "b");
988 /// assert_eq!(map.insert(37, "c"), Some("b"));
989 /// assert_eq!(map[&37], "c");
990 /// ```
991 pub fn insert(&mut self, key: K, value: V) -> Option<V>
992 where
993 K: SortableBy<O>,
994 O: TotalOrder,
995 {
996 match self.entry(key) {
997 Occupied(mut entry) => Some(entry.insert(value)),
998 Vacant(entry) => {
999 entry.insert(value);
1000 None
1001 }
1002 }
1003 }
1004
1005 /// Tries to insert a key-value pair into the map, and returns
1006 /// a mutable reference to the value in the entry.
1007 ///
1008 /// If the map already had this key present, nothing is updated, and
1009 /// an error containing the occupied entry and the value is returned.
1010 ///
1011 /// # Examples
1012 ///
1013 /// Basic usage:
1014 ///
1015 /// ```
1016 /// use copse::BTreeMap;
1017 ///
1018 /// let mut map = BTreeMap::default();
1019 /// assert_eq!(map.try_insert(37, "a").unwrap(), &"a");
1020 ///
1021 /// let err = map.try_insert(37, "b").unwrap_err();
1022 /// assert_eq!(err.entry.key(), &37);
1023 /// assert_eq!(err.entry.get(), &"a");
1024 /// assert_eq!(err.value, "b");
1025 /// ```
1026 #[cfg(feature = "map_try_insert")]
1027 pub fn try_insert(&mut self, key: K, value: V) -> Result<&mut V, OccupiedError<'_, K, V, O, A>>
1028 where
1029 K: SortableBy<O>,
1030 O: TotalOrder,
1031 {
1032 match self.entry(key) {
1033 Occupied(entry) => Err(OccupiedError { entry, value }),
1034 Vacant(entry) => Ok(entry.insert(value)),
1035 }
1036 }
1037
1038 /// Removes a key from the map, returning the value at the key if the key
1039 /// was previously in the map.
1040 ///
1041 /// The key may be any borrowed form of the map's key type, but the ordering
1042 /// on the borrowed form *must* match the ordering on the key type.
1043 ///
1044 /// # Examples
1045 ///
1046 /// Basic usage:
1047 ///
1048 /// ```
1049 /// use copse::BTreeMap;
1050 ///
1051 /// let mut map = BTreeMap::default();
1052 /// map.insert(1, "a");
1053 /// assert_eq!(map.remove(&1), Some("a"));
1054 /// assert_eq!(map.remove(&1), None);
1055 /// ```
1056 pub fn remove<Q: ?Sized>(&mut self, key: &Q) -> Option<V>
1057 where
1058 K: SortableBy<O>,
1059 Q: SortableBy<O>,
1060 O: TotalOrder,
1061 {
1062 self.remove_entry(key).map(|(_, v)| v)
1063 }
1064
1065 /// Removes a key from the map, returning the stored key and value if the key
1066 /// was previously in the map.
1067 ///
1068 /// The key may be any borrowed form of the map's key type, but the ordering
1069 /// on the borrowed form *must* match the ordering on the key type.
1070 ///
1071 /// # Examples
1072 ///
1073 /// Basic usage:
1074 ///
1075 /// ```
1076 /// use copse::BTreeMap;
1077 ///
1078 /// let mut map = BTreeMap::default();
1079 /// map.insert(1, "a");
1080 /// assert_eq!(map.remove_entry(&1), Some((1, "a")));
1081 /// assert_eq!(map.remove_entry(&1), None);
1082 /// ```
1083 pub fn remove_entry<Q: ?Sized>(&mut self, key: &Q) -> Option<(K, V)>
1084 where
1085 K: SortableBy<O>,
1086 Q: SortableBy<O>,
1087 O: TotalOrder,
1088 {
1089 let (map, dormant_map) = DormantMutRef::new(self);
1090 let root_node = map.root.as_mut()?.borrow_mut();
1091 match root_node.search_tree(key, &map.order) {
1092 Found(handle) => Some(
1093 OccupiedEntry {
1094 handle,
1095 dormant_map,
1096 alloc: (*map.alloc).clone(),
1097 _marker: PhantomData,
1098 }
1099 .remove_entry(),
1100 ),
1101 GoDown(_) => None,
1102 }
1103 }
1104
1105 /// Retains only the elements specified by the predicate.
1106 ///
1107 /// In other words, remove all pairs `(k, v)` for which `f(&k, &mut v)` returns `false`.
1108 /// The elements are visited in ascending key order.
1109 ///
1110 /// # Examples
1111 ///
1112 /// ```
1113 /// use copse::BTreeMap;
1114 ///
1115 /// let mut map: BTreeMap<i32, i32> = (0..8).map(|x| (x, x*10)).collect();
1116 /// // Keep only the elements with even-numbered keys.
1117 /// map.retain(|&k, _| k % 2 == 0);
1118 /// assert!(map.into_iter().eq(vec![(0, 0), (2, 20), (4, 40), (6, 60)]));
1119 /// ```
1120 #[inline]
1121 pub fn retain<F>(&mut self, mut f: F)
1122 where
1123 K: SortableBy<O>,
1124 O: TotalOrder,
1125 F: FnMut(&K, &mut V) -> bool,
1126 {
1127 self.drain_filter(|k, v| !f(k, v));
1128 }
1129
1130 /// Moves all elements from `other` into `self`, leaving `other` empty.
1131 ///
1132 /// If a key from `other` is already present in `self`, the respective
1133 /// value from `self` will be overwritten with the respective value from `other`.
1134 ///
1135 /// # Examples
1136 ///
1137 /// ```
1138 /// use copse::BTreeMap;
1139 ///
1140 /// let mut a = BTreeMap::default();
1141 /// a.insert(1, "a");
1142 /// a.insert(2, "b");
1143 /// a.insert(3, "c"); // Note: Key (3) also present in b.
1144 ///
1145 /// let mut b = BTreeMap::default();
1146 /// b.insert(3, "d"); // Note: Key (3) also present in a.
1147 /// b.insert(4, "e");
1148 /// b.insert(5, "f");
1149 ///
1150 /// a.append(&mut b);
1151 ///
1152 /// assert_eq!(a.len(), 5);
1153 /// assert_eq!(b.len(), 0);
1154 ///
1155 /// assert_eq!(a[&1], "a");
1156 /// assert_eq!(a[&2], "b");
1157 /// assert_eq!(a[&3], "d"); // Note: "c" has been overwritten.
1158 /// assert_eq!(a[&4], "e");
1159 /// assert_eq!(a[&5], "f");
1160 /// ```
1161 pub fn append(&mut self, other: &mut Self)
1162 where
1163 K: SortableBy<O>,
1164 O: Clone + TotalOrder,
1165 A: Clone,
1166 {
1167 // Do we have to append anything at all?
1168 if other.is_empty() {
1169 return;
1170 }
1171
1172 // We can just swap `self` and `other` if `self` is empty.
1173 if self.is_empty() {
1174 mem::swap(self, other);
1175 return;
1176 }
1177
1178 let self_iter =
1179 mem::replace(self, Self::new_in(self.order.clone(), (*self.alloc).clone())).into_iter();
1180 let other_iter =
1181 mem::replace(other, Self::new_in(self.order.clone(), (*self.alloc).clone()))
1182 .into_iter();
1183 let root = self.root.get_or_insert_with(|| Root::new((*self.alloc).clone()));
1184 root.append_from_sorted_iters(
1185 self_iter,
1186 other_iter,
1187 &mut self.length,
1188 |a: &(K, V), b: &(K, V)| self.order.cmp_any(&a.0, &b.0),
1189 (*self.alloc).clone(),
1190 )
1191 }
1192
1193 /// Constructs a double-ended iterator over a sub-range of elements in the map.
1194 /// The simplest way is to use the range syntax `min..max`, thus `range(min..max)` will
1195 /// yield elements from min (inclusive) to max (exclusive).
1196 /// The range may also be entered as `(Bound<T>, Bound<T>)`, so for example
1197 /// `range((Excluded(4), Included(10)))` will yield a left-exclusive, right-inclusive
1198 /// range from 4 to 10.
1199 ///
1200 /// # Panics
1201 ///
1202 /// Panics if range `start > end`.
1203 /// Panics if range `start == end` and both bounds are `Excluded`.
1204 ///
1205 /// # Examples
1206 ///
1207 /// Basic usage:
1208 ///
1209 /// ```
1210 /// use copse::BTreeMap;
1211 /// use std::ops::Bound::Included;
1212 ///
1213 /// let mut map = BTreeMap::default();
1214 /// map.insert(3, "a");
1215 /// map.insert(5, "b");
1216 /// map.insert(8, "c");
1217 /// for (&key, &value) in map.range::<i32, _>((Included(&4), Included(&8))) {
1218 /// println!("{key}: {value}");
1219 /// }
1220 /// assert_eq!(Some((&5, &"b")), map.range(4..).next());
1221 /// ```
1222 pub fn range<T: ?Sized, R>(&self, range: R) -> Range<'_, K, V>
1223 where
1224 T: SortableBy<O>,
1225 K: SortableBy<O>,
1226 O: TotalOrder,
1227 R: RangeBounds<T>,
1228 {
1229 if let Some(root) = &self.root {
1230 Range { inner: root.reborrow().range_search(&self.order, range) }
1231 } else {
1232 Range { inner: LeafRange::none() }
1233 }
1234 }
1235
1236 /// Constructs a mutable double-ended iterator over a sub-range of elements in the map.
1237 /// The simplest way is to use the range syntax `min..max`, thus `range(min..max)` will
1238 /// yield elements from min (inclusive) to max (exclusive).
1239 /// The range may also be entered as `(Bound<T>, Bound<T>)`, so for example
1240 /// `range((Excluded(4), Included(10)))` will yield a left-exclusive, right-inclusive
1241 /// range from 4 to 10.
1242 ///
1243 /// # Panics
1244 ///
1245 /// Panics if range `start > end`.
1246 /// Panics if range `start == end` and both bounds are `Excluded`.
1247 ///
1248 /// # Examples
1249 ///
1250 /// Basic usage:
1251 ///
1252 /// ```
1253 /// use copse::BTreeMap;
1254 ///
1255 /// let mut map: BTreeMap<&str, i32> =
1256 /// [("Alice", 0), ("Bob", 0), ("Carol", 0), ("Cheryl", 0)].into();
1257 /// for (_, balance) in map.range_mut("B".."Cheryl") {
1258 /// *balance += 100;
1259 /// }
1260 /// for (name, balance) in &map {
1261 /// println!("{name} => {balance}");
1262 /// }
1263 /// ```
1264 pub fn range_mut<T: ?Sized, R>(&mut self, range: R) -> RangeMut<'_, K, V>
1265 where
1266 T: SortableBy<O>,
1267 K: SortableBy<O>,
1268 O: TotalOrder,
1269 R: RangeBounds<T>,
1270 {
1271 if let Some(root) = &mut self.root {
1272 RangeMut {
1273 inner: root.borrow_valmut().range_search(&self.order, range),
1274 _marker: PhantomData,
1275 }
1276 } else {
1277 RangeMut { inner: LeafRange::none(), _marker: PhantomData }
1278 }
1279 }
1280
1281 /// Gets the given key's corresponding entry in the map for in-place manipulation.
1282 ///
1283 /// # Examples
1284 ///
1285 /// Basic usage:
1286 ///
1287 /// ```
1288 /// use copse::BTreeMap;
1289 ///
1290 /// let mut count: BTreeMap<&str, usize> = BTreeMap::default();
1291 ///
1292 /// // count the number of occurrences of letters in the vec
1293 /// for x in ["a", "b", "a", "c", "a", "b"] {
1294 /// count.entry(x).and_modify(|curr| *curr += 1).or_insert(1);
1295 /// }
1296 ///
1297 /// assert_eq!(count["a"], 3);
1298 /// assert_eq!(count["b"], 2);
1299 /// assert_eq!(count["c"], 1);
1300 /// ```
1301 pub fn entry(&mut self, key: K) -> Entry<'_, K, V, O, A>
1302 where
1303 K: SortableBy<O>,
1304 O: TotalOrder,
1305 {
1306 let (map, dormant_map) = DormantMutRef::new(self);
1307 match map.root {
1308 None => Vacant(VacantEntry {
1309 key,
1310 handle: None,
1311 dormant_map,
1312 alloc: (*map.alloc).clone(),
1313 _marker: PhantomData,
1314 }),
1315 Some(ref mut root) => match root.borrow_mut().search_tree(&key, &map.order) {
1316 Found(handle) => Occupied(OccupiedEntry {
1317 handle,
1318 dormant_map,
1319 alloc: (*map.alloc).clone(),
1320 _marker: PhantomData,
1321 }),
1322 GoDown(handle) => Vacant(VacantEntry {
1323 key,
1324 handle: Some(handle),
1325 dormant_map,
1326 alloc: (*map.alloc).clone(),
1327 _marker: PhantomData,
1328 }),
1329 },
1330 }
1331 }
1332
1333 /// Splits the collection into two at the given key. Returns everything after the given key,
1334 /// including the key.
1335 ///
1336 /// # Examples
1337 ///
1338 /// Basic usage:
1339 ///
1340 /// ```
1341 /// use copse::BTreeMap;
1342 ///
1343 /// let mut a = BTreeMap::default();
1344 /// a.insert(1, "a");
1345 /// a.insert(2, "b");
1346 /// a.insert(3, "c");
1347 /// a.insert(17, "d");
1348 /// a.insert(41, "e");
1349 ///
1350 /// let b = a.split_off(&3);
1351 ///
1352 /// assert_eq!(a.len(), 2);
1353 /// assert_eq!(b.len(), 3);
1354 ///
1355 /// assert_eq!(a[&1], "a");
1356 /// assert_eq!(a[&2], "b");
1357 ///
1358 /// assert_eq!(b[&3], "c");
1359 /// assert_eq!(b[&17], "d");
1360 /// assert_eq!(b[&41], "e");
1361 /// ```
1362 pub fn split_off<Q: ?Sized>(&mut self, key: &Q) -> Self
1363 where
1364 K: SortableBy<O>,
1365 Q: SortableBy<O>,
1366 O: Clone + TotalOrder,
1367 A: Clone,
1368 {
1369 if self.is_empty() {
1370 return Self::new_in(self.order.clone(), (*self.alloc).clone());
1371 }
1372
1373 let total_num = self.len();
1374 let left_root = self.root.as_mut().unwrap(); // unwrap succeeds because not empty
1375
1376 let right_root = left_root.split_off(key, &self.order, (*self.alloc).clone());
1377
1378 let (new_left_len, right_len) = Root::calc_split_length(total_num, &left_root, &right_root);
1379 self.length = new_left_len;
1380
1381 BTreeMap {
1382 root: Some(right_root),
1383 length: right_len,
1384 order: self.order.clone(),
1385 alloc: self.alloc.clone(),
1386 _marker: PhantomData,
1387 }
1388 }
1389
1390 decorate_if! {
1391 if #[cfg(feature = "btree_drain_filter")] {
1392 /// Creates an iterator that visits all elements (key-value pairs) in
1393 /// ascending key order and uses a closure to determine if an element should
1394 /// be removed. If the closure returns `true`, the element is removed from
1395 /// the map and yielded. If the closure returns `false`, or panics, the
1396 /// element remains in the map and will not be yielded.
1397 ///
1398 /// The iterator also lets you mutate the value of each element in the
1399 /// closure, regardless of whether you choose to keep or remove it.
1400 ///
1401 /// If the iterator is only partially consumed or not consumed at all, each
1402 /// of the remaining elements is still subjected to the closure, which may
1403 /// change its value and, by returning `true`, have the element removed and
1404 /// dropped.
1405 ///
1406 /// It is unspecified how many more elements will be subjected to the
1407 /// closure if a panic occurs in the closure, or a panic occurs while
1408 /// dropping an element, or if the `DrainFilter` value is leaked.
1409 ///
1410 /// # Examples
1411 ///
1412 /// Splitting a map into even and odd keys, reusing the original map:
1413 ///
1414 /// ```
1415 /// use copse::BTreeMap;
1416 ///
1417 /// let mut map: BTreeMap<i32, i32> = (0..8).map(|x| (x, x)).collect();
1418 /// let evens: BTreeMap<_, _> = map.drain_filter(|k, _v| k % 2 == 0).collect();
1419 /// let odds = map;
1420 /// assert_eq!(evens.keys().copied().collect::<Vec<_>>(), [0, 2, 4, 6]);
1421 /// assert_eq!(odds.keys().copied().collect::<Vec<_>>(), [1, 3, 5, 7]);
1422 /// ```
1423 pub
1424 }
1425 fn drain_filter<F>(&mut self, pred: F) -> DrainFilter<'_, K, V, F, A>
1426 where
1427 K: SortableBy<O>,
1428 O: TotalOrder,
1429 F: FnMut(&K, &mut V) -> bool,
1430 {
1431 let (inner, alloc) = self.drain_filter_inner();
1432 DrainFilter { pred, inner, alloc }
1433 }
1434 }
1435
1436 pub(super) fn drain_filter_inner(&mut self) -> (DrainFilterInner<'_, K, V>, A)
1437 where
1438 K: SortableBy<O>,
1439 O: TotalOrder,
1440 {
1441 if let Some(root) = self.root.as_mut() {
1442 let (root, dormant_root) = DormantMutRef::new(root);
1443 let front = root.borrow_mut().first_leaf_edge();
1444 (
1445 DrainFilterInner {
1446 length: &mut self.length,
1447 dormant_root: Some(dormant_root),
1448 cur_leaf_edge: Some(front),
1449 },
1450 (*self.alloc).clone(),
1451 )
1452 } else {
1453 (
1454 DrainFilterInner {
1455 length: &mut self.length,
1456 dormant_root: None,
1457 cur_leaf_edge: None,
1458 },
1459 (*self.alloc).clone(),
1460 )
1461 }
1462 }
1463
1464 /// Creates a consuming iterator visiting all the keys, in sorted order.
1465 /// The map cannot be used after calling this.
1466 /// The iterator element type is `K`.
1467 ///
1468 /// # Examples
1469 ///
1470 /// ```
1471 /// use copse::BTreeMap;
1472 ///
1473 /// let mut a = BTreeMap::default();
1474 /// a.insert(2, "b");
1475 /// a.insert(1, "a");
1476 ///
1477 /// let keys: Vec<i32> = a.into_keys().collect();
1478 /// assert_eq!(keys, [1, 2]);
1479 /// ```
1480 #[inline]
1481 pub fn into_keys(self) -> IntoKeys<K, V, A> {
1482 IntoKeys { inner: self.into_iter() }
1483 }
1484
1485 /// Creates a consuming iterator visiting all the values, in order by key.
1486 /// The map cannot be used after calling this.
1487 /// The iterator element type is `V`.
1488 ///
1489 /// # Examples
1490 ///
1491 /// ```
1492 /// use copse::BTreeMap;
1493 ///
1494 /// let mut a = BTreeMap::default();
1495 /// a.insert(1, "hello");
1496 /// a.insert(2, "goodbye");
1497 ///
1498 /// let values: Vec<&str> = a.into_values().collect();
1499 /// assert_eq!(values, ["hello", "goodbye"]);
1500 /// ```
1501 #[inline]
1502 pub fn into_values(self) -> IntoValues<K, V, A> {
1503 IntoValues { inner: self.into_iter() }
1504 }
1505
1506 /// Makes a `BTreeMap` from a sorted iterator.
1507 pub(crate) fn bulk_build_from_sorted_iter<I>(
1508 iter: I,
1509 order: O,
1510 alloc: A,
1511 ) -> BTreeMap<K, V, O, A>
1512 where
1513 K: SortableBy<O>,
1514 O: TotalOrder,
1515 I: IntoIterator<Item = (K, V)>,
1516 {
1517 let mut root = Root::new(alloc.clone());
1518 let mut length = 0;
1519 root.bulk_push(DedupSortedIter::new(iter.into_iter(), &order), &mut length, alloc.clone());
1520 BTreeMap {
1521 root: Some(root),
1522 length,
1523 order,
1524 alloc: ManuallyDrop::new(alloc),
1525 _marker: PhantomData,
1526 }
1527 }
1528}
1529
1530impl<'a, K, V, O, A: Allocator + Clone> IntoIterator for &'a BTreeMap<K, V, O, A> {
1531 type Item = (&'a K, &'a V);
1532 type IntoIter = Iter<'a, K, V>;
1533
1534 fn into_iter(self) -> Iter<'a, K, V> {
1535 self.iter()
1536 }
1537}
1538
1539impl<'a, K: 'a, V: 'a> Iterator for Iter<'a, K, V> {
1540 type Item = (&'a K, &'a V);
1541
1542 fn next(&mut self) -> Option<(&'a K, &'a V)> {
1543 if self.length == 0 {
1544 None
1545 } else {
1546 self.length -= 1;
1547 Some(unsafe { self.range.next_unchecked() })
1548 }
1549 }
1550
1551 fn size_hint(&self) -> (usize, Option<usize>) {
1552 (self.length, Some(self.length))
1553 }
1554
1555 fn last(mut self) -> Option<(&'a K, &'a V)> {
1556 self.next_back()
1557 }
1558
1559 fn min(mut self) -> Option<(&'a K, &'a V)> {
1560 self.next()
1561 }
1562
1563 fn max(mut self) -> Option<(&'a K, &'a V)> {
1564 self.next_back()
1565 }
1566}
1567
1568impl<K, V> FusedIterator for Iter<'_, K, V> {}
1569
1570impl<'a, K: 'a, V: 'a> DoubleEndedIterator for Iter<'a, K, V> {
1571 fn next_back(&mut self) -> Option<(&'a K, &'a V)> {
1572 if self.length == 0 {
1573 None
1574 } else {
1575 self.length -= 1;
1576 Some(unsafe { self.range.next_back_unchecked() })
1577 }
1578 }
1579}
1580
1581impl<K, V> ExactSizeIterator for Iter<'_, K, V> {
1582 fn len(&self) -> usize {
1583 self.length
1584 }
1585}
1586
1587impl<K, V> Clone for Iter<'_, K, V> {
1588 fn clone(&self) -> Self {
1589 Iter { range: self.range.clone(), length: self.length }
1590 }
1591}
1592
1593impl<'a, K, V, O, A: Allocator + Clone> IntoIterator for &'a mut BTreeMap<K, V, O, A> {
1594 type Item = (&'a K, &'a mut V);
1595 type IntoIter = IterMut<'a, K, V>;
1596
1597 fn into_iter(self) -> IterMut<'a, K, V> {
1598 self.iter_mut()
1599 }
1600}
1601
1602impl<'a, K, V> Iterator for IterMut<'a, K, V> {
1603 type Item = (&'a K, &'a mut V);
1604
1605 fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
1606 if self.length == 0 {
1607 None
1608 } else {
1609 self.length -= 1;
1610 Some(unsafe { self.range.next_unchecked() })
1611 }
1612 }
1613
1614 fn size_hint(&self) -> (usize, Option<usize>) {
1615 (self.length, Some(self.length))
1616 }
1617
1618 fn last(mut self) -> Option<(&'a K, &'a mut V)> {
1619 self.next_back()
1620 }
1621
1622 fn min(mut self) -> Option<(&'a K, &'a mut V)> {
1623 self.next()
1624 }
1625
1626 fn max(mut self) -> Option<(&'a K, &'a mut V)> {
1627 self.next_back()
1628 }
1629}
1630
1631impl<'a, K, V> DoubleEndedIterator for IterMut<'a, K, V> {
1632 fn next_back(&mut self) -> Option<(&'a K, &'a mut V)> {
1633 if self.length == 0 {
1634 None
1635 } else {
1636 self.length -= 1;
1637 Some(unsafe { self.range.next_back_unchecked() })
1638 }
1639 }
1640}
1641
1642impl<K, V> ExactSizeIterator for IterMut<'_, K, V> {
1643 fn len(&self) -> usize {
1644 self.length
1645 }
1646}
1647
1648impl<K, V> FusedIterator for IterMut<'_, K, V> {}
1649
1650impl<'a, K, V> IterMut<'a, K, V> {
1651 /// Returns an iterator of references over the remaining items.
1652 #[inline]
1653 pub(super) fn iter(&self) -> Iter<'_, K, V> {
1654 Iter { range: self.range.reborrow(), length: self.length }
1655 }
1656}
1657
1658impl<K, V, O, A: Allocator + Clone> IntoIterator for BTreeMap<K, V, O, A> {
1659 type Item = (K, V);
1660 type IntoIter = IntoIter<K, V, A>;
1661
1662 fn into_iter(self) -> IntoIter<K, V, A> {
1663 let mut me = ManuallyDrop::new(self);
1664 if let Some(root) = me.root.take() {
1665 let full_range = root.into_dying().full_range();
1666
1667 IntoIter {
1668 range: full_range,
1669 length: me.length,
1670 alloc: unsafe { ManuallyDrop::take(&mut me.alloc) },
1671 }
1672 } else {
1673 IntoIter {
1674 range: LazyLeafRange::none(),
1675 length: 0,
1676 alloc: unsafe { ManuallyDrop::take(&mut me.alloc) },
1677 }
1678 }
1679 }
1680}
1681
1682impl<K, V, A: Allocator + Clone> Drop for IntoIter<K, V, A> {
1683 fn drop(&mut self) {
1684 struct DropGuard<'a, K, V, A: Allocator + Clone>(&'a mut IntoIter<K, V, A>);
1685
1686 impl<'a, K, V, A: Allocator + Clone> Drop for DropGuard<'a, K, V, A> {
1687 fn drop(&mut self) {
1688 // Continue the same loop we perform below. This only runs when unwinding, so we
1689 // don't have to care about panics this time (they'll abort).
1690 while let Some(kv) = self.0.dying_next() {
1691 // SAFETY: we consume the dying handle immediately.
1692 unsafe { kv.drop_key_val() };
1693 }
1694 }
1695 }
1696
1697 while let Some(kv) = self.dying_next() {
1698 let guard = DropGuard(self);
1699 // SAFETY: we don't touch the tree before consuming the dying handle.
1700 unsafe { kv.drop_key_val() };
1701 mem::forget(guard);
1702 }
1703 }
1704}
1705
1706impl<K, V, A: Allocator + Clone> IntoIter<K, V, A> {
1707 /// Core of a `next` method returning a dying KV handle,
1708 /// invalidated by further calls to this function and some others.
1709 fn dying_next(
1710 &mut self,
1711 ) -> Option<Handle<NodeRef<marker::Dying, K, V, marker::LeafOrInternal>, marker::KV>> {
1712 if self.length == 0 {
1713 self.range.deallocating_end(self.alloc.clone());
1714 None
1715 } else {
1716 self.length -= 1;
1717 Some(unsafe { self.range.deallocating_next_unchecked(self.alloc.clone()) })
1718 }
1719 }
1720
1721 /// Core of a `next_back` method returning a dying KV handle,
1722 /// invalidated by further calls to this function and some others.
1723 fn dying_next_back(
1724 &mut self,
1725 ) -> Option<Handle<NodeRef<marker::Dying, K, V, marker::LeafOrInternal>, marker::KV>> {
1726 if self.length == 0 {
1727 self.range.deallocating_end(self.alloc.clone());
1728 None
1729 } else {
1730 self.length -= 1;
1731 Some(unsafe { self.range.deallocating_next_back_unchecked(self.alloc.clone()) })
1732 }
1733 }
1734}
1735
1736impl<K, V, A: Allocator + Clone> Iterator for IntoIter<K, V, A> {
1737 type Item = (K, V);
1738
1739 fn next(&mut self) -> Option<(K, V)> {
1740 // SAFETY: we consume the dying handle immediately.
1741 self.dying_next().map(unsafe { |kv| kv.into_key_val() })
1742 }
1743
1744 fn size_hint(&self) -> (usize, Option<usize>) {
1745 (self.length, Some(self.length))
1746 }
1747}
1748
1749impl<K, V, A: Allocator + Clone> DoubleEndedIterator for IntoIter<K, V, A> {
1750 fn next_back(&mut self) -> Option<(K, V)> {
1751 // SAFETY: we consume the dying handle immediately.
1752 self.dying_next_back().map(unsafe { |kv| kv.into_key_val() })
1753 }
1754}
1755
1756impl<K, V, A: Allocator + Clone> ExactSizeIterator for IntoIter<K, V, A> {
1757 fn len(&self) -> usize {
1758 self.length
1759 }
1760}
1761
1762impl<K, V, A: Allocator + Clone> FusedIterator for IntoIter<K, V, A> {}
1763
1764impl<'a, K, V> Iterator for Keys<'a, K, V> {
1765 type Item = &'a K;
1766
1767 fn next(&mut self) -> Option<&'a K> {
1768 self.inner.next().map(|(k, _)| k)
1769 }
1770
1771 fn size_hint(&self) -> (usize, Option<usize>) {
1772 self.inner.size_hint()
1773 }
1774
1775 fn last(mut self) -> Option<&'a K> {
1776 self.next_back()
1777 }
1778
1779 fn min(mut self) -> Option<&'a K> {
1780 self.next()
1781 }
1782
1783 fn max(mut self) -> Option<&'a K> {
1784 self.next_back()
1785 }
1786}
1787
1788impl<'a, K, V> DoubleEndedIterator for Keys<'a, K, V> {
1789 fn next_back(&mut self) -> Option<&'a K> {
1790 self.inner.next_back().map(|(k, _)| k)
1791 }
1792}
1793
1794impl<K, V> ExactSizeIterator for Keys<'_, K, V> {
1795 fn len(&self) -> usize {
1796 self.inner.len()
1797 }
1798}
1799
1800impl<K, V> FusedIterator for Keys<'_, K, V> {}
1801
1802impl<K, V> Clone for Keys<'_, K, V> {
1803 fn clone(&self) -> Self {
1804 Keys { inner: self.inner.clone() }
1805 }
1806}
1807
1808impl<'a, K, V> Iterator for Values<'a, K, V> {
1809 type Item = &'a V;
1810
1811 fn next(&mut self) -> Option<&'a V> {
1812 self.inner.next().map(|(_, v)| v)
1813 }
1814
1815 fn size_hint(&self) -> (usize, Option<usize>) {
1816 self.inner.size_hint()
1817 }
1818
1819 fn last(mut self) -> Option<&'a V> {
1820 self.next_back()
1821 }
1822}
1823
1824impl<'a, K, V> DoubleEndedIterator for Values<'a, K, V> {
1825 fn next_back(&mut self) -> Option<&'a V> {
1826 self.inner.next_back().map(|(_, v)| v)
1827 }
1828}
1829
1830impl<K, V> ExactSizeIterator for Values<'_, K, V> {
1831 fn len(&self) -> usize {
1832 self.inner.len()
1833 }
1834}
1835
1836impl<K, V> FusedIterator for Values<'_, K, V> {}
1837
1838impl<K, V> Clone for Values<'_, K, V> {
1839 fn clone(&self) -> Self {
1840 Values { inner: self.inner.clone() }
1841 }
1842}
1843
1844decorate_if! {
1845 /// An iterator produced by calling `drain_filter` on BTreeMap.
1846 if #[cfg(feature = "btree_drain_filter")] { pub }
1847 struct DrainFilter<'a, K, V, F, A: Allocator + Clone = Global>
1848 where
1849 F: 'a + FnMut(&K, &mut V) -> bool,
1850 {
1851 pred: F,
1852 inner: DrainFilterInner<'a, K, V>,
1853 /// The BTreeMap will outlive this IntoIter so we don't care about drop order for `alloc`.
1854 alloc: A,
1855 }
1856}
1857/// Most of the implementation of DrainFilter are generic over the type
1858/// of the predicate, thus also serving for BTreeSet::DrainFilter.
1859pub(super) struct DrainFilterInner<'a, K, V> {
1860 /// Reference to the length field in the borrowed map, updated live.
1861 length: &'a mut usize,
1862 /// Buried reference to the root field in the borrowed map.
1863 /// Wrapped in `Option` to allow drop handler to `take` it.
1864 dormant_root: Option<DormantMutRef<'a, Root<K, V>>>,
1865 /// Contains a leaf edge preceding the next element to be returned, or the last leaf edge.
1866 /// Empty if the map has no root, if iteration went beyond the last leaf edge,
1867 /// or if a panic occurred in the predicate.
1868 cur_leaf_edge: Option<Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge>>,
1869}
1870
1871impl<K, V, F, A: Allocator + Clone> Drop for DrainFilter<'_, K, V, F, A>
1872where
1873 F: FnMut(&K, &mut V) -> bool,
1874{
1875 fn drop(&mut self) {
1876 self.for_each(drop);
1877 }
1878}
1879
1880impl<K, V, F> fmt::Debug for DrainFilter<'_, K, V, F>
1881where
1882 K: fmt::Debug,
1883 V: fmt::Debug,
1884 F: FnMut(&K, &mut V) -> bool,
1885{
1886 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1887 f.debug_tuple("DrainFilter").field(&self.inner.peek()).finish()
1888 }
1889}
1890
1891impl<K, V, F, A: Allocator + Clone> Iterator for DrainFilter<'_, K, V, F, A>
1892where
1893 F: FnMut(&K, &mut V) -> bool,
1894{
1895 type Item = (K, V);
1896
1897 fn next(&mut self) -> Option<(K, V)> {
1898 self.inner.next(&mut self.pred, self.alloc.clone())
1899 }
1900
1901 fn size_hint(&self) -> (usize, Option<usize>) {
1902 self.inner.size_hint()
1903 }
1904}
1905
1906impl<'a, K, V> DrainFilterInner<'a, K, V> {
1907 /// Allow Debug implementations to predict the next element.
1908 pub(super) fn peek(&self) -> Option<(&K, &V)> {
1909 let edge = self.cur_leaf_edge.as_ref()?;
1910 edge.reborrow().next_kv().ok().map(Handle::into_kv)
1911 }
1912
1913 /// Implementation of a typical `DrainFilter::next` method, given the predicate.
1914 pub(super) fn next<F, A: Allocator + Clone>(&mut self, pred: &mut F, alloc: A) -> Option<(K, V)>
1915 where
1916 F: FnMut(&K, &mut V) -> bool,
1917 {
1918 while let Ok(mut kv) = self.cur_leaf_edge.take()?.next_kv() {
1919 let (k, v) = kv.kv_mut();
1920 if pred(k, v) {
1921 *self.length -= 1;
1922 let (kv, pos) = kv.remove_kv_tracking(
1923 || {
1924 // SAFETY: we will touch the root in a way that will not
1925 // invalidate the position returned.
1926 let root = unsafe { self.dormant_root.take().unwrap().awaken() };
1927 root.pop_internal_level(alloc.clone());
1928 self.dormant_root = Some(DormantMutRef::new(root).1);
1929 },
1930 alloc.clone(),
1931 );
1932 self.cur_leaf_edge = Some(pos);
1933 return Some(kv);
1934 }
1935 self.cur_leaf_edge = Some(kv.next_leaf_edge());
1936 }
1937 None
1938 }
1939
1940 /// Implementation of a typical `DrainFilter::size_hint` method.
1941 pub(super) fn size_hint(&self) -> (usize, Option<usize>) {
1942 // In most of the btree iterators, `self.length` is the number of elements
1943 // yet to be visited. Here, it includes elements that were visited and that
1944 // the predicate decided not to drain. Making this upper bound more tight
1945 // during iteration would require an extra field.
1946 (0, Some(*self.length))
1947 }
1948}
1949
1950impl<K, V, F> FusedIterator for DrainFilter<'_, K, V, F> where F: FnMut(&K, &mut V) -> bool {}
1951
1952impl<'a, K, V> Iterator for Range<'a, K, V> {
1953 type Item = (&'a K, &'a V);
1954
1955 fn next(&mut self) -> Option<(&'a K, &'a V)> {
1956 self.inner.next_checked()
1957 }
1958
1959 fn last(mut self) -> Option<(&'a K, &'a V)> {
1960 self.next_back()
1961 }
1962
1963 fn min(mut self) -> Option<(&'a K, &'a V)> {
1964 self.next()
1965 }
1966
1967 fn max(mut self) -> Option<(&'a K, &'a V)> {
1968 self.next_back()
1969 }
1970}
1971
1972impl<'a, K, V> Iterator for ValuesMut<'a, K, V> {
1973 type Item = &'a mut V;
1974
1975 fn next(&mut self) -> Option<&'a mut V> {
1976 self.inner.next().map(|(_, v)| v)
1977 }
1978
1979 fn size_hint(&self) -> (usize, Option<usize>) {
1980 self.inner.size_hint()
1981 }
1982
1983 fn last(mut self) -> Option<&'a mut V> {
1984 self.next_back()
1985 }
1986}
1987
1988impl<'a, K, V> DoubleEndedIterator for ValuesMut<'a, K, V> {
1989 fn next_back(&mut self) -> Option<&'a mut V> {
1990 self.inner.next_back().map(|(_, v)| v)
1991 }
1992}
1993
1994impl<K, V> ExactSizeIterator for ValuesMut<'_, K, V> {
1995 fn len(&self) -> usize {
1996 self.inner.len()
1997 }
1998}
1999
2000impl<K, V> FusedIterator for ValuesMut<'_, K, V> {}
2001
2002impl<K, V, A: Allocator + Clone> Iterator for IntoKeys<K, V, A> {
2003 type Item = K;
2004
2005 fn next(&mut self) -> Option<K> {
2006 self.inner.next().map(|(k, _)| k)
2007 }
2008
2009 fn size_hint(&self) -> (usize, Option<usize>) {
2010 self.inner.size_hint()
2011 }
2012
2013 fn last(mut self) -> Option<K> {
2014 self.next_back()
2015 }
2016
2017 fn min(mut self) -> Option<K> {
2018 self.next()
2019 }
2020
2021 fn max(mut self) -> Option<K> {
2022 self.next_back()
2023 }
2024}
2025
2026impl<K, V, A: Allocator + Clone> DoubleEndedIterator for IntoKeys<K, V, A> {
2027 fn next_back(&mut self) -> Option<K> {
2028 self.inner.next_back().map(|(k, _)| k)
2029 }
2030}
2031
2032impl<K, V, A: Allocator + Clone> ExactSizeIterator for IntoKeys<K, V, A> {
2033 fn len(&self) -> usize {
2034 self.inner.len()
2035 }
2036}
2037
2038impl<K, V, A: Allocator + Clone> FusedIterator for IntoKeys<K, V, A> {}
2039
2040impl<K, V, A: Allocator + Clone> Iterator for IntoValues<K, V, A> {
2041 type Item = V;
2042
2043 fn next(&mut self) -> Option<V> {
2044 self.inner.next().map(|(_, v)| v)
2045 }
2046
2047 fn size_hint(&self) -> (usize, Option<usize>) {
2048 self.inner.size_hint()
2049 }
2050
2051 fn last(mut self) -> Option<V> {
2052 self.next_back()
2053 }
2054}
2055
2056impl<K, V, A: Allocator + Clone> DoubleEndedIterator for IntoValues<K, V, A> {
2057 fn next_back(&mut self) -> Option<V> {
2058 self.inner.next_back().map(|(_, v)| v)
2059 }
2060}
2061
2062impl<K, V, A: Allocator + Clone> ExactSizeIterator for IntoValues<K, V, A> {
2063 fn len(&self) -> usize {
2064 self.inner.len()
2065 }
2066}
2067
2068impl<K, V, A: Allocator + Clone> FusedIterator for IntoValues<K, V, A> {}
2069
2070impl<'a, K, V> DoubleEndedIterator for Range<'a, K, V> {
2071 fn next_back(&mut self) -> Option<(&'a K, &'a V)> {
2072 self.inner.next_back_checked()
2073 }
2074}
2075
2076impl<K, V> FusedIterator for Range<'_, K, V> {}
2077
2078impl<K, V> Clone for Range<'_, K, V> {
2079 fn clone(&self) -> Self {
2080 Range { inner: self.inner.clone() }
2081 }
2082}
2083
2084impl<'a, K, V> Iterator for RangeMut<'a, K, V> {
2085 type Item = (&'a K, &'a mut V);
2086
2087 fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
2088 self.inner.next_checked()
2089 }
2090
2091 fn last(mut self) -> Option<(&'a K, &'a mut V)> {
2092 self.next_back()
2093 }
2094
2095 fn min(mut self) -> Option<(&'a K, &'a mut V)> {
2096 self.next()
2097 }
2098
2099 fn max(mut self) -> Option<(&'a K, &'a mut V)> {
2100 self.next_back()
2101 }
2102}
2103
2104impl<'a, K, V> DoubleEndedIterator for RangeMut<'a, K, V> {
2105 fn next_back(&mut self) -> Option<(&'a K, &'a mut V)> {
2106 self.inner.next_back_checked()
2107 }
2108}
2109
2110impl<K, V> FusedIterator for RangeMut<'_, K, V> {}
2111
2112impl<K: SortableBy<O>, V, O: TotalOrder + Default> FromIterator<(K, V)> for BTreeMap<K, V, O> {
2113 fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> BTreeMap<K, V, O> {
2114 let mut inputs: Vec<_> = iter.into_iter().collect();
2115
2116 if inputs.is_empty() {
2117 return BTreeMap::new(O::default());
2118 }
2119
2120 // use stable sort to preserve the insertion order.
2121 let order = O::default();
2122 inputs.sort_by(|a, b| order.cmp_any(&a.0, &b.0));
2123 BTreeMap::bulk_build_from_sorted_iter(inputs, order, Global)
2124 }
2125}
2126
2127impl<K: SortableBy<O>, V, O: TotalOrder, A: Allocator + Clone> Extend<(K, V)>
2128 for BTreeMap<K, V, O, A>
2129{
2130 #[inline]
2131 fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) {
2132 iter.into_iter().for_each(move |(k, v)| {
2133 self.insert(k, v);
2134 });
2135 }
2136
2137 #[inline]
2138 #[cfg(feature = "extend_one")]
2139 fn extend_one(&mut self, (k, v): (K, V)) {
2140 self.insert(k, v);
2141 }
2142}
2143
2144impl<'a, K: SortableBy<O> + Copy, V: Copy, O: TotalOrder, A: Allocator + Clone>
2145 Extend<(&'a K, &'a V)> for BTreeMap<K, V, O, A>
2146{
2147 fn extend<I: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: I) {
2148 self.extend(iter.into_iter().map(|(&key, &value)| (key, value)));
2149 }
2150
2151 #[inline]
2152 #[cfg(feature = "extend_one")]
2153 fn extend_one(&mut self, (&k, &v): (&'a K, &'a V)) {
2154 self.insert(k, v);
2155 }
2156}
2157
2158impl<K: Hash, V: Hash, O, A: Allocator + Clone> Hash for BTreeMap<K, V, O, A> {
2159 fn hash<H: Hasher>(&self, state: &mut H) {
2160 state.write_length_prefix(self.len());
2161 for elt in self {
2162 elt.hash(state);
2163 }
2164 }
2165}
2166
2167impl<K, V, O: TotalOrder + Default> Default for BTreeMap<K, V, O> {
2168 /// Creates an empty `BTreeMap`, ordered by a default `O` order.
2169 fn default() -> BTreeMap<K, V, O> {
2170 BTreeMap::new(O::default())
2171 }
2172}
2173
2174impl<K: PartialEq, V: PartialEq, O, A: Allocator + Clone> PartialEq for BTreeMap<K, V, O, A> {
2175 fn eq(&self, other: &BTreeMap<K, V, O, A>) -> bool {
2176 self.len() == other.len() && self.iter().zip(other).all(|(a, b)| a == b)
2177 }
2178}
2179
2180impl<K: Eq, V: Eq, O, A: Allocator + Clone> Eq for BTreeMap<K, V, O, A> {}
2181
2182impl<K: PartialOrd, V: PartialOrd, O, A: Allocator + Clone> PartialOrd for BTreeMap<K, V, O, A> {
2183 #[inline]
2184 fn partial_cmp(&self, other: &BTreeMap<K, V, O, A>) -> Option<Ordering> {
2185 self.iter().partial_cmp(other.iter())
2186 }
2187}
2188
2189impl<K: Ord, V: Ord, O, A: Allocator + Clone> Ord for BTreeMap<K, V, O, A> {
2190 #[inline]
2191 fn cmp(&self, other: &BTreeMap<K, V, O, A>) -> Ordering {
2192 self.iter().cmp(other.iter())
2193 }
2194}
2195
2196impl<K: Debug, V: Debug, O, A: Allocator + Clone> Debug for BTreeMap<K, V, O, A> {
2197 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2198 f.debug_map().entries(self.iter()).finish()
2199 }
2200}
2201
2202impl<K, Q: ?Sized, V, O, A: Allocator + Clone> Index<&Q> for BTreeMap<K, V, O, A>
2203where
2204 K: SortableBy<O>,
2205 Q: SortableBy<O>,
2206 O: TotalOrder,
2207{
2208 type Output = V;
2209
2210 /// Returns a reference to the value corresponding to the supplied key.
2211 ///
2212 /// # Panics
2213 ///
2214 /// Panics if the key is not present in the `BTreeMap`.
2215 #[inline]
2216 fn index(&self, key: &Q) -> &V {
2217 self.get(key).expect("no entry found for key")
2218 }
2219}
2220
2221impl<K: SortableBy<O>, V, O: TotalOrder + Default, const N: usize> From<[(K, V); N]>
2222 for BTreeMap<K, V, O>
2223{
2224 /// Converts a `[(K, V); N]` into a `BTreeMap<(K, V)>`.
2225 ///
2226 /// ```
2227 /// use copse::BTreeMap;
2228 ///
2229 /// let map1 = BTreeMap::from([(1, 2), (3, 4)]);
2230 /// let map2: BTreeMap<_, _> = [(1, 2), (3, 4)].into();
2231 /// assert_eq!(map1, map2);
2232 /// ```
2233 fn from(mut arr: [(K, V); N]) -> Self {
2234 if N == 0 {
2235 return BTreeMap::new(O::default());
2236 }
2237
2238 // use stable sort to preserve the insertion order.
2239 let order = O::default();
2240 arr.sort_by(|a, b| order.cmp_any(&a.0, &b.0));
2241 BTreeMap::bulk_build_from_sorted_iter(arr, order, Global)
2242 }
2243}
2244
2245impl<K, V, O, A: Allocator + Clone> BTreeMap<K, V, O, A> {
2246 /// Gets an iterator over the entries of the map, sorted by key.
2247 ///
2248 /// # Examples
2249 ///
2250 /// Basic usage:
2251 ///
2252 /// ```
2253 /// use copse::BTreeMap;
2254 ///
2255 /// let mut map = BTreeMap::default();
2256 /// map.insert(3, "c");
2257 /// map.insert(2, "b");
2258 /// map.insert(1, "a");
2259 ///
2260 /// for (key, value) in map.iter() {
2261 /// println!("{key}: {value}");
2262 /// }
2263 ///
2264 /// let (first_key, first_value) = map.iter().next().unwrap();
2265 /// assert_eq!((*first_key, *first_value), (1, "a"));
2266 /// ```
2267 pub fn iter(&self) -> Iter<'_, K, V> {
2268 if let Some(root) = &self.root {
2269 let full_range = root.reborrow().full_range();
2270
2271 Iter { range: full_range, length: self.length }
2272 } else {
2273 Iter { range: LazyLeafRange::none(), length: 0 }
2274 }
2275 }
2276
2277 /// Gets a mutable iterator over the entries of the map, sorted by key.
2278 ///
2279 /// # Examples
2280 ///
2281 /// Basic usage:
2282 ///
2283 /// ```
2284 /// use copse::BTreeMap;
2285 ///
2286 /// let mut map = BTreeMap::<_, _>::from([
2287 /// ("a", 1),
2288 /// ("b", 2),
2289 /// ("c", 3),
2290 /// ]);
2291 ///
2292 /// // add 10 to the value if the key isn't "a"
2293 /// for (key, value) in map.iter_mut() {
2294 /// if key != &"a" {
2295 /// *value += 10;
2296 /// }
2297 /// }
2298 /// ```
2299 pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {
2300 if let Some(root) = &mut self.root {
2301 let full_range = root.borrow_valmut().full_range();
2302
2303 IterMut { range: full_range, length: self.length, _marker: PhantomData }
2304 } else {
2305 IterMut { range: LazyLeafRange::none(), length: 0, _marker: PhantomData }
2306 }
2307 }
2308
2309 /// Gets an iterator over the keys of the map, in sorted order.
2310 ///
2311 /// # Examples
2312 ///
2313 /// Basic usage:
2314 ///
2315 /// ```
2316 /// use copse::BTreeMap;
2317 ///
2318 /// let mut a = BTreeMap::default();
2319 /// a.insert(2, "b");
2320 /// a.insert(1, "a");
2321 ///
2322 /// let keys: Vec<_> = a.keys().cloned().collect();
2323 /// assert_eq!(keys, [1, 2]);
2324 /// ```
2325 pub fn keys(&self) -> Keys<'_, K, V> {
2326 Keys { inner: self.iter() }
2327 }
2328
2329 /// Gets an iterator over the values of the map, in order by key.
2330 ///
2331 /// # Examples
2332 ///
2333 /// Basic usage:
2334 ///
2335 /// ```
2336 /// use copse::BTreeMap;
2337 ///
2338 /// let mut a = BTreeMap::default();
2339 /// a.insert(1, "hello");
2340 /// a.insert(2, "goodbye");
2341 ///
2342 /// let values: Vec<&str> = a.values().cloned().collect();
2343 /// assert_eq!(values, ["hello", "goodbye"]);
2344 /// ```
2345 pub fn values(&self) -> Values<'_, K, V> {
2346 Values { inner: self.iter() }
2347 }
2348
2349 /// Gets a mutable iterator over the values of the map, in order by key.
2350 ///
2351 /// # Examples
2352 ///
2353 /// Basic usage:
2354 ///
2355 /// ```
2356 /// use copse::BTreeMap;
2357 ///
2358 /// let mut a = BTreeMap::default();
2359 /// a.insert(1, String::from("hello"));
2360 /// a.insert(2, String::from("goodbye"));
2361 ///
2362 /// for value in a.values_mut() {
2363 /// value.push_str("!");
2364 /// }
2365 ///
2366 /// let values: Vec<String> = a.values().cloned().collect();
2367 /// assert_eq!(values, [String::from("hello!"),
2368 /// String::from("goodbye!")]);
2369 /// ```
2370 pub fn values_mut(&mut self) -> ValuesMut<'_, K, V> {
2371 ValuesMut { inner: self.iter_mut() }
2372 }
2373
2374 decorate_if! {
2375 /// Returns the number of elements in the map.
2376 ///
2377 /// # Examples
2378 ///
2379 /// Basic usage:
2380 ///
2381 /// ```
2382 /// use copse::BTreeMap;
2383 ///
2384 /// let mut a = BTreeMap::default();
2385 /// assert_eq!(a.len(), 0);
2386 /// a.insert(1, "a");
2387 /// assert_eq!(a.len(), 1);
2388 /// ```
2389 #[must_use]
2390 pub
2391 if #[cfg(feature = "const_btree_len")] { const }
2392 fn len(&self) -> usize {
2393 self.length
2394 }
2395 }
2396
2397 decorate_if! {
2398 /// Returns `true` if the map contains no elements.
2399 ///
2400 /// # Examples
2401 ///
2402 /// Basic usage:
2403 ///
2404 /// ```
2405 /// use copse::BTreeMap;
2406 ///
2407 /// let mut a = BTreeMap::default();
2408 /// assert!(a.is_empty());
2409 /// a.insert(1, "a");
2410 /// assert!(!a.is_empty());
2411 /// ```
2412 #[must_use]
2413 pub
2414 if #[cfg(feature = "const_btree_len")] { const }
2415 fn is_empty(&self) -> bool {
2416 self.len() == 0
2417 }
2418 }
2419
2420 /// Returns a [`Cursor`] pointing at the first element that is above the
2421 /// given bound.
2422 ///
2423 /// If no such element exists then a cursor pointing at the "ghost"
2424 /// non-element is returned.
2425 ///
2426 /// Passing [`Bound::Unbounded`] will return a cursor pointing at the first
2427 /// element of the map.
2428 ///
2429 /// # Examples
2430 ///
2431 /// Basic usage:
2432 ///
2433 /// ```
2434 /// use copse::BTreeMap;
2435 /// use std::ops::Bound;
2436 ///
2437 /// let mut a = BTreeMap::default();
2438 /// a.insert(1, "a");
2439 /// a.insert(2, "b");
2440 /// a.insert(3, "c");
2441 /// a.insert(4, "c");
2442 /// let cursor = a.lower_bound(Bound::Excluded(&2));
2443 /// assert_eq!(cursor.key(), Some(&3));
2444 /// ```
2445 #[cfg(feature = "btree_cursors")]
2446 pub fn lower_bound<Q>(&self, bound: Bound<&Q>) -> Cursor<'_, K, V>
2447 where
2448 K: SortableBy<O>,
2449 Q: SortableBy<O>,
2450 O: TotalOrder,
2451 {
2452 let root_node = match self.root.as_ref() {
2453 None => return Cursor { current: None, root: None },
2454 Some(root) => root.reborrow(),
2455 };
2456 let edge = root_node.lower_bound(&self.order, SearchBound::from_range(bound));
2457 Cursor { current: edge.next_kv().ok(), root: self.root.as_ref() }
2458 }
2459
2460 /// Returns a [`CursorMut`] pointing at the first element that is above the
2461 /// given bound.
2462 ///
2463 /// If no such element exists then a cursor pointing at the "ghost"
2464 /// non-element is returned.
2465 ///
2466 /// Passing [`Bound::Unbounded`] will return a cursor pointing at the first
2467 /// element of the map.
2468 ///
2469 /// # Examples
2470 ///
2471 /// Basic usage:
2472 ///
2473 /// ```
2474 /// use copse::BTreeMap;
2475 /// use std::ops::Bound;
2476 ///
2477 /// let mut a = BTreeMap::default();
2478 /// a.insert(1, "a");
2479 /// a.insert(2, "b");
2480 /// a.insert(3, "c");
2481 /// a.insert(4, "c");
2482 /// let cursor = a.lower_bound_mut(Bound::Excluded(&2));
2483 /// assert_eq!(cursor.key(), Some(&3));
2484 /// ```
2485 #[cfg(feature = "btree_cursors")]
2486 pub fn lower_bound_mut<Q>(&mut self, bound: Bound<&Q>) -> CursorMut<'_, K, V, A>
2487 where
2488 K: SortableBy<O>,
2489 Q: SortableBy<O>,
2490 O: TotalOrder,
2491 {
2492 let (root, dormant_root) = DormantMutRef::new(&mut self.root);
2493 let root_node = match root.as_mut() {
2494 None => {
2495 return CursorMut {
2496 current: None,
2497 root: dormant_root,
2498 length: &mut self.length,
2499 alloc: &mut *self.alloc,
2500 };
2501 }
2502 Some(root) => root.borrow_mut(),
2503 };
2504 let edge = root_node.lower_bound(&self.order, SearchBound::from_range(bound));
2505 CursorMut {
2506 current: edge.next_kv().ok(),
2507 root: dormant_root,
2508 length: &mut self.length,
2509 alloc: &mut *self.alloc,
2510 }
2511 }
2512
2513 /// Returns a [`Cursor`] pointing at the last element that is below the
2514 /// given bound.
2515 ///
2516 /// If no such element exists then a cursor pointing at the "ghost"
2517 /// non-element is returned.
2518 ///
2519 /// Passing [`Bound::Unbounded`] will return a cursor pointing at the last
2520 /// element of the map.
2521 ///
2522 /// # Examples
2523 ///
2524 /// Basic usage:
2525 ///
2526 /// ```
2527 /// use copse::BTreeMap;
2528 /// use std::ops::Bound;
2529 ///
2530 /// let mut a = BTreeMap::default();
2531 /// a.insert(1, "a");
2532 /// a.insert(2, "b");
2533 /// a.insert(3, "c");
2534 /// a.insert(4, "c");
2535 /// let cursor = a.upper_bound(Bound::Excluded(&3));
2536 /// assert_eq!(cursor.key(), Some(&2));
2537 /// ```
2538 #[cfg(feature = "btree_cursors")]
2539 pub fn upper_bound<Q>(&self, bound: Bound<&Q>) -> Cursor<'_, K, V>
2540 where
2541 K: SortableBy<O>,
2542 Q: SortableBy<O>,
2543 O: TotalOrder,
2544 {
2545 let root_node = match self.root.as_ref() {
2546 None => return Cursor { current: None, root: None },
2547 Some(root) => root.reborrow(),
2548 };
2549 let edge = root_node.upper_bound(&self.order, SearchBound::from_range(bound));
2550 Cursor { current: edge.next_back_kv().ok(), root: self.root.as_ref() }
2551 }
2552
2553 /// Returns a [`CursorMut`] pointing at the last element that is below the
2554 /// given bound.
2555 ///
2556 /// If no such element exists then a cursor pointing at the "ghost"
2557 /// non-element is returned.
2558 ///
2559 /// Passing [`Bound::Unbounded`] will return a cursor pointing at the last
2560 /// element of the map.
2561 ///
2562 /// # Examples
2563 ///
2564 /// Basic usage:
2565 ///
2566 /// ```
2567 /// use copse::BTreeMap;
2568 /// use std::ops::Bound;
2569 ///
2570 /// let mut a = BTreeMap::default();
2571 /// a.insert(1, "a");
2572 /// a.insert(2, "b");
2573 /// a.insert(3, "c");
2574 /// a.insert(4, "c");
2575 /// let cursor = a.upper_bound_mut(Bound::Excluded(&3));
2576 /// assert_eq!(cursor.key(), Some(&2));
2577 /// ```
2578 #[cfg(feature = "btree_cursors")]
2579 pub fn upper_bound_mut<Q>(&mut self, bound: Bound<&Q>) -> CursorMut<'_, K, V, A>
2580 where
2581 K: SortableBy<O>,
2582 Q: SortableBy<O>,
2583 O: TotalOrder,
2584 {
2585 let (root, dormant_root) = DormantMutRef::new(&mut self.root);
2586 let root_node = match root.as_mut() {
2587 None => {
2588 return CursorMut {
2589 current: None,
2590 root: dormant_root,
2591 length: &mut self.length,
2592 alloc: &mut *self.alloc,
2593 };
2594 }
2595 Some(root) => root.borrow_mut(),
2596 };
2597 let edge = root_node.upper_bound(&self.order, SearchBound::from_range(bound));
2598 CursorMut {
2599 current: edge.next_back_kv().ok(),
2600 root: dormant_root,
2601 length: &mut self.length,
2602 alloc: &mut *self.alloc,
2603 }
2604 }
2605}
2606
2607/// A cursor over a `BTreeMap`.
2608///
2609/// A `Cursor` is like an iterator, except that it can freely seek back-and-forth.
2610///
2611/// Cursors always point to an element in the tree, and index in a logically circular way.
2612/// To accommodate this, there is a "ghost" non-element that yields `None` between the last and
2613/// first elements of the tree.
2614///
2615/// A `Cursor` is created with the [`BTreeMap::lower_bound`] and [`BTreeMap::upper_bound`] methods.
2616#[cfg(feature = "btree_cursors")]
2617pub struct Cursor<'a, K: 'a, V: 'a> {
2618 current: Option<Handle<NodeRef<marker::Immut<'a>, K, V, marker::LeafOrInternal>, marker::KV>>,
2619 root: Option<&'a node::Root<K, V>>,
2620}
2621
2622#[cfg(feature = "btree_cursors")]
2623impl<K, V> Clone for Cursor<'_, K, V> {
2624 fn clone(&self) -> Self {
2625 let Cursor { current, root } = *self;
2626 Cursor { current, root }
2627 }
2628}
2629
2630#[cfg(feature = "btree_cursors")]
2631impl<K: Debug, V: Debug> Debug for Cursor<'_, K, V> {
2632 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2633 f.debug_tuple("Cursor").field(&self.key_value()).finish()
2634 }
2635}
2636
2637/// A cursor over a `BTreeMap` with editing operations.
2638///
2639/// A `Cursor` is like an iterator, except that it can freely seek back-and-forth, and can
2640/// safely mutate the tree during iteration. This is because the lifetime of its yielded
2641/// references is tied to its own lifetime, instead of just the underlying tree. This means
2642/// cursors cannot yield multiple elements at once.
2643///
2644/// Cursors always point to an element in the tree, and index in a logically circular way.
2645/// To accommodate this, there is a "ghost" non-element that yields `None` between the last and
2646/// first elements of the tree.
2647///
2648/// A `Cursor` is created with the [`BTreeMap::lower_bound_mut`] and [`BTreeMap::upper_bound_mut`]
2649/// methods.
2650#[cfg(feature = "btree_cursors")]
2651pub struct CursorMut<'a, K: 'a, V: 'a, A = Global> {
2652 current: Option<Handle<NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal>, marker::KV>>,
2653 root: DormantMutRef<'a, Option<node::Root<K, V>>>,
2654 length: &'a mut usize,
2655 alloc: &'a mut A,
2656}
2657
2658#[cfg(feature = "btree_cursors")]
2659impl<K: Debug, V: Debug, A> Debug for CursorMut<'_, K, V, A> {
2660 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2661 f.debug_tuple("CursorMut").field(&self.key_value()).finish()
2662 }
2663}
2664
2665#[cfg(feature = "btree_cursors")]
2666impl<'a, K, V> Cursor<'a, K, V> {
2667 /// Moves the cursor to the next element of the `BTreeMap`.
2668 ///
2669 /// If the cursor is pointing to the "ghost" non-element then this will move it to
2670 /// the first element of the `BTreeMap`. If it is pointing to the last
2671 /// element of the `BTreeMap` then this will move it to the "ghost" non-element.
2672 #[cfg(feature = "btree_cursors")]
2673 pub fn move_next(&mut self) {
2674 match self.current.take() {
2675 None => {
2676 self.current = self.root.and_then(|root| {
2677 root.reborrow().first_leaf_edge().forget_node_type().right_kv().ok()
2678 });
2679 }
2680 Some(current) => {
2681 self.current = current.next_leaf_edge().next_kv().ok();
2682 }
2683 }
2684 }
2685
2686 /// Moves the cursor to the previous element of the `BTreeMap`.
2687 ///
2688 /// If the cursor is pointing to the "ghost" non-element then this will move it to
2689 /// the last element of the `BTreeMap`. If it is pointing to the first
2690 /// element of the `BTreeMap` then this will move it to the "ghost" non-element.
2691 #[cfg(feature = "btree_cursors")]
2692 pub fn move_prev(&mut self) {
2693 match self.current.take() {
2694 None => {
2695 self.current = self.root.and_then(|root| {
2696 root.reborrow().last_leaf_edge().forget_node_type().left_kv().ok()
2697 });
2698 }
2699 Some(current) => {
2700 self.current = current.next_back_leaf_edge().next_back_kv().ok();
2701 }
2702 }
2703 }
2704
2705 /// Returns a reference to the key of the element that the cursor is
2706 /// currently pointing to.
2707 ///
2708 /// This returns `None` if the cursor is currently pointing to the
2709 /// "ghost" non-element.
2710 #[cfg(feature = "btree_cursors")]
2711 pub fn key(&self) -> Option<&'a K> {
2712 self.current.as_ref().map(|current| current.into_kv().0)
2713 }
2714
2715 /// Returns a reference to the value of the element that the cursor is
2716 /// currently pointing to.
2717 ///
2718 /// This returns `None` if the cursor is currently pointing to the
2719 /// "ghost" non-element.
2720 #[cfg(feature = "btree_cursors")]
2721 pub fn value(&self) -> Option<&'a V> {
2722 self.current.as_ref().map(|current| current.into_kv().1)
2723 }
2724
2725 /// Returns a reference to the key and value of the element that the cursor
2726 /// is currently pointing to.
2727 ///
2728 /// This returns `None` if the cursor is currently pointing to the
2729 /// "ghost" non-element.
2730 #[cfg(feature = "btree_cursors")]
2731 pub fn key_value(&self) -> Option<(&'a K, &'a V)> {
2732 self.current.as_ref().map(|current| current.into_kv())
2733 }
2734
2735 /// Returns a reference to the next element.
2736 ///
2737 /// If the cursor is pointing to the "ghost" non-element then this returns
2738 /// the first element of the `BTreeMap`. If it is pointing to the last
2739 /// element of the `BTreeMap` then this returns `None`.
2740 #[cfg(feature = "btree_cursors")]
2741 pub fn peek_next(&self) -> Option<(&'a K, &'a V)> {
2742 let mut next = self.clone();
2743 next.move_next();
2744 next.current.as_ref().map(|current| current.into_kv())
2745 }
2746
2747 /// Returns a reference to the previous element.
2748 ///
2749 /// If the cursor is pointing to the "ghost" non-element then this returns
2750 /// the last element of the `BTreeMap`. If it is pointing to the first
2751 /// element of the `BTreeMap` then this returns `None`.
2752 #[cfg(feature = "btree_cursors")]
2753 pub fn peek_prev(&self) -> Option<(&'a K, &'a V)> {
2754 let mut prev = self.clone();
2755 prev.move_prev();
2756 prev.current.as_ref().map(|current| current.into_kv())
2757 }
2758}
2759
2760#[cfg(feature = "btree_cursors")]
2761impl<'a, K, V, A> CursorMut<'a, K, V, A> {
2762 /// Moves the cursor to the next element of the `BTreeMap`.
2763 ///
2764 /// If the cursor is pointing to the "ghost" non-element then this will move it to
2765 /// the first element of the `BTreeMap`. If it is pointing to the last
2766 /// element of the `BTreeMap` then this will move it to the "ghost" non-element.
2767 #[cfg(feature = "btree_cursors")]
2768 pub fn move_next(&mut self) {
2769 match self.current.take() {
2770 None => {
2771 // SAFETY: The previous borrow of root has ended.
2772 self.current = unsafe { self.root.reborrow() }.as_mut().and_then(|root| {
2773 root.borrow_mut().first_leaf_edge().forget_node_type().right_kv().ok()
2774 });
2775 }
2776 Some(current) => {
2777 self.current = current.next_leaf_edge().next_kv().ok();
2778 }
2779 }
2780 }
2781
2782 /// Moves the cursor to the previous element of the `BTreeMap`.
2783 ///
2784 /// If the cursor is pointing to the "ghost" non-element then this will move it to
2785 /// the last element of the `BTreeMap`. If it is pointing to the first
2786 /// element of the `BTreeMap` then this will move it to the "ghost" non-element.
2787 #[cfg(feature = "btree_cursors")]
2788 pub fn move_prev(&mut self) {
2789 match self.current.take() {
2790 None => {
2791 // SAFETY: The previous borrow of root has ended.
2792 self.current = unsafe { self.root.reborrow() }.as_mut().and_then(|root| {
2793 root.borrow_mut().last_leaf_edge().forget_node_type().left_kv().ok()
2794 });
2795 }
2796 Some(current) => {
2797 self.current = current.next_back_leaf_edge().next_back_kv().ok();
2798 }
2799 }
2800 }
2801
2802 /// Returns a reference to the key of the element that the cursor is
2803 /// currently pointing to.
2804 ///
2805 /// This returns `None` if the cursor is currently pointing to the
2806 /// "ghost" non-element.
2807 #[cfg(feature = "btree_cursors")]
2808 pub fn key(&self) -> Option<&K> {
2809 self.current.as_ref().map(|current| current.reborrow().into_kv().0)
2810 }
2811
2812 /// Returns a reference to the value of the element that the cursor is
2813 /// currently pointing to.
2814 ///
2815 /// This returns `None` if the cursor is currently pointing to the
2816 /// "ghost" non-element.
2817 #[cfg(feature = "btree_cursors")]
2818 pub fn value(&self) -> Option<&V> {
2819 self.current.as_ref().map(|current| current.reborrow().into_kv().1)
2820 }
2821
2822 /// Returns a reference to the key and value of the element that the cursor
2823 /// is currently pointing to.
2824 ///
2825 /// This returns `None` if the cursor is currently pointing to the
2826 /// "ghost" non-element.
2827 #[cfg(feature = "btree_cursors")]
2828 pub fn key_value(&self) -> Option<(&K, &V)> {
2829 self.current.as_ref().map(|current| current.reborrow().into_kv())
2830 }
2831
2832 /// Returns a mutable reference to the value of the element that the cursor
2833 /// is currently pointing to.
2834 ///
2835 /// This returns `None` if the cursor is currently pointing to the
2836 /// "ghost" non-element.
2837 #[cfg(feature = "btree_cursors")]
2838 pub fn value_mut(&mut self) -> Option<&mut V> {
2839 self.current.as_mut().map(|current| current.kv_mut().1)
2840 }
2841
2842 /// Returns a reference to the key and mutable reference to the value of the
2843 /// element that the cursor is currently pointing to.
2844 ///
2845 /// This returns `None` if the cursor is currently pointing to the
2846 /// "ghost" non-element.
2847 #[cfg(feature = "btree_cursors")]
2848 pub fn key_value_mut(&mut self) -> Option<(&K, &mut V)> {
2849 self.current.as_mut().map(|current| {
2850 let (k, v) = current.kv_mut();
2851 (&*k, v)
2852 })
2853 }
2854
2855 /// Returns a mutable reference to the of the element that the cursor is
2856 /// currently pointing to.
2857 ///
2858 /// This returns `None` if the cursor is currently pointing to the
2859 /// "ghost" non-element.
2860 ///
2861 /// # Safety
2862 ///
2863 /// This can be used to modify the key, but you must ensure that the
2864 /// `BTreeMap` invariants are maintained. Specifically:
2865 ///
2866 /// * The key must remain unique within the tree.
2867 /// * The key must remain in sorted order with regards to other elements in
2868 /// the tree.
2869 #[cfg(feature = "btree_cursors")]
2870 pub unsafe fn key_mut_unchecked(&mut self) -> Option<&mut K> {
2871 self.current.as_mut().map(|current| current.kv_mut().0)
2872 }
2873
2874 /// Returns a reference to the key and value of the next element.
2875 ///
2876 /// If the cursor is pointing to the "ghost" non-element then this returns
2877 /// the first element of the `BTreeMap`. If it is pointing to the last
2878 /// element of the `BTreeMap` then this returns `None`.
2879 #[cfg(feature = "btree_cursors")]
2880 pub fn peek_next(&mut self) -> Option<(&K, &mut V)> {
2881 let (k, v) = match self.current {
2882 None => {
2883 // SAFETY: The previous borrow of root has ended.
2884 unsafe { self.root.reborrow() }
2885 .as_mut()?
2886 .borrow_mut()
2887 .first_leaf_edge()
2888 .next_kv()
2889 .ok()?
2890 .into_kv_valmut()
2891 }
2892 // SAFETY: We're not using this to mutate the tree.
2893 Some(ref mut current) => {
2894 unsafe { current.reborrow_mut() }.next_leaf_edge().next_kv().ok()?.into_kv_valmut()
2895 }
2896 };
2897 Some((k, v))
2898 }
2899
2900 /// Returns a reference to the key and value of the previous element.
2901 ///
2902 /// If the cursor is pointing to the "ghost" non-element then this returns
2903 /// the last element of the `BTreeMap`. If it is pointing to the first
2904 /// element of the `BTreeMap` then this returns `None`.
2905 #[cfg(feature = "btree_cursors")]
2906 pub fn peek_prev(&mut self) -> Option<(&K, &mut V)> {
2907 let (k, v) = match self.current.as_mut() {
2908 None => {
2909 // SAFETY: The previous borrow of root has ended.
2910 unsafe { self.root.reborrow() }
2911 .as_mut()?
2912 .borrow_mut()
2913 .first_leaf_edge()
2914 .next_kv()
2915 .ok()?
2916 .into_kv_valmut()
2917 }
2918 Some(current) => {
2919 // SAFETY: We're not using this to mutate the tree.
2920 unsafe { current.reborrow_mut() }
2921 .next_back_leaf_edge()
2922 .next_back_kv()
2923 .ok()?
2924 .into_kv_valmut()
2925 }
2926 };
2927 Some((k, v))
2928 }
2929
2930 /// Returns a read-only cursor pointing to the current element.
2931 ///
2932 /// The lifetime of the returned `Cursor` is bound to that of the
2933 /// `CursorMut`, which means it cannot outlive the `CursorMut` and that the
2934 /// `CursorMut` is frozen for the lifetime of the `Cursor`.
2935 #[cfg(feature = "btree_cursors")]
2936 pub fn as_cursor(&self) -> Cursor<'_, K, V> {
2937 Cursor {
2938 // SAFETY: The tree is immutable while the cursor exists.
2939 root: unsafe { self.root.reborrow_shared().as_ref() },
2940 current: self.current.as_ref().map(|current| current.reborrow()),
2941 }
2942 }
2943}
2944
2945// Now the tree editing operations
2946#[cfg(feature = "btree_cursors")]
2947impl<'a, K: Ord, V, A: Allocator + Clone> CursorMut<'a, K, V, A> {
2948 /// Inserts a new element into the `BTreeMap` after the current one.
2949 ///
2950 /// If the cursor is pointing at the "ghost" non-element then the new element is
2951 /// inserted at the front of the `BTreeMap`.
2952 ///
2953 /// # Safety
2954 ///
2955 /// You must ensure that the `BTreeMap` invariants are maintained.
2956 /// Specifically:
2957 ///
2958 /// * The key of the newly inserted element must be unique in the tree.
2959 /// * All keys in the tree must remain in sorted order.
2960 #[cfg(feature = "btree_cursors")]
2961 pub unsafe fn insert_after_unchecked(&mut self, key: K, value: V) {
2962 let edge = match self.current.take() {
2963 None => {
2964 // SAFETY: We have no other reference to the tree.
2965 match unsafe { self.root.reborrow() } {
2966 root @ None => {
2967 // Tree is empty, allocate a new root.
2968 let mut node = NodeRef::new_leaf(self.alloc.clone());
2969 node.borrow_mut().push(key, value);
2970 *root = Some(node.forget_type());
2971 *self.length += 1;
2972 return;
2973 }
2974 Some(root) => root.borrow_mut().first_leaf_edge(),
2975 }
2976 }
2977 Some(current) => current.next_leaf_edge(),
2978 };
2979
2980 let handle = edge.insert_recursing(key, value, self.alloc.clone(), |ins| {
2981 drop(ins.left);
2982 // SAFETY: The handle to the newly inserted value is always on a
2983 // leaf node, so adding a new root node doesn't invalidate it.
2984 let root = unsafe { self.root.reborrow().as_mut().unwrap() };
2985 root.push_internal_level(self.alloc.clone()).push(ins.kv.0, ins.kv.1, ins.right)
2986 });
2987 self.current = handle.left_edge().next_back_kv().ok();
2988 *self.length += 1;
2989 }
2990
2991 /// Inserts a new element into the `BTreeMap` before the current one.
2992 ///
2993 /// If the cursor is pointing at the "ghost" non-element then the new element is
2994 /// inserted at the end of the `BTreeMap`.
2995 ///
2996 /// # Safety
2997 ///
2998 /// You must ensure that the `BTreeMap` invariants are maintained.
2999 /// Specifically:
3000 ///
3001 /// * The key of the newly inserted element must be unique in the tree.
3002 /// * All keys in the tree must remain in sorted order.
3003 #[cfg(feature = "btree_cursors")]
3004 pub unsafe fn insert_before_unchecked(&mut self, key: K, value: V) {
3005 let edge = match self.current.take() {
3006 None => {
3007 // SAFETY: We have no other reference to the tree.
3008 match unsafe { self.root.reborrow() } {
3009 root @ None => {
3010 // Tree is empty, allocate a new root.
3011 let mut node = NodeRef::new_leaf(self.alloc.clone());
3012 node.borrow_mut().push(key, value);
3013 *root = Some(node.forget_type());
3014 *self.length += 1;
3015 return;
3016 }
3017 Some(root) => root.borrow_mut().last_leaf_edge(),
3018 }
3019 }
3020 Some(current) => current.next_back_leaf_edge(),
3021 };
3022
3023 let handle = edge.insert_recursing(key, value, self.alloc.clone(), |ins| {
3024 drop(ins.left);
3025 // SAFETY: The handle to the newly inserted value is always on a
3026 // leaf node, so adding a new root node doesn't invalidate it.
3027 let root = unsafe { self.root.reborrow().as_mut().unwrap() };
3028 root.push_internal_level(self.alloc.clone()).push(ins.kv.0, ins.kv.1, ins.right)
3029 });
3030 self.current = handle.right_edge().next_kv().ok();
3031 *self.length += 1;
3032 }
3033
3034 /// Inserts a new element into the `BTreeMap` after the current one.
3035 ///
3036 /// If the cursor is pointing at the "ghost" non-element then the new element is
3037 /// inserted at the front of the `BTreeMap`.
3038 ///
3039 /// # Panics
3040 ///
3041 /// This function panics if:
3042 /// - the given key compares less than or equal to the current element (if
3043 /// any).
3044 /// - the given key compares greater than or equal to the next element (if
3045 /// any).
3046 #[cfg(feature = "btree_cursors")]
3047 pub fn insert_after(&mut self, key: K, value: V) {
3048 if let Some(current) = self.key() {
3049 if &key <= current {
3050 panic!("key must be ordered above the current element");
3051 }
3052 }
3053 if let Some((next, _)) = self.peek_prev() {
3054 if &key >= next {
3055 panic!("key must be ordered below the next element");
3056 }
3057 }
3058 unsafe {
3059 self.insert_after_unchecked(key, value);
3060 }
3061 }
3062
3063 /// Inserts a new element into the `BTreeMap` before the current one.
3064 ///
3065 /// If the cursor is pointing at the "ghost" non-element then the new element is
3066 /// inserted at the end of the `BTreeMap`.
3067 ///
3068 /// # Panics
3069 ///
3070 /// This function panics if:
3071 /// - the given key compares greater than or equal to the current element
3072 /// (if any).
3073 /// - the given key compares less than or equal to the previous element (if
3074 /// any).
3075 #[cfg(feature = "btree_cursors")]
3076 pub fn insert_before(&mut self, key: K, value: V) {
3077 if let Some(current) = self.key() {
3078 if &key >= current {
3079 panic!("key must be ordered below the current element");
3080 }
3081 }
3082 if let Some((prev, _)) = self.peek_prev() {
3083 if &key <= prev {
3084 panic!("key must be ordered above the previous element");
3085 }
3086 }
3087 unsafe {
3088 self.insert_before_unchecked(key, value);
3089 }
3090 }
3091
3092 /// Removes the current element from the `BTreeMap`.
3093 ///
3094 /// The element that was removed is returned, and the cursor is
3095 /// moved to point to the next element in the `BTreeMap`.
3096 ///
3097 /// If the cursor is currently pointing to the "ghost" non-element then no element
3098 /// is removed and `None` is returned. The cursor is not moved in this case.
3099 #[cfg(feature = "btree_cursors")]
3100 pub fn remove_current(&mut self) -> Option<(K, V)> {
3101 let current = self.current.take()?;
3102 let mut emptied_internal_root = false;
3103 let (kv, pos) =
3104 current.remove_kv_tracking(|| emptied_internal_root = true, self.alloc.clone());
3105 self.current = pos.next_kv().ok();
3106 *self.length -= 1;
3107 if emptied_internal_root {
3108 // SAFETY: This is safe since current does not point within the now
3109 // empty root node.
3110 let root = unsafe { self.root.reborrow().as_mut().unwrap() };
3111 root.pop_internal_level(self.alloc.clone());
3112 }
3113 Some(kv)
3114 }
3115
3116 /// Removes the current element from the `BTreeMap`.
3117 ///
3118 /// The element that was removed is returned, and the cursor is
3119 /// moved to point to the previous element in the `BTreeMap`.
3120 ///
3121 /// If the cursor is currently pointing to the "ghost" non-element then no element
3122 /// is removed and `None` is returned. The cursor is not moved in this case.
3123 #[cfg(feature = "btree_cursors")]
3124 pub fn remove_current_and_move_back(&mut self) -> Option<(K, V)> {
3125 let current = self.current.take()?;
3126 let mut emptied_internal_root = false;
3127 let (kv, pos) =
3128 current.remove_kv_tracking(|| emptied_internal_root = true, self.alloc.clone());
3129 self.current = pos.next_back_kv().ok();
3130 *self.length -= 1;
3131 if emptied_internal_root {
3132 // SAFETY: This is safe since current does not point within the now
3133 // empty root node.
3134 let root = unsafe { self.root.reborrow().as_mut().unwrap() };
3135 root.pop_internal_level(self.alloc.clone());
3136 }
3137 Some(kv)
3138 }
3139}
3140
3141#[cfg(test)]
3142mod tests;