wt_indexset/
lib.rs

1#[cfg(feature = "concurrent")]
2pub mod concurrent;
3
4#[cfg(feature = "concurrent")]
5pub mod cdc;
6
7pub mod core;
8
9use crate::Entry::{Occupied, Vacant};
10use core::constants::DEFAULT_INNER_SIZE;
11use core::node::*;
12use core::pair::Pair;
13use ftree::FenwickTree;
14#[cfg(feature = "serde")]
15use serde::{Deserialize, Serialize};
16use std::borrow::Borrow;
17use std::cmp::Ordering;
18use std::collections::Bound;
19use std::iter::FusedIterator;
20use std::mem::swap;
21use std::ops::{Index, RangeBounds};
22
23type Node<T> = Vec<T>;
24
25/// An ordered set based on a B-Tree.
26///
27/// See [`BTreeMap`]'s documentation for a detailed discussion of this collection's performance
28/// benefits and drawbacks.
29///
30/// It is a logic error for an item to be modified in such a way that the item's ordering relative
31/// to any other item, as determined by the [`Ord`] trait, changes while it is in the set. This is
32/// normally only possible through [`Cell`], [`RefCell`], global state, I/O, or unsafe code.
33/// The behavior resulting from such a logic error is not specified, but will be encapsulated to the
34/// `BTreeSet` that observed the logic error and not result in undefined behavior. This could
35/// include panics, incorrect results, aborts, memory leaks, and non-termination.
36///
37/// Iterators returned by [`BTreeSet::iter`] produce their items in order, and take worst-case
38/// logarithmic and amortized constant time per item returned.
39///
40/// [`Cell`]: core::cell::Cell
41/// [`RefCell`]: core::cell::RefCell
42///
43/// # Examples
44///
45/// ```
46/// use wt_indexset::BTreeSet;
47///
48/// // Type inference lets us omit an explicit type signature (which
49/// // would be `BTreeSet<&str>` in this example).
50/// let mut books = BTreeSet::new();
51///
52/// // Add some books.
53/// books.insert("A Dance With Dragons");
54/// books.insert("To Kill a Mockingbird");
55/// books.insert("The Odyssey");
56/// books.insert("The Great Gatsby");
57///
58/// // Check for a specific one.
59/// if !books.contains("The Winds of Winter") {
60///     println!("We have {} books, but The Winds of Winter ain't one.",
61///              books.len());
62/// }
63///
64/// // Remove a book.
65/// books.remove("The Odyssey");
66///
67/// // Iterate over everything.
68/// for book in &books {
69///     println!("{book}");
70/// }
71/// ```
72///
73/// A `BTreeSet` with a known list of items can be initialized from an array:
74///
75/// ```
76/// use wt_indexset::BTreeSet;
77///
78/// let set = BTreeSet::from_iter([1, 2, 3]);
79/// ```
80#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
81#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
82pub struct BTreeSet<T>
83where
84    T: Ord,
85{
86    inner: Vec<Node<T>>,
87    index: FenwickTree<usize>,
88    node_capacity: usize,
89    len: usize,
90}
91
92impl<T: Ord> BTreeSet<T> {
93    /// Makes a new, empty `BTreeSet` with maximum node size 1024. Allocates one vec of capacity 1024.
94    ///
95    /// Note that this does not mean that the maximum number of items is 1024.
96    ///
97    /// In case you would like to make a tree with a different maximum node size, use the
98    /// `with_maximum_node_size` method.
99    ///
100    /// # Examples
101    ///
102    /// ```
103    /// # #![allow(unused_mut)]
104    /// use wt_indexset::BTreeSet;
105    ///
106    /// let mut set: BTreeSet<i32> = BTreeSet::new();
107    /// ```
108    pub fn new() -> Self {
109        Self {
110            ..Default::default()
111        }
112    }
113    /// Makes a new, empty `BTreeSet` with the given maximum node size. Allocates one vec with
114    /// the capacity set to be the specified node size.
115    ///
116    /// # Examples
117    ///
118    /// ```
119    /// # #![allow(unused_mut)]
120    /// use wt_indexset::BTreeSet;
121    ///
122    /// let mut set: BTreeSet<i32> = BTreeSet::with_maximum_node_size(128);
123    pub fn with_maximum_node_size(maximum_node_size: usize) -> Self {
124        let mut new: Self = Default::default();
125        new.inner = vec![Node::with_capacity(maximum_node_size)];
126        new.node_capacity = maximum_node_size;
127
128        new
129    }
130    /// Clears the set, removing all elements.
131    ///
132    /// # Examples
133    ///
134    /// ```
135    /// use wt_indexset::BTreeSet;
136    ///
137    /// let mut v = BTreeSet::new();
138    /// v.insert(1);
139    /// v.clear();
140    /// assert!(v.is_empty());
141    /// ```
142    pub fn clear(&mut self) {
143        self.inner = vec![Node::with_capacity(self.node_capacity)];
144        self.index = FenwickTree::from_iter(vec![0]);
145        self.len = 0;
146    }
147    fn locate_node<Q>(&self, value: &Q) -> usize
148    where
149        T: Borrow<Q>,
150        Q: Ord + ?Sized,
151    {
152        let mut node_idx = self.inner.partition_point(|node| {
153            if let Some(&max) = node.last().as_ref() {
154                return max.borrow() < value;
155            };
156
157            false
158        });
159
160        // When value is greater than all elements inside inner[node_idx], then len
161        // of inner[node_idx], which is not a valid place for insertion, is returned. It will
162        // never return less than 0, so it is only necessary to check whether it is out of bounds
163        // from the right
164        if self.inner.get(node_idx).is_none() {
165            node_idx -= 1
166        }
167
168        node_idx
169    }
170    fn locate_node_cmp<P, Q>(&self, mut cmp: P) -> usize
171    where
172        T: Borrow<Q>,
173        Q: Ord + ?Sized,
174        P: FnMut(&Q) -> bool,
175    {
176        let mut node_idx = self.inner.partition_point(|node| {
177            if let Some(max) = node.last() {
178                return cmp(max.borrow());
179            }
180
181            true
182        });
183
184        if self.inner.get(node_idx).is_none() {
185            node_idx -= 1
186        }
187
188        node_idx
189    }
190    fn locate_value<Q>(&self, value: &Q) -> (usize, usize)
191    where
192        T: Borrow<Q>,
193        Q: Ord + ?Sized,
194    {
195        let node_idx = self.locate_node(value);
196        let position_within_node =
197            self.inner[node_idx].partition_point(|item| item.borrow() < value);
198
199        (node_idx, position_within_node)
200    }
201    fn locate_value_cmp<P, Q>(&self, mut cmp: P) -> (usize, usize)
202    where
203        T: Borrow<Q>,
204        Q: Ord + ?Sized,
205        P: FnMut(&Q) -> bool,
206    {
207        let node_idx = self.locate_node_cmp(&mut cmp);
208        let position_within_node = self.inner[node_idx].partition_point(|item| cmp(item.borrow()));
209
210        (node_idx, position_within_node)
211    }
212    fn locate_ith(&self, idx: usize) -> (usize, usize) {
213        let mut node_index = self.index.index_of(idx);
214        let mut offset = 0;
215
216        if node_index != 0 {
217            offset = self.index.prefix_sum(node_index, 0);
218        }
219
220        let mut position_within_node = idx - offset;
221        if let Some(node) = self.inner.get(node_index) {
222            if position_within_node == node.len() {
223                node_index += 1;
224                position_within_node = 0;
225            }
226        }
227
228        (node_index, position_within_node)
229    }
230    /// Returns a reference to the element in the i-th position of the set, if any.
231    ///
232    /// The value may be any borrowed form of the set's element type,
233    /// but the ordering on the borrowed form *must* match the
234    /// ordering on the element type.
235    ///
236    /// # Examples
237    ///
238    /// ```
239    /// use wt_indexset::BTreeSet;
240    ///
241    /// let set = BTreeSet::from_iter([1, 2, 3]);
242    /// assert_eq!(set.get_index(0), Some(&1));
243    /// assert_eq!(set.get_index(2), Some(&3));
244    /// assert_eq!(set.get_index(4), None);
245    /// ```
246    pub fn get_index(&self, idx: usize) -> Option<&T> {
247        let (node_idx, position_within_node) = self.locate_ith(idx);
248        if let Some(candidate_node) = self.inner.get(node_idx) {
249            return candidate_node.get(position_within_node);
250        }
251
252        None
253    }
254    fn get_mut_index(&mut self, index: usize) -> Option<&mut T> {
255        let (node_idx, position_within_node) = self.locate_ith(index);
256        if let Some(_) = self.inner.get(node_idx) {
257            return self.inner[node_idx].get_mut(position_within_node);
258        }
259
260        None
261    }
262    /// Returns a reference to the element in the set, if any, that is equal to
263    /// the value.
264    ///
265    /// The value may be any borrowed form of the set's element type,
266    /// but the ordering on the borrowed form *must* match the
267    /// ordering on the element type.
268    ///
269    /// # Examples
270    ///
271    /// ```
272    /// use wt_indexset::BTreeSet;
273    ///
274    /// let set = BTreeSet::from([1, 2, 3]);
275    /// assert_eq!(set.get(&2), Some(&2));
276    /// assert_eq!(set.get(&4), None);
277    /// ```
278    pub fn get<Q>(&self, value: &Q) -> Option<&T>
279    where
280        T: Borrow<Q> + Ord,
281        Q: Ord + ?Sized,
282    {
283        let (node_idx, position_within_node) = self.locate_value(value);
284        if let Some(candidate_node) = self.inner.get(node_idx) {
285            return candidate_node.get(position_within_node);
286        }
287
288        None
289    }
290    /// Returns a reference to the first element in the set, if any, that is not less than the
291    /// input.
292    ///
293    /// The value may be any borrowed form of the set's element type,
294    /// but the ordering on the borrowed form *must* match the
295    /// ordering on the element type.
296    ///
297    /// # Examples
298    ///
299    /// ```
300    /// use wt_indexset::BTreeSet;
301    ///
302    /// let set = BTreeSet::from_iter([1, 2, 3, 5]);
303    /// assert_eq!(set.lower_bound(&2), Some(&2));
304    /// assert_eq!(set.lower_bound(&4), Some(&5));
305    /// ```
306    pub fn lower_bound<Q>(&self, value: &Q) -> Option<&T>
307    where
308        T: Borrow<Q>,
309        Q: Ord + ?Sized,
310    {
311        let (node_idx, position_within_node) = self.locate_value(value);
312        if let Some(candidate_node) = self.inner.get(node_idx) {
313            return candidate_node.get(position_within_node);
314        }
315
316        None
317    }
318    /// Returns the number of elements in the set.
319    ///
320    /// # Examples
321    ///
322    /// ```
323    /// use wt_indexset::BTreeSet;
324    ///
325    /// let mut v = BTreeSet::new();
326    /// assert_eq!(v.len(), 0);
327    /// v.insert(1);
328    /// assert_eq!(v.len(), 1);
329    /// ```
330    pub fn len(&self) -> usize {
331        self.len
332    }
333    /// Adds a value to the set.
334    ///
335    /// Returns whether the value was newly inserted. That is:
336    ///
337    /// - If the set did not previously contain an equal value, `true` is
338    ///   returned.
339    /// - If the set already contained an equal value, `false` is returned, and
340    ///   the entry is not updated.
341    ///
342    /// See the [module-level documentation] for more.
343    ///
344    /// [module-level documentation]: index.html#insert-and-complex-keys
345    ///
346    /// # Examples
347    ///
348    /// ```
349    /// use wt_indexset::BTreeSet;
350    ///
351    /// let mut set = BTreeSet::new();
352    ///
353    /// assert_eq!(set.insert(2), true);
354    /// assert_eq!(set.insert(2), false);
355    /// assert_eq!(set.len(), 1);
356    /// ```
357    pub fn insert(&mut self, value: T) -> bool {
358        let node_idx = self.locate_node(&value);
359        if self.inner[node_idx].len() == self.node_capacity {
360            let new_node = self.inner[node_idx].halve();
361            let mut insert_node_idx = node_idx;
362            if value >= new_node[0] {
363                insert_node_idx += 1;
364            }
365
366            self.inner.insert(node_idx + 1, new_node);
367            if NodeLike::insert(&mut self.inner[insert_node_idx], value).0 {
368                // Reconstruct the index after the new node and inner value inserts.
369                self.index = FenwickTree::from_iter(self.inner.iter().map(|node| node.len()));
370                self.len += 1;
371
372                true
373            } else {
374                // Reconstruct the index after the new node insert even if the new value wasn't added.
375                self.index = FenwickTree::from_iter(self.inner.iter().map(|node| node.len()));
376                false
377            }
378        } else if NodeLike::insert(&mut self.inner[node_idx], value).0 {
379            self.index.add_at(node_idx, 1);
380            self.len += 1;
381
382            true
383        } else {
384            false
385        }
386    }
387
388    /// Adds a value to the set, replacing the existing element, if any, that is
389    /// equal to the value. Returns the replaced element.
390    ///
391    /// # Examples
392    ///
393    /// ```
394    /// use wt_indexset::BTreeSet;
395    ///
396    /// let mut set = BTreeSet::new();
397    /// set.insert(Vec::<i32>::new());
398    ///
399    /// assert_eq!(set.get(&[][..]).unwrap().capacity(), 0);
400    /// println!("{}", set.replace(Vec::with_capacity(10)).unwrap().capacity());
401    /// println!("{}", set.get(&[][..]).unwrap().capacity());
402    /// assert_eq!(set.get(&[][..]).unwrap().capacity(), 10);
403    /// ```
404    pub fn replace(&mut self, value: T) -> Option<T> {
405        let replaced_element = self.take(&value);
406        self.insert(value);
407
408        replaced_element
409    }
410    /// Returns `true` if the set contains an element equal to the value.
411    ///
412    /// The value may be any borrowed form of the set's element type,
413    /// but the ordering on the borrowed form *must* match the
414    /// ordering on the element type.
415    ///
416    /// # Examples
417    ///
418    /// ```
419    /// use wt_indexset::BTreeSet;
420    ///
421    /// let set = BTreeSet::from_iter([1, 2, 3]);
422    /// assert_eq!(set.contains(&1), true);
423    /// assert_eq!(set.contains(&4), false);
424    /// ```
425    pub fn contains<Q>(&self, value: &Q) -> bool
426    where
427        T: Borrow<Q>,
428        Q: Ord + ?Sized,
429    {
430        let (node_idx, position_within_node) = self.locate_value(value);
431        if let Some(candidate_node) = self.inner.get(node_idx) {
432            if let Some(candidate_value) = candidate_node.get(position_within_node) {
433                return value == candidate_value.borrow();
434            }
435        }
436
437        false
438    }
439    fn contains_cmp<P, Q, R>(&self, cmp: P, mut cmp2: R) -> bool
440    where
441        T: Borrow<Q>,
442        Q: Ord + ?Sized,
443        P: FnMut(&Q) -> bool,
444        R: FnMut(&Q) -> bool,
445    {
446        let (node_idx, position_within_node) = self.locate_value_cmp(cmp);
447        if let Some(candidate_node) = self.inner.get(node_idx) {
448            if let Some(candidate_value) = candidate_node.get(position_within_node) {
449                return cmp2(candidate_value.borrow());
450            }
451        }
452
453        false
454    }
455    fn delete_at(&mut self, node_idx: usize, position_within_node: usize) -> T {
456        let removal = self.inner[node_idx].remove(position_within_node);
457
458        let mut decrease_length = false;
459        // check whether the node has to be deleted
460        if self.inner[node_idx].len() == 0 {
461            // delete it as long as it is not the last remaining node
462            if self.inner.len() > 1 {
463                self.inner.remove(node_idx);
464                self.len -= 1;
465                self.index = FenwickTree::from_iter(self.inner.iter().map(|node| node.len()));
466            } else {
467                decrease_length = true;
468            }
469        } else {
470            decrease_length = true;
471        }
472
473        if decrease_length {
474            self.index.sub_at(node_idx, 1);
475            self.len -= 1;
476        }
477
478        removal
479    }
480    fn delete<Q>(&mut self, value: &Q) -> (Option<T>, bool)
481    where
482        T: Borrow<Q>,
483        Q: Ord + ?Sized,
484    {
485        let mut removed = false;
486        let mut removal = None;
487        let (node_idx, position_within_node) = self.locate_value(value);
488        if let Some(candidate_node) = self.inner.get(node_idx) {
489            if let Some(candidate_value) = candidate_node.get(position_within_node) {
490                if value == candidate_value.borrow() {
491                    removal = Some(self.delete_at(node_idx, position_within_node));
492                    removed = true;
493                }
494            }
495        }
496
497        (removal, removed)
498    }
499    fn delete_cmp<P, Q, R>(&mut self, cmp: P, mut cmp2: R) -> (Option<T>, bool)
500    where
501        T: Borrow<Q>,
502        Q: Ord + ?Sized,
503        P: FnMut(&Q) -> bool,
504        R: FnMut(&Q) -> bool,
505    {
506        let mut removed = false;
507        let mut removal = None;
508        let (node_idx, position_within_node) = self.locate_value_cmp(cmp);
509        if let Some(candidate_node) = self.inner.get(node_idx) {
510            if let Some(candidate_value) = candidate_node.get(position_within_node) {
511                if cmp2(candidate_value.borrow()) {
512                    removal = Some(self.delete_at(node_idx, position_within_node));
513                    removed = true;
514                }
515            }
516        }
517
518        (removal, removed)
519    }
520    /// If the set contains an element equal to the value, removes it from the
521    /// set and drops it. Returns whether such an element was present.
522    ///
523    /// The value may be any borrowed form of the set's element type,
524    /// but the ordering on the borrowed form *must* match the
525    /// ordering on the element type.
526    ///
527    /// # Examples
528    ///
529    /// ```
530    /// use wt_indexset::BTreeSet;
531    ///
532    /// let mut set = BTreeSet::new();
533    ///
534    /// set.insert(2);
535    /// assert_eq!(set.remove(&2), true);
536    /// assert_eq!(set.remove(&2), false);
537    /// ```
538    pub fn remove<Q>(&mut self, value: &Q) -> bool
539    where
540        T: Borrow<Q>,
541        Q: Ord + ?Sized,
542    {
543        self.delete(value).1
544    }
545    /// Removes and returns the element in the set, if any, that is equal to
546    /// the value.
547    ///
548    /// The value may be any borrowed form of the set's element type,
549    /// but the ordering on the borrowed form *must* match the
550    /// ordering on the element type.
551    ///
552    /// # Examples
553    ///
554    /// ```
555    /// use wt_indexset::BTreeSet;
556    ///
557    /// let mut set = BTreeSet::from_iter([1, 2, 3]);
558    /// assert_eq!(set.take(&2), Some(2));
559    /// assert_eq!(set.take(&2), None);
560    /// ```
561    pub fn take<Q>(&mut self, value: &Q) -> Option<T>
562    where
563        T: Borrow<Q>,
564        Q: Ord + ?Sized,
565    {
566        self.delete(value).0
567    }
568    /// Returns a reference to the first element in the set, if any.
569    /// This element is always the minimum of all elements in the set.
570    ///
571    /// # Examples
572    ///
573    /// Basic usage:
574    ///
575    /// ```
576    /// use wt_indexset::BTreeSet;
577    ///
578    /// let mut set = BTreeSet::new();
579    /// assert_eq!(set.first(), None);
580    /// set.insert(1);
581    /// assert_eq!(set.first(), Some(&1));
582    /// set.insert(2);
583    /// assert_eq!(set.first(), Some(&1));
584    /// ```
585    pub fn first(&self) -> Option<&T> {
586        if let Some(candidate_node) = self.inner.get(0) {
587            return candidate_node.get(0);
588        }
589
590        None
591    }
592    /// Returns a reference to the last element in the set, if any.
593    /// This element is always the maximum of all elements in the set.
594    ///
595    /// # Examples
596    ///
597    /// Basic usage:
598    ///
599    /// ```
600    /// use wt_indexset::BTreeSet;
601    ///
602    /// let mut set = BTreeSet::new();
603    /// assert_eq!(set.last(), None);
604    /// set.insert(1);
605    /// assert_eq!(set.last(), Some(&1));
606    /// set.insert(2);
607    /// assert_eq!(set.last(), Some(&2));
608    /// ```
609    pub fn last(&self) -> Option<&T> {
610        if let Some(candidate_node) = self.inner.get(self.inner.len() - 1) {
611            if candidate_node.len() > 0 {
612                return candidate_node.get(candidate_node.len() - 1);
613            }
614        }
615
616        None
617    }
618    /// Removes the first element from the set and returns it, if any.
619    /// The first element is always the minimum element in the set.
620    ///
621    /// # Examples
622    ///
623    /// ```
624    /// use wt_indexset::BTreeSet;
625    ///
626    /// let mut set = BTreeSet::new();
627    ///
628    /// set.insert(1);
629    /// while let Some(n) = set.pop_first() {
630    ///     assert_eq!(n, 1);
631    /// }
632    /// assert!(set.is_empty());
633    /// ```
634    pub fn pop_first(&mut self) -> Option<T> {
635        let (first_node_idx, first_position_within_node) = (0, 0);
636        if let Some(candidate_node) = self.inner.get(first_node_idx) {
637            if candidate_node.get(first_position_within_node).is_some() {
638                return Some(self.delete_at(first_node_idx, first_position_within_node));
639            }
640        }
641
642        None
643    }
644    /// Removes the i-th element from the set and returns it, if any.
645    ///
646    /// # Examples
647    ///
648    /// ```
649    /// use wt_indexset::BTreeSet;
650    ///
651    /// let mut set = BTreeSet::new();
652    ///
653    /// set.insert(1);
654    /// set.insert(2);
655    /// assert_eq!(set.pop_index(0), 1);
656    /// assert_eq!(set.pop_index(0), 2);
657    /// assert!(set.is_empty());
658    /// ```
659    pub fn pop_index(&mut self, idx: usize) -> T {
660        let (node_idx, position_within_node) = self.locate_ith(idx);
661
662        self.delete_at(node_idx, position_within_node)
663    }
664    /// Removes the last element from the set and returns it, if any.
665    /// The last element is always the maximum element in the set.
666    ///
667    /// # Examples
668    ///
669    /// ```
670    /// use wt_indexset::BTreeSet;
671    ///
672    /// let mut set = BTreeSet::new();
673    ///
674    /// set.insert(1);
675    /// while let Some(n) = set.pop_last() {
676    ///     assert_eq!(n, 1);
677    /// }
678    /// assert!(set.is_empty());
679    /// ```
680    pub fn pop_last(&mut self) -> Option<T> {
681        let last_node_idx = self.inner.len() - 1;
682        let mut last_position_within_node = self.inner[last_node_idx].len();
683        last_position_within_node = last_position_within_node.saturating_sub(1);
684
685        if let Some(candidate_node) = self.inner.get(last_node_idx) {
686            if candidate_node.get(last_position_within_node).is_some() {
687                return Some(self.delete_at(last_node_idx, last_position_within_node));
688            }
689        }
690
691        None
692    }
693    /// Returns `true` if the set contains no elements.
694    ///
695    /// # Examples
696    ///
697    /// ```
698    /// use wt_indexset::BTreeSet;
699    ///
700    /// let mut v = BTreeSet::new();
701    /// assert!(v.is_empty());
702    /// v.insert(1);
703    /// assert!(!v.is_empty());
704    /// ```
705    pub fn is_empty(&self) -> bool {
706        self.len() == 0
707    }
708    /// Returns `true` if the set is a subset of another,
709    /// i.e., `other` contains at least all the elements in `self`.
710    ///
711    /// # Examples
712    ///
713    /// ```
714    /// use wt_indexset::BTreeSet;
715    ///
716    /// let sup = BTreeSet::from_iter([1, 2, 3]);
717    /// let mut set = BTreeSet::new();
718    ///
719    /// assert_eq!(set.is_subset(&sup), true);
720    /// set.insert(2);
721    /// assert_eq!(set.is_subset(&sup), true);
722    /// set.insert(4);
723    /// assert_eq!(set.is_subset(&sup), false);
724    /// ```
725    pub fn is_subset(&self, other: &Self) -> bool {
726        if self.difference(other).next().is_some() {
727            return false;
728        }
729
730        true
731    }
732    /// Returns `true` if the set is a superset of another,
733    /// i.e., `self` contains at least all the elements in `other`.
734    ///
735    /// # Examples
736    ///
737    /// ```
738    /// use wt_indexset::BTreeSet;
739    ///
740    /// let sub = BTreeSet::from_iter([1, 2]);
741    /// let mut set = BTreeSet::new();
742    ///
743    /// assert_eq!(set.is_superset(&sub), false);
744    ///
745    /// set.insert(0);
746    /// set.insert(1);
747    /// assert_eq!(set.is_superset(&sub), false);
748    ///
749    /// set.insert(2);
750    /// assert_eq!(set.is_superset(&sub), true);
751    /// ```
752    pub fn is_superset(&self, other: &Self) -> bool {
753        if other.difference(self).next().is_some() {
754            return false;
755        }
756
757        true
758    }
759    /// Returns `true` if `self` has no elements in common with `other`.
760    /// This is equivalent to checking for an empty intersection.
761    ///
762    /// # Examples
763    ///
764    /// ```
765    /// use wt_indexset::BTreeSet;
766    ///
767    /// let a = BTreeSet::from_iter([1, 2, 3]);
768    /// let mut b = BTreeSet::new();
769    ///
770    /// assert_eq!(a.is_disjoint(&b), true);
771    /// b.insert(4);
772    /// assert_eq!(a.is_disjoint(&b), true);
773    /// b.insert(1);
774    /// assert_eq!(a.is_disjoint(&b), false);
775    /// ```
776    pub fn is_disjoint(&self, other: &Self) -> bool {
777        if self.intersection(other).next().is_some() {
778            return false;
779        }
780
781        true
782    }
783    /// Gets an iterator that visits the elements in the `BTreeSet` in ascending
784    /// order.
785    ///
786    /// # Examples
787    ///
788    /// ```
789    /// use wt_indexset::BTreeSet;
790    ///
791    /// let set = BTreeSet::from_iter([1, 2, 3]);
792    /// let mut set_iter = set.iter();
793    /// assert_eq!(set_iter.next(), Some(&1));
794    /// assert_eq!(set_iter.next(), Some(&2));
795    /// assert_eq!(set_iter.next(), Some(&3));
796    /// assert_eq!(set_iter.next(), None);
797    /// ```
798    ///
799    /// Values returned by the iterator are returned in ascending order:
800    ///
801    /// ```
802    /// use wt_indexset::BTreeSet;
803    ///
804    /// let set = BTreeSet::from_iter([3, 1, 2]);
805    /// let mut set_iter = set.iter();
806    /// assert_eq!(set_iter.next(), Some(&1));
807    /// assert_eq!(set_iter.next(), Some(&2));
808    /// assert_eq!(set_iter.next(), Some(&3));
809    /// assert_eq!(set_iter.next(), None);
810    /// ```
811    pub fn iter(&self) -> Iter<'_, T> {
812        Iter::new(self)
813    }
814    /// Visits the elements representing the union,
815    /// i.e., all the elements in `self` or `other`, without duplicates,
816    /// in ascending order.
817    ///
818    /// # Examples
819    ///
820    /// ```
821    /// use wt_indexset::BTreeSet;
822    ///
823    /// let mut a = BTreeSet::new();
824    /// a.insert(1);
825    ///
826    /// let mut b = BTreeSet::new();
827    /// b.insert(2);
828    ///
829    /// let union: Vec<_> = a.union(&b).cloned().collect();
830    /// assert_eq!(union, [1, 2]);
831    /// ```
832    pub fn union<'a>(&'a self, other: &'a Self) -> Union<'a, T> {
833        Union {
834            merge_iter: MergeIter {
835                start: true,
836                left_iter: self.iter(),
837                current_left: None,
838                right_iter: other.iter(),
839                current_right: None,
840            },
841        }
842    }
843    /// Visits the elements representing the difference,
844    /// i.e., the elements that are in `self` but not in `other`,
845    /// in ascending order.
846    ///
847    /// # Examples
848    ///
849    /// ```
850    /// use wt_indexset::BTreeSet;
851    ///
852    /// let mut a = BTreeSet::new();
853    /// a.insert(1);
854    /// a.insert(2);
855    ///
856    /// let mut b = BTreeSet::new();
857    /// b.insert(2);
858    /// b.insert(3);
859    ///
860    /// let diff: Vec<_> = a.difference(&b).cloned().collect();
861    /// assert_eq!(diff, [1]);
862    /// ```
863    pub fn difference<'a>(&'a self, other: &'a Self) -> Difference<'a, T> {
864        Difference {
865            merge_iter: MergeIter {
866                start: true,
867                left_iter: self.iter(),
868                current_left: None,
869                right_iter: other.iter(),
870                current_right: None,
871            },
872        }
873    }
874    /// Visits the elements representing the symmetric difference,
875    /// i.e., the elements that are in `self` or in `other` but not in both,
876    /// in ascending order.
877    ///
878    /// # Examples
879    ///
880    /// ```
881    /// use wt_indexset::BTreeSet;
882    ///
883    /// let mut a = BTreeSet::new();
884    /// a.insert(1);
885    /// a.insert(2);
886    ///
887    /// let mut b = BTreeSet::new();
888    /// b.insert(2);
889    /// b.insert(3);
890    ///
891    /// let sym_diff: Vec<_> = a.symmetric_difference(&b).cloned().collect();
892    /// assert_eq!(sym_diff, [1, 3]);
893    /// ```
894    pub fn symmetric_difference<'a>(&'a self, other: &'a Self) -> SymmetricDifference<'a, T> {
895        SymmetricDifference {
896            merge_iter: MergeIter {
897                start: true,
898                left_iter: self.iter(),
899                current_left: None,
900                right_iter: other.iter(),
901                current_right: None,
902            },
903        }
904    }
905    /// Visits the elements representing the intersection,
906    /// i.e., the elements that are both in `self` and `other`,
907    /// in ascending order.
908    ///
909    /// # Examples
910    ///
911    /// ```
912    /// use wt_indexset::BTreeSet;
913    ///
914    /// let mut a = BTreeSet::new();
915    /// a.insert(1);
916    /// a.insert(2);
917    ///
918    /// let mut b = BTreeSet::new();
919    /// b.insert(2);
920    /// b.insert(3);
921    ///
922    /// let intersection: Vec<_> = a.intersection(&b).cloned().collect();
923    /// assert_eq!(intersection, [2]);
924    /// ```
925    pub fn intersection<'a>(&'a self, other: &'a Self) -> Intersection<'a, T> {
926        Intersection {
927            merge_iter: MergeIter {
928                start: true,
929                left_iter: self.iter(),
930                current_left: None,
931                right_iter: other.iter(),
932                current_right: None,
933            },
934        }
935    }
936    /// Retains only the elements specified by the predicate.
937    ///
938    /// In other words, remove all elements `e` for which `f(&e)` returns `false`.
939    /// The elements are visited in ascending order.
940    ///
941    /// # Examples
942    ///
943    /// ```
944    /// use wt_indexset::BTreeSet;
945    ///
946    /// let mut set = BTreeSet::from_iter([1, 2, 3, 4, 5, 6]);
947    /// // Keep only the even numbers.
948    /// set.retain(|&k| k % 2 == 0);
949    /// assert!(set.iter().eq([2, 4, 6].iter()));
950    /// ```
951    pub fn retain<F, Q>(&mut self, mut f: F)
952    where
953        T: Borrow<Q>,
954        Q: Ord + ?Sized,
955        F: FnMut(&Q) -> bool,
956    {
957        let mut positions_to_delete = vec![];
958        for (node_idx, node) in self.inner.iter().enumerate() {
959            for (position_within_node, item) in node.iter().enumerate() {
960                if !f(item.borrow()) {
961                    positions_to_delete.push((node_idx, position_within_node));
962                }
963            }
964        }
965        positions_to_delete.reverse();
966
967        positions_to_delete
968            .into_iter()
969            .for_each(|(node_idx, position_within_node)| {
970                self.delete_at(node_idx, position_within_node);
971            })
972    }
973    fn split_off_cmp<P, Q>(&mut self, cmp: P) -> Self
974    where
975        T: Borrow<Q>,
976        Q: Ord + ?Sized,
977        P: FnMut(&Q) -> bool,
978    {
979        let (node_idx, position_within_node) = self.locate_value_cmp(cmp);
980        let first_node = self.inner[node_idx].split_off(position_within_node);
981        let mut remaining_nodes = vec![];
982        while self.inner.len() > node_idx + 1 {
983            remaining_nodes.push(self.inner.pop().unwrap());
984        }
985        remaining_nodes.reverse();
986        remaining_nodes.insert(0, first_node);
987        let mut latter_half = BTreeSet::default();
988        latter_half.len = remaining_nodes.iter().map(|node| node.len()).sum();
989        latter_half.inner = remaining_nodes;
990        latter_half.index = FenwickTree::from_iter(latter_half.inner.iter().map(|node| node.len()));
991
992        if self.inner[node_idx].len() == 0 && self.inner.len() > 1 {
993            self.inner.remove(node_idx);
994        }
995
996        self.index = FenwickTree::from_iter(self.inner.iter().map(|node| node.len()));
997        self.len = self.inner.iter().map(|node| node.len()).sum();
998
999        latter_half
1000    }
1001    /// Splits the collection into two at the value. Returns a new collection
1002    /// with all elements greater than or equal to the value.
1003    ///
1004    /// # Examples
1005    ///
1006    /// Basic usage:
1007    ///
1008    /// ```
1009    /// use wt_indexset::BTreeSet;
1010    ///
1011    /// let mut a = BTreeSet::new();
1012    /// a.insert(1);
1013    /// a.insert(2);
1014    /// a.insert(3);
1015    /// a.insert(17);
1016    /// a.insert(41);
1017    ///
1018    /// let b = a.split_off(&3);
1019    ///
1020    /// assert_eq!(a.len(), 2);
1021    /// assert_eq!(b.len(), 3);
1022    ///
1023    /// assert!(a.contains(&1));
1024    /// assert!(a.contains(&2));
1025    ///
1026    /// assert!(b.contains(&3));
1027    /// assert!(b.contains(&17));
1028    /// assert!(b.contains(&41));
1029    /// ```
1030    pub fn split_off<Q>(&mut self, value: &Q) -> Self
1031    where
1032        T: Borrow<Q>,
1033        Q: Ord + ?Sized,
1034    {
1035        let (node_idx, position_within_node) = self.locate_value(value);
1036        let first_node = self.inner[node_idx].split_off(position_within_node);
1037        let mut remaining_nodes = vec![];
1038        while self.inner.len() > node_idx + 1 {
1039            remaining_nodes.push(self.inner.pop().unwrap());
1040        }
1041        remaining_nodes.reverse();
1042        remaining_nodes.insert(0, first_node);
1043        let mut latter_half = BTreeSet::default();
1044        latter_half.len = remaining_nodes.iter().map(|node| node.len()).sum();
1045        latter_half.inner = remaining_nodes;
1046        latter_half.index = FenwickTree::from_iter(latter_half.inner.iter().map(|node| node.len()));
1047
1048        if self.inner[node_idx].len() == 0 && self.inner.len() > 1 {
1049            self.inner.remove(node_idx);
1050        }
1051
1052        self.index = FenwickTree::from_iter(self.inner.iter().map(|node| node.len()));
1053        self.len = self.inner.iter().map(|node| node.len()).sum();
1054
1055        latter_half
1056    }
1057    /// Moves all elements from `other` into `self`, leaving `other` empty.
1058    ///
1059    /// # Examples
1060    ///
1061    /// ```
1062    /// use wt_indexset::BTreeSet;
1063    ///
1064    /// let mut a = BTreeSet::new();
1065    /// a.insert(1);
1066    /// a.insert(2);
1067    /// a.insert(3);
1068    ///
1069    /// let mut b = BTreeSet::new();
1070    /// b.insert(3);
1071    /// b.insert(4);
1072    /// b.insert(5);
1073    ///
1074    /// a.append(&mut b);
1075    ///
1076    /// assert_eq!(a.len(), 5);
1077    /// assert_eq!(b.len(), 0);
1078    ///
1079    /// assert!(a.contains(&1));
1080    /// assert!(a.contains(&2));
1081    /// assert!(a.contains(&3));
1082    /// assert!(a.contains(&4));
1083    /// assert!(a.contains(&5));
1084    /// ```
1085    pub fn append(&mut self, other: &mut Self) {
1086        while let Some(value) = other.pop_first() {
1087            self.replace(value);
1088        }
1089    }
1090    fn resolve_range<R>(&self, range: R) -> ((usize, usize, usize), (usize, usize, usize))
1091    where
1092        R: RangeBounds<usize>,
1093    {
1094        let mut global_front_idx: usize = 0;
1095        let mut global_back_idx: usize =
1096            self.index.prefix_sum(self.inner.len(), 0).saturating_sub(1);
1097
1098        // Solving global indexes
1099        let start = range.start_bound();
1100        match start {
1101            Bound::Included(bound) => {
1102                global_front_idx = *bound;
1103            }
1104            Bound::Excluded(bound) => {
1105                global_front_idx = *bound + 1;
1106            }
1107            Bound::Unbounded => (),
1108        }
1109
1110        let end = range.end_bound();
1111        match end {
1112            Bound::Included(bound) => {
1113                global_back_idx = *bound;
1114            }
1115            Bound::Excluded(bound) => {
1116                global_back_idx = *bound - 1;
1117            }
1118            Bound::Unbounded => (),
1119        }
1120        // Figuring out nodes
1121        let (front_node_idx, front_start_idx) = self.locate_ith(global_front_idx);
1122        let (back_node_idx, back_start_idx) = self.locate_ith(global_back_idx);
1123
1124        (
1125            (global_front_idx, front_node_idx, front_start_idx),
1126            (global_back_idx, back_node_idx, back_start_idx),
1127        )
1128    }
1129    /// Constructs a double-ended iterator over a sub-range of elements in the set.
1130    /// The simplest way is to use the range syntax `min..max`, thus `range(min..max)` will
1131    /// yield elements from min (inclusive) to max (exclusive).
1132    /// The range may also be entered as `(Bound<T>, Bound<T>)`, so for example
1133    /// `range((Excluded(4), Included(10)))` will yield a left-exclusive, right-inclusive
1134    /// range from 4 to 10.
1135    ///
1136    /// # Panics
1137    ///
1138    /// Panics if range `start > end`.
1139    /// Panics if range `start == end` and both bounds are `Excluded`.
1140    ///
1141    /// # Examples
1142    ///
1143    /// ```
1144    /// use wt_indexset::BTreeSet;
1145    /// use std::ops::Bound::Included;
1146    ///
1147    /// let mut set = BTreeSet::new();
1148    /// set.insert(3);
1149    /// set.insert(5);
1150    /// set.insert(8);
1151    /// for &elem in set.range((Included(&4), Included(&8))) {
1152    ///     println!("{elem}");
1153    /// }
1154    /// assert_eq!(Some(&5), set.range(4..).next());
1155    /// ```
1156    pub fn range<R, Q>(&self, range: R) -> Range<'_, T>
1157    where
1158        Q: Ord + ?Sized,
1159        T: Borrow<Q>,
1160        R: RangeBounds<Q>,
1161    {
1162        let start_idx = match range.start_bound() {
1163            Bound::Included(bound) => self.rank(bound),
1164            Bound::Excluded(bound) => self.rank(bound) + 1,
1165            Bound::Unbounded => 0,
1166        };
1167        let end_idx = match range.end_bound() {
1168            Bound::Included(bound) => self.rank(bound),
1169            Bound::Excluded(bound) => self.rank(bound).saturating_sub(1),
1170            Bound::Unbounded => self.len().saturating_sub(1),
1171        };
1172
1173        self.range_idx(start_idx..=end_idx)
1174    }
1175    /// Returns the position in which the given element would fall in the already-existing sorted
1176    /// order.
1177    ///
1178    /// The value may be any borrowed form of the set's element type,
1179    /// but the ordering on the borrowed form *must* match the
1180    /// ordering on the element type.
1181    ///
1182    /// # Examples
1183    ///
1184    /// ```
1185    /// use wt_indexset::BTreeSet;
1186    ///
1187    /// let set = BTreeSet::from_iter([1, 2, 3]);
1188    /// assert_eq!(set.rank(&1), 0);
1189    /// assert_eq!(set.rank(&3), 2);
1190    /// assert_eq!(set.rank(&4), 3);
1191    /// assert_eq!(set.rank(&100), 3);
1192    /// ```
1193    pub fn rank<Q>(&self, value: &Q) -> usize
1194    where
1195        Q: Ord + ?Sized,
1196        T: Borrow<Q>,
1197    {
1198        let (node_idx, position_within_node) = self.locate_value(value);
1199
1200        let offset = self.index.prefix_sum(node_idx, 0);
1201
1202        offset + position_within_node
1203    }
1204    fn rank_cmp<Q, P>(&self, cmp: P) -> usize
1205    where
1206        T: Borrow<Q>,
1207        Q: Ord + ?Sized,
1208        P: FnMut(&Q) -> bool,
1209    {
1210        let (node_idx, position_within_node) = self.locate_value_cmp(cmp);
1211
1212        let offset = self.index.prefix_sum(node_idx, 0);
1213
1214        offset + position_within_node
1215    }
1216    pub fn range_idx<R>(&self, range: R) -> Range<'_, T>
1217    where
1218        R: RangeBounds<usize>,
1219    {
1220        let (
1221            (global_front_idx, front_node_idx, front_start_idx),
1222            (global_back_idx, back_node_idx, back_start_idx),
1223        ) = self.resolve_range(range);
1224
1225        let front_iter = if front_node_idx < self.inner.len() {
1226            Some(self.inner[front_node_idx][front_start_idx..].iter())
1227        } else {
1228            None
1229        };
1230
1231        let back_iter = if back_node_idx < self.inner.len() {
1232            Some(self.inner[back_node_idx][..=back_start_idx].iter())
1233        } else {
1234            None
1235        };
1236
1237        Range {
1238            spine_iter: Iter {
1239                btree: self,
1240                current_front_node_idx: front_node_idx,
1241                current_front_idx: global_front_idx,
1242                current_back_node_idx: back_node_idx,
1243                current_back_idx: global_back_idx + 1,
1244                current_front_iterator: front_iter,
1245                current_back_iterator: back_iter,
1246            },
1247        }
1248    }
1249}
1250
1251impl<T> FromIterator<T> for BTreeSet<T>
1252where
1253    T: Ord,
1254{
1255    fn from_iter<K: IntoIterator<Item = T>>(iter: K) -> Self {
1256        let mut btree = BTreeSet::new();
1257        iter.into_iter().for_each(|item| {
1258            btree.insert(item);
1259        });
1260
1261        btree
1262    }
1263}
1264
1265impl<T, const N: usize> From<[T; N]> for BTreeSet<T>
1266where
1267    T: Ord,
1268{
1269    fn from(value: [T; N]) -> Self {
1270        let mut btree: BTreeSet<T> = Default::default();
1271
1272        value.into_iter().for_each(|item| {
1273            btree.insert(item);
1274        });
1275
1276        btree
1277    }
1278}
1279
1280impl<T> Default for BTreeSet<T>
1281where
1282    T: Ord,
1283{
1284    fn default() -> Self {
1285        let node_capacity = DEFAULT_INNER_SIZE;
1286
1287        Self {
1288            inner: vec![Node::with_capacity(node_capacity)],
1289            index: FenwickTree::from_iter(vec![0]),
1290            node_capacity,
1291            len: 0,
1292        }
1293    }
1294}
1295
1296/// An iterator over the items of a `BTreeSet`.
1297///
1298/// This `struct` is created by the [`iter`] method on [`BTreeSet`].
1299/// See its documentation for more.
1300///
1301/// [`iter`]: BTreeSet::iter
1302pub struct Iter<'a, T>
1303where
1304    T: Ord,
1305{
1306    btree: &'a BTreeSet<T>,
1307    current_front_node_idx: usize,
1308    current_front_idx: usize,
1309    current_back_node_idx: usize,
1310    current_back_idx: usize,
1311    current_front_iterator: Option<std::slice::Iter<'a, T>>,
1312    current_back_iterator: Option<std::slice::Iter<'a, T>>,
1313}
1314
1315impl<'a, T> Iter<'a, T>
1316where
1317    T: Ord,
1318{
1319    pub fn new(btree: &'a BTreeSet<T>) -> Self {
1320        Self {
1321            btree,
1322            current_front_node_idx: 0,
1323            current_front_idx: 0,
1324            current_back_node_idx: btree.inner.len() - 1,
1325            current_back_idx: btree.len(),
1326            current_front_iterator: Some(btree.inner[0].iter()),
1327            current_back_iterator: Some(btree.inner[btree.inner.len() - 1].iter()),
1328        }
1329    }
1330}
1331
1332impl<'a, T> Iterator for Iter<'a, T>
1333where
1334    T: Ord,
1335{
1336    type Item = &'a T;
1337
1338    fn next(&mut self) -> Option<Self::Item> {
1339        if self.current_front_idx == self.current_back_idx {
1340            return None;
1341        }
1342        if let Some(value) = self.current_front_iterator.as_mut().and_then(|i| i.next()) {
1343            self.current_front_idx += 1;
1344            Some(value)
1345        } else {
1346            self.current_front_node_idx += 1;
1347            if self.current_front_node_idx >= self.btree.inner.len() {
1348                return None;
1349            }
1350            self.current_front_iterator =
1351                Some(self.btree.inner[self.current_front_node_idx].iter());
1352
1353            self.next()
1354        }
1355    }
1356}
1357
1358impl<'a, T> DoubleEndedIterator for Iter<'a, T>
1359where
1360    T: Ord,
1361{
1362    fn next_back(&mut self) -> Option<Self::Item> {
1363        if self.current_front_idx == self.current_back_idx {
1364            return None;
1365        }
1366        if let Some(value) = self
1367            .current_back_iterator
1368            .as_mut()
1369            .and_then(|i| i.next_back())
1370        {
1371            self.current_back_idx -= 1;
1372            Some(value)
1373        } else {
1374            if self.current_back_node_idx == 0 {
1375                return None;
1376            };
1377            self.current_back_node_idx -= 1;
1378            self.current_back_iterator = Some(self.btree.inner[self.current_back_node_idx].iter());
1379
1380            self.next_back()
1381        }
1382    }
1383}
1384
1385impl<'a, T> FusedIterator for Iter<'a, T> where T: Ord {}
1386
1387impl<'a, T> IntoIterator for &'a BTreeSet<T>
1388where
1389    T: Ord,
1390{
1391    type Item = &'a T;
1392
1393    type IntoIter = Iter<'a, T>;
1394
1395    fn into_iter(self) -> Self::IntoIter {
1396        Iter::new(self)
1397    }
1398}
1399
1400/// An owning iterator over the items of a `BTreeSet`.
1401///
1402/// This `struct` is created by the [`into_iter`] method on [`BTreeSet`]
1403/// (provided by the [`IntoIterator`] trait). See its documentation for more.
1404///
1405/// [`into_iter`]: BTreeSet#method.into_iter
1406pub struct IntoIter<T>
1407where
1408    T: Ord,
1409{
1410    btree: BTreeSet<T>,
1411}
1412
1413impl<T> Iterator for IntoIter<T>
1414where
1415    T: Ord,
1416{
1417    type Item = T;
1418
1419    fn next(&mut self) -> Option<Self::Item> {
1420        self.btree.pop_first()
1421    }
1422}
1423
1424impl<T> DoubleEndedIterator for IntoIter<T>
1425where
1426    T: Ord,
1427{
1428    fn next_back(&mut self) -> Option<Self::Item> {
1429        self.btree.pop_last()
1430    }
1431}
1432
1433impl<T> FusedIterator for IntoIter<T> where T: Ord {}
1434
1435impl<T> IntoIterator for BTreeSet<T>
1436where
1437    T: Ord,
1438{
1439    type Item = T;
1440
1441    type IntoIter = IntoIter<T>;
1442
1443    fn into_iter(self) -> Self::IntoIter {
1444        // This will never panic, since there always is at least one node in the btree
1445        IntoIter { btree: self }
1446    }
1447}
1448
1449struct MergeIter<'a, T>
1450where
1451    T: Ord,
1452{
1453    start: bool,
1454    left_iter: Iter<'a, T>,
1455    current_left: Option<&'a T>,
1456    right_iter: Iter<'a, T>,
1457    current_right: Option<&'a T>,
1458}
1459
1460impl<'a, T> Iterator for MergeIter<'a, T>
1461where
1462    T: Ord,
1463{
1464    type Item = (Option<&'a T>, Option<&'a T>);
1465    fn next(&mut self) -> Option<Self::Item> {
1466        if !self.start {
1467            if let Some(left) = self.current_left {
1468                if let Some(right) = self.current_right {
1469                    match left.cmp(right) {
1470                        Ordering::Less => {
1471                            self.current_left = self.left_iter.next();
1472                        }
1473                        Ordering::Equal => {
1474                            self.current_left = self.left_iter.next();
1475                            self.current_right = self.right_iter.next();
1476                        }
1477                        Ordering::Greater => {
1478                            self.current_right = self.right_iter.next();
1479                        }
1480                    }
1481                } else {
1482                    self.current_left = self.left_iter.next();
1483                }
1484            } else if let Some(_) = self.current_right {
1485                self.current_right = self.right_iter.next();
1486            } else {
1487                return None;
1488            }
1489        } else {
1490            self.current_left = self.left_iter.next();
1491            self.current_right = self.right_iter.next();
1492            self.start = false;
1493        }
1494
1495        Some((self.current_left, self.current_right))
1496    }
1497}
1498
1499/// A lazy iterator producing elements in the union of `BTreeSet`s.
1500///
1501/// This `struct` is created by the [`union`] method on [`BTreeSet`].
1502/// See its documentation for more.
1503///
1504/// [`union`]: BTreeSet::union
1505pub struct Union<'a, T>
1506where
1507    T: Ord,
1508{
1509    merge_iter: MergeIter<'a, T>,
1510}
1511
1512impl<'a, T> Iterator for Union<'a, T>
1513where
1514    T: Ord,
1515{
1516    type Item = &'a T;
1517
1518    fn next(&mut self) -> Option<Self::Item> {
1519        if let Some((current_left, current_right)) = self.merge_iter.next() {
1520            return match (current_left, current_right) {
1521                (Some(left), Some(right)) => {
1522                    if right < left {
1523                        Some(right)
1524                    } else {
1525                        Some(left)
1526                    }
1527                }
1528                (Some(left), None) => Some(left),
1529                (None, Some(right)) => Some(right),
1530                (None, None) => None,
1531            };
1532        }
1533
1534        None
1535    }
1536}
1537
1538impl<'a, T> FusedIterator for Union<'a, T> where T: Ord {}
1539
1540/// A lazy iterator producing elements in the difference of `BTreeSet`s.
1541///
1542/// This `struct` is created by the [`difference`] method on [`BTreeSet`].
1543/// See its documentation for more.
1544///
1545/// [`difference`]: BTreeSet::difference
1546pub struct Difference<'a, T>
1547where
1548    T: Ord,
1549{
1550    merge_iter: MergeIter<'a, T>,
1551}
1552
1553impl<'a, T> Iterator for Difference<'a, T>
1554where
1555    T: Ord,
1556{
1557    type Item = &'a T;
1558
1559    fn next(&mut self) -> Option<Self::Item> {
1560        loop {
1561            return if let Some((current_left, current_right)) = self.merge_iter.next() {
1562                match (current_left, current_right) {
1563                    (Some(left), Some(right)) => {
1564                        if left < right {
1565                            Some(left)
1566                        } else {
1567                            continue;
1568                        }
1569                    }
1570                    (Some(left), None) => Some(left),
1571                    (None, _) => None,
1572                }
1573            } else {
1574                None
1575            };
1576        }
1577    }
1578}
1579
1580impl<'a, T> FusedIterator for Difference<'a, T> where T: Ord {}
1581
1582/// A lazy iterator producing elements in the symmetric difference of `BTreeSet`s.
1583///
1584/// This `struct` is created by the [`symmetric_difference`] method on
1585/// [`BTreeSet`]. See its documentation for more.
1586///
1587/// [`symmetric_difference`]: BTreeSet::symmetric_difference
1588pub struct SymmetricDifference<'a, T>
1589where
1590    T: Ord,
1591{
1592    merge_iter: MergeIter<'a, T>,
1593}
1594
1595impl<'a, T> Iterator for SymmetricDifference<'a, T>
1596where
1597    T: Ord,
1598{
1599    type Item = &'a T;
1600
1601    fn next(&mut self) -> Option<Self::Item> {
1602        loop {
1603            return if let Some((current_left, current_right)) = self.merge_iter.next() {
1604                match (current_left, current_right) {
1605                    (Some(left), Some(right)) => {
1606                        if left < right {
1607                            Some(left)
1608                        } else if right < left {
1609                            Some(right)
1610                        } else {
1611                            continue;
1612                        }
1613                    }
1614                    (Some(left), None) => Some(left),
1615                    (None, Some(right)) => Some(right),
1616                    (None, _) => None,
1617                }
1618            } else {
1619                None
1620            };
1621        }
1622    }
1623}
1624
1625impl<'a, T> FusedIterator for SymmetricDifference<'a, T> where T: Ord {}
1626
1627/// A lazy iterator producing elements in the intersection of `BTreeSet`s.
1628///
1629/// This `struct` is created by the [`intersection`] method on [`BTreeSet`].
1630/// See its documentation for more.
1631///
1632/// [`intersection`]: BTreeSet::intersection
1633pub struct Intersection<'a, T>
1634where
1635    T: Ord,
1636{
1637    merge_iter: MergeIter<'a, T>,
1638}
1639
1640impl<'a, T> Iterator for Intersection<'a, T>
1641where
1642    T: Ord,
1643{
1644    type Item = &'a T;
1645
1646    fn next(&mut self) -> Option<Self::Item> {
1647        loop {
1648            if let Some((current_left, current_right)) = self.merge_iter.next() {
1649                match (current_left, current_right) {
1650                    (Some(left), Some(right)) => {
1651                        if left == right {
1652                            return Some(left);
1653                        } else {
1654                            continue;
1655                        }
1656                    }
1657                    (None, _) | (_, None) => return None,
1658                }
1659            } else {
1660                return None;
1661            }
1662        }
1663    }
1664}
1665
1666impl<'a, T> FusedIterator for Intersection<'a, T> where T: Ord {}
1667
1668/// An iterator over a sub-range of items in a `BTreeSet`.
1669///
1670/// This `struct` is created by the [`range`] method on [`BTreeSet`].
1671/// See its documentation for more.
1672///
1673/// [`range`]: BTreeSet::range
1674pub struct Range<'a, T>
1675where
1676    T: Ord,
1677{
1678    spine_iter: Iter<'a, T>,
1679}
1680
1681impl<'a, T> Iterator for Range<'a, T>
1682where
1683    T: Ord,
1684{
1685    type Item = &'a T;
1686
1687    fn next(&mut self) -> Option<Self::Item> {
1688        self.spine_iter.next()
1689    }
1690}
1691
1692impl<'a, T> DoubleEndedIterator for Range<'a, T>
1693where
1694    T: Ord,
1695{
1696    fn next_back(&mut self) -> Option<Self::Item> {
1697        self.spine_iter.next_back()
1698    }
1699}
1700
1701impl<'a, T> FusedIterator for Range<'a, T> where T: Ord {}
1702
1703impl<T> Index<usize> for BTreeSet<T>
1704where
1705    T: Ord,
1706{
1707    type Output = T;
1708
1709    fn index(&self, index: usize) -> &Self::Output {
1710        self.get_index(index).unwrap()
1711    }
1712}
1713
1714pub struct VacantEntry<'a, K, V>
1715where
1716    K: Ord,
1717{
1718    map: &'a mut BTreeMap<K, V>,
1719    key: K,
1720}
1721
1722pub struct OccupiedEntry<'a, K, V>
1723where
1724    K: Ord,
1725{
1726    map: &'a mut BTreeMap<K, V>,
1727    idx: usize,
1728}
1729
1730pub enum Entry<'a, K, V>
1731where
1732    K: 'a + Ord,
1733    V: 'a,
1734{
1735    Vacant(VacantEntry<'a, K, V>),
1736    Occupied(OccupiedEntry<'a, K, V>),
1737}
1738
1739impl<'a, K, V> Entry<'a, K, V>
1740where
1741    K: 'a + Ord,
1742    V: 'a,
1743{
1744    pub fn or_insert(self, default: V) -> &'a mut V {
1745        match self {
1746            Vacant(entry) => entry.insert(default),
1747            Occupied(entry) => entry.into_mut(),
1748        }
1749    }
1750    pub fn or_insert_with<F>(self, default: F) -> &'a mut V
1751    where
1752        F: FnOnce() -> V,
1753    {
1754        match self {
1755            Vacant(entry) => entry.insert(default()),
1756            Occupied(entry) => entry.into_mut(),
1757        }
1758    }
1759    pub fn or_insert_with_key<F>(self, default: F) -> &'a mut V
1760    where
1761        F: FnOnce(&K) -> V,
1762    {
1763        match self {
1764            Vacant(entry) => {
1765                let value = default(entry.key());
1766                entry.insert(value)
1767            }
1768            Occupied(entry) => entry.into_mut(),
1769        }
1770    }
1771    pub fn key(&self) -> &K {
1772        match *self {
1773            Occupied(ref entry) => entry.key(),
1774            Vacant(ref entry) => entry.key(),
1775        }
1776    }
1777    pub fn and_modify<F>(self, f: F) -> Self
1778    where
1779        F: FnOnce(&mut V),
1780    {
1781        match self {
1782            Occupied(mut entry) => {
1783                f(entry.get_mut());
1784                Occupied(entry)
1785            }
1786            Vacant(entry) => Vacant(entry),
1787        }
1788    }
1789    pub fn or_default(self) -> &'a mut V
1790    where
1791        V: Default,
1792    {
1793        match self {
1794            Occupied(entry) => entry.into_mut(),
1795            Vacant(entry) => entry.insert(Default::default()),
1796        }
1797    }
1798}
1799
1800impl<'a, K, V> OccupiedEntry<'a, K, V>
1801where
1802    K: Ord,
1803{
1804    pub fn key(&self) -> &K {
1805        &self.map.set.get_index(self.idx).unwrap().key
1806    }
1807    pub fn remove_entry(self) -> (K, V) {
1808        self.map.pop_index(self.idx)
1809    }
1810    pub fn get(&self) -> &V {
1811        self.map.get_index(self.idx).unwrap().1
1812    }
1813    pub fn get_mut(&mut self) -> &mut V {
1814        self.map.get_mut_index(self.idx).unwrap()
1815    }
1816    pub fn into_mut(self) -> &'a mut V {
1817        self.map.get_mut_index(self.idx).unwrap()
1818    }
1819    pub fn insert(&mut self, value: V) -> V {
1820        let current_value = self.map.get_mut_index(self.idx).unwrap();
1821        let mut previous_value = value;
1822        swap(&mut previous_value, current_value);
1823
1824        previous_value
1825    }
1826    pub fn remove(self) -> V {
1827        self.map.pop_index(self.idx).1
1828    }
1829}
1830
1831impl<'a, K, V> VacantEntry<'a, K, V>
1832where
1833    K: Ord,
1834{
1835    pub fn key(&self) -> &K {
1836        &self.key
1837    }
1838    pub fn into_key(self) -> K {
1839        self.key
1840    }
1841    pub fn insert(self, value: V) -> &'a mut V {
1842        let rank = self
1843            .map
1844            .set
1845            .rank_cmp(|item: &Pair<K, V>| &item.key < &self.key);
1846        self.map.insert(self.key, value);
1847
1848        self.map.get_mut_index(rank).unwrap()
1849    }
1850}
1851
1852/// An ordered map based on a two-level [B-Tree].
1853///
1854/// B-Trees represent a fundamental compromise between cache-efficiency and actually minimizing
1855/// the amount of work performed in a search. In theory, a binary search tree (BST) is the optimal
1856/// choice for a sorted map, as a perfectly balanced BST performs the theoretical minimum amount of
1857/// comparisons necessary to find an element (log<sub>2</sub>n). However, in practice the way this
1858/// is done is *very* inefficient for modern computer architectures. In particular, every element
1859/// is stored in its own individually heap-allocated node. This means that every single insertion
1860/// triggers a heap-allocation, and every single comparison should be a cache-miss. Since these
1861/// are both notably expensive things to do in practice, we are forced to, at the very least,
1862/// reconsider the BST strategy.
1863///
1864/// However, B-Trees are not as performant as they could be, since there still is a significant
1865/// amount of pointer indirection, and, in Rust's case, a linear search on the node level.
1866///
1867/// Our implementation restricts a B-Tree to only have two levels, and have zero pointer indirection,
1868/// with data residing only in the second level. The first level is an array, sorted by each node's
1869/// maximum element. The second is where all the data is at, being a sorted array of sorted arrays of
1870/// fixed size, 1024. Lookups are done in two steps, one binary search over the first level, and one
1871/// over the second. This is significantly simpler than a regular B-Tree. The main tradeoff, is that
1872/// insertion and deletion relies on always having to sort an array of size 1024. In practice, this
1873/// is barely noticable, but still presents itself as a drawback significant enough to warrant considering
1874/// not using this crate. Please, read the Readme in order to see benchmarking results.
1875///
1876/// Furthermore, it has a very efficient get-the-ith-element implementation, that is thousands(literally)
1877/// of times faster than what is currently available in stdlib.
1878///
1879/// Iterators obtained from functions such as [`BTreeMap::iter`], [`BTreeMap::values`], or
1880/// [`BTreeMap::keys`] produce their items in order by key, and directly leverage Rust's own
1881/// slice iterators, therefore being as fast as possible.
1882///
1883/// [B-Tree]: https://en.wikipedia.org/wiki/B-tree
1884///
1885/// # Examples
1886///
1887/// ```
1888/// use wt_indexset::BTreeMap;
1889///
1890/// // type inference lets us omit an explicit type signature (which
1891/// // would be `BTreeMap<&str, &str>` in this example).
1892/// let mut movie_reviews = BTreeMap::new();
1893///
1894/// // review some movies.
1895/// movie_reviews.insert("Office Space",       "Deals with real issues in the workplace.");
1896/// movie_reviews.insert("Pulp Fiction",       "Masterpiece.");
1897/// movie_reviews.insert("The Godfather",      "Very enjoyable.");
1898/// movie_reviews.insert("The Blues Brothers", "Eye lyked it a lot.");
1899///
1900/// // check for a specific one.
1901/// if !movie_reviews.contains_key("Les Misérables") {
1902///     println!("We've got {} reviews, but Les Misérables ain't one.",
1903///              movie_reviews.len());
1904/// }
1905///
1906/// // oops, this review has a lot of spelling mistakes, let's delete it.
1907/// movie_reviews.remove("The Blues Brothers");
1908///
1909/// // look up the values associated with some keys.
1910/// let to_find = ["Up!", "Office Space"];
1911/// for movie in &to_find {
1912///     match movie_reviews.get(movie) {
1913///        Some(review) => println!("{movie}: {review}"),
1914///        None => println!("{movie} is unreviewed.")
1915///     }
1916/// }
1917///
1918/// // Look up the value for a key (will panic if the key is not found).
1919/// println!("Movie review: {}", movie_reviews["Office Space"]);
1920///
1921/// // iterate over everything.
1922/// for (movie, review) in &movie_reviews {
1923///     println!("{movie}: \"{review}\"");
1924/// }
1925/// ```
1926///
1927/// A `BTreeMap` with a known list of items can be initialized from an array:
1928///
1929/// ```
1930/// use wt_indexset::BTreeMap;
1931///
1932/// let solar_distance = BTreeMap::from_iter([
1933///     ("Mercury", 0.4),
1934///     ("Venus", 0.7),
1935///     ("Earth", 1.0),
1936///     ("Mars", 1.5),
1937/// ]);
1938/// ```
1939#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1940#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
1941pub struct BTreeMap<K, V>
1942where
1943    K: Ord,
1944{
1945    set: BTreeSet<Pair<K, V>>,
1946}
1947
1948impl<K: Ord, V> Default for BTreeMap<K, V>
1949where
1950    K: Ord,
1951{
1952    fn default() -> Self {
1953        Self {
1954            set: BTreeSet::default(),
1955        }
1956    }
1957}
1958
1959impl<K, V> FromIterator<(K, V)> for BTreeMap<K, V>
1960where
1961    K: Ord,
1962{
1963    fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> Self {
1964        let mut btree = BTreeMap::new();
1965        iter.into_iter().for_each(|item| {
1966            btree.insert(item.0, item.1);
1967        });
1968
1969        btree
1970    }
1971}
1972
1973impl<K: Ord, V> BTreeMap<K, V>
1974where
1975    K: Ord,
1976{
1977    /// Moves all elements from `other` into `self`, leaving `other` empty.
1978    ///
1979    /// If a key from `other` is already present in `self`, the respective
1980    /// value from `self` will be overwritten with the respective value from `other`.
1981    ///
1982    /// # Examples
1983    ///
1984    /// ```
1985    /// use wt_indexset::BTreeMap;
1986    ///
1987    /// let mut a = BTreeMap::new();
1988    /// a.insert(1, "a");
1989    /// a.insert(2, "b");
1990    /// a.insert(3, "c"); // Note: Key (3) also present in b.
1991    ///
1992    /// let mut b = BTreeMap::new();
1993    /// b.insert(3, "d"); // Note: Key (3) also present in a.
1994    /// b.insert(4, "e");
1995    /// b.insert(5, "f");
1996    ///
1997    /// a.append(&mut b);
1998    ///
1999    /// assert_eq!(a.len(), 5);
2000    /// assert_eq!(b.len(), 0);
2001    ///
2002    /// assert_eq!(a[&1], "a");
2003    /// assert_eq!(a[&2], "b");
2004    /// assert_eq!(a[&3], "d"); // Note: "c" has been overwritten.
2005    /// assert_eq!(a[&4], "e");
2006    /// assert_eq!(a[&5], "f");
2007    /// ```
2008    pub fn append(&mut self, other: &mut Self) {
2009        self.set.append(&mut other.set)
2010    }
2011    /// Clears the map, removing all elements.
2012    ///
2013    /// # Examples
2014    ///
2015    /// Basic usage:
2016    ///
2017    /// ```
2018    /// use wt_indexset::BTreeMap;
2019    ///
2020    /// let mut a = BTreeMap::new();
2021    /// a.insert(1, "a");
2022    /// a.clear();
2023    /// assert!(a.is_empty());
2024    /// ```
2025    pub fn clear(&mut self) {
2026        self.set.clear()
2027    }
2028    /// Returns `true` if the map contains a value for the specified key.
2029    ///
2030    /// The key may be any borrowed form of the map's key type, but the ordering
2031    /// on the borrowed form *must* match the ordering on the key type.
2032    ///
2033    /// # Examples
2034    ///
2035    /// Basic usage:
2036    ///
2037    /// ```
2038    /// use wt_indexset::BTreeMap;
2039    ///
2040    /// let mut map = BTreeMap::new();
2041    /// map.insert(1, "a");
2042    /// assert_eq!(map.contains_key(&1), true);
2043    /// assert_eq!(map.contains_key(&2), false);
2044    /// ```
2045    pub fn contains_key<Q>(&self, key: &Q) -> bool
2046    where
2047        K: Borrow<Q> + Ord,
2048        Q: Ord + ?Sized,
2049    {
2050        self.set.contains_cmp(
2051            |item: &Pair<K, V>| item.key.borrow() < key,
2052            |item| item.key.borrow() == key,
2053        )
2054    }
2055    /// Returns the first key-value pair in the map.
2056    /// The key in this pair is the minimum key in the map.
2057    ///
2058    /// # Examples
2059    ///
2060    /// Basic usage:
2061    ///
2062    /// ```
2063    /// use wt_indexset::BTreeMap;
2064    ///
2065    /// let mut map = BTreeMap::new();
2066    /// assert_eq!(map.first_key_value(), None);
2067    /// map.insert(1, "b");
2068    /// map.insert(2, "a");
2069    /// assert_eq!(map.first_key_value(), Some((&1, &"b")));
2070    /// ```
2071    pub fn first_key_value(&self) -> Option<(&K, &V)> {
2072        let popping = self.set.first();
2073        if let Some(pop) = popping {
2074            return Some((&pop.key, &pop.value));
2075        }
2076
2077        None
2078    }
2079    /// Returns a reference to the value corresponding to the key.
2080    ///
2081    /// The key may be any borrowed form of the map's key type, but the ordering
2082    /// on the borrowed form *must* match the ordering on the key type.
2083    ///
2084    /// # Examples
2085    ///
2086    /// Basic usage:
2087    ///
2088    /// ```
2089    /// use wt_indexset::BTreeMap;
2090    ///
2091    /// let mut map = BTreeMap::new();
2092    /// map.insert(1, "a");
2093    /// assert_eq!(map.get(&1), Some(&"a"));
2094    /// assert_eq!(map.get(&2), None);
2095    /// ```
2096    pub fn get<Q>(&self, key: &Q) -> Option<&V>
2097    where
2098        K: Borrow<Q> + Ord,
2099        Q: Ord + ?Sized,
2100    {
2101        if let Some(key_value) = self.get_key_value(key) {
2102            return Some(key_value.1);
2103        }
2104
2105        None
2106    }
2107    /// Returns the key-value pair currently residing at the given position.
2108    ///
2109    ///
2110    /// # Examples
2111    ///
2112    /// ```
2113    /// use wt_indexset::BTreeMap;
2114    ///
2115    /// let mut map = BTreeMap::new();
2116    /// map.insert(1, "a");
2117    /// assert_eq!(map.get_index(0), Some((&1, &"a")));
2118    /// assert_eq!(map.get_index(1), None);
2119    /// ```
2120    pub fn get_index(&self, idx: usize) -> Option<(&K, &V)> {
2121        let ith = self.set.get_index(idx);
2122        if let Some(entry) = ith {
2123            return Some((&entry.key, &entry.value));
2124        }
2125
2126        None
2127    }
2128    /// Returns the key-value pair corresponding to the supplied key.
2129    ///
2130    /// The supplied key may be any borrowed form of the map's key type, but the ordering
2131    /// on the borrowed form *must* match the ordering on the key type.
2132    ///
2133    /// # Examples
2134    ///
2135    /// ```
2136    /// use wt_indexset::BTreeMap;
2137    ///
2138    /// let mut map = BTreeMap::new();
2139    /// map.insert(1, "a");
2140    /// assert_eq!(map.get_key_value(&1), Some((&1, &"a")));
2141    /// assert_eq!(map.get_key_value(&2), None);
2142    /// ```
2143    pub fn get_key_value<Q>(&self, key: &Q) -> Option<(&K, &V)>
2144    where
2145        K: Borrow<Q> + Ord,
2146        Q: Ord + ?Sized,
2147    {
2148        let (node_idx, position_within_node) = self
2149            .set
2150            .locate_value_cmp(|item: &Pair<K, V>| item.key.borrow() < key);
2151        if let Some(candidate_node) = self.set.inner.get(node_idx) {
2152            if let Some(candidate_value) = candidate_node.get(position_within_node) {
2153                if candidate_value.key.borrow() == key {
2154                    return Some((&candidate_value.key, &candidate_value.value));
2155                }
2156            }
2157        }
2158
2159        None
2160    }
2161    /// Returns a mutable reference to the value corresponding to the key.
2162    ///
2163    /// The key may be any borrowed form of the map's key type, but the ordering
2164    /// on the borrowed form *must* match the ordering on the key type.
2165    ///
2166    /// # Examples
2167    ///
2168    /// Basic usage:
2169    ///
2170    /// ```
2171    /// use wt_indexset::BTreeMap;
2172    ///
2173    /// let mut map = BTreeMap::new();
2174    /// map.insert(1, "a");
2175    /// if let Some(x) = map.get_mut(&1) {
2176    ///     *x = "b";
2177    /// }
2178    /// assert_eq!(map[&1], "b");
2179    /// ```
2180    pub fn get_mut<Q>(&mut self, key: &Q) -> Option<&mut V>
2181    where
2182        K: Borrow<Q> + Ord,
2183        Q: Ord,
2184    {
2185        let (node_idx, position_within_node) = self
2186            .set
2187            .locate_value_cmp(|item: &Pair<K, V>| item.key.borrow() < key);
2188        if self.set.inner.get(node_idx).is_some()
2189            && self.set.inner[node_idx].get(position_within_node).is_some()
2190        {
2191            let entry = self.set.inner[node_idx].get_mut(position_within_node)?;
2192
2193            return Some(&mut entry.value);
2194        }
2195
2196        None
2197    }
2198    /// Returns a mutable reference to the value at the designated index
2199    ///
2200    /// # Examples
2201    ///
2202    /// Basic usage:
2203    ///
2204    /// ```
2205    /// use wt_indexset::BTreeMap;
2206    ///
2207    /// let mut map = BTreeMap::new();
2208    /// map.insert(1, "a");
2209    /// if let Some(x) = map.get_mut_index(0) {
2210    ///     *x = "b";
2211    /// }
2212    /// assert_eq!(map[&1], "b");
2213    /// ```
2214    pub fn get_mut_index(&mut self, index: usize) -> Option<&mut V> {
2215        if let Some(entry) = self.set.get_mut_index(index) {
2216            return Some(&mut entry.value);
2217        }
2218
2219        None
2220    }
2221    /// Inserts a key-value pair into the map.
2222    ///
2223    /// If the map did not have this key present, `None` is returned.
2224    ///
2225    /// If the map did have this key present, the value is updated, and the old
2226    /// value is returned. The key is not updated, though; this matters for
2227    /// types that can be `==` without being identical. See the [module-level
2228    /// documentation] for more.
2229    ///
2230    /// [module-level documentation]: index.html#insert-and-complex-keys
2231    ///
2232    /// # Examples
2233    ///
2234    /// Basic usage:
2235    ///
2236    /// ```
2237    /// use wt_indexset::BTreeMap;
2238    ///
2239    /// let mut map = BTreeMap::new();
2240    /// assert_eq!(map.insert(37, "a"), None);
2241    /// assert_eq!(map.is_empty(), false);
2242    ///
2243    /// map.insert(37, "b");
2244    /// assert_eq!(map.insert(37, "c"), Some("b"));
2245    /// assert_eq!(map[&37], "c");
2246    /// ```
2247    pub fn insert(&mut self, key: K, value: V) -> Option<V> {
2248        if self.contains_key(&key) {
2249            let old_entry = self
2250                .set
2251                .delete_cmp(|item: &Pair<K, V>| item.key < key, |item| item.key == key)
2252                .0?;
2253
2254            self.set.insert(Pair { key, value });
2255
2256            Some(old_entry.value)
2257        } else {
2258            self.set.insert(Pair { key, value });
2259
2260            None
2261        }
2262    }
2263    /// Creates a consuming iterator visiting all the keys, in sorted order.
2264    /// The map cannot be used after calling this.
2265    /// The iterator element type is `K`.
2266    ///
2267    /// # Examples
2268    ///
2269    /// ```
2270    /// use wt_indexset::BTreeMap;
2271    ///
2272    /// let mut a = BTreeMap::new();
2273    /// a.insert(2, "b");
2274    /// a.insert(1, "a");
2275    ///
2276    /// let keys: Vec<i32> = a.into_keys().collect();
2277    /// assert_eq!(keys, [1, 2]);
2278    /// ```
2279    pub fn into_keys(self) -> IntoKeys<K, V> {
2280        IntoKeys {
2281            inner: self.into_iter(),
2282        }
2283    }
2284    /// Creates a consuming iterator visiting all the values, in order by key.
2285    /// The map cannot be used after calling this.
2286    /// The iterator element type is `V`.
2287    ///
2288    /// # Examples
2289    ///
2290    /// ```
2291    /// use wt_indexset::BTreeMap;
2292    ///
2293    /// let mut a = BTreeMap::new();
2294    /// a.insert(1, "hello");
2295    /// a.insert(2, "goodbye");
2296    ///
2297    /// let values: Vec<&str> = a.into_values().collect();
2298    /// assert_eq!(values, ["hello", "goodbye"]);
2299    /// ```
2300    pub fn into_values(self) -> IntoValues<K, V> {
2301        IntoValues {
2302            inner: self.into_iter(),
2303        }
2304    }
2305    /// Returns `true` if the map contains no elements.
2306    ///
2307    /// # Examples
2308    ///
2309    /// Basic usage:
2310    ///
2311    /// ```
2312    /// use wt_indexset::BTreeMap;
2313    ///
2314    /// let mut a = BTreeMap::new();
2315    /// assert!(a.is_empty());
2316    /// a.insert(1, "a");
2317    /// assert!(!a.is_empty());
2318    /// ```
2319    pub fn is_empty(&self) -> bool {
2320        self.set.is_empty()
2321    }
2322    /// Gets an iterator over the entries of the map, sorted by key.
2323    ///
2324    /// # Examples
2325    ///
2326    /// Basic usage:
2327    ///
2328    /// ```
2329    /// use wt_indexset::BTreeMap;
2330    ///
2331    /// let mut map = BTreeMap::new();
2332    /// map.insert(3, "c");
2333    /// map.insert(2, "b");
2334    /// map.insert(1, "a");
2335    ///
2336    /// for (key, value) in map.iter() {
2337    ///     println!("{key}: {value}");
2338    /// }
2339    ///
2340    /// let (first_key, first_value) = map.iter().next().unwrap();
2341    /// assert_eq!((*first_key, *first_value), (1, "a"));
2342    /// ```
2343    pub fn iter(&self) -> IterMap<'_,K, V> {
2344        IterMap {
2345            inner: self.set.iter(),
2346        }
2347    }
2348    /// Gets a mutable iterator over the entries of the map, sorted by key.
2349    ///
2350    /// # Examples
2351    ///
2352    /// Basic usage:
2353    ///
2354    /// ```
2355    /// use wt_indexset::BTreeMap;
2356    ///
2357    /// let mut map = BTreeMap::from_iter([
2358    ///    ("a", 1),
2359    ///    ("b", 2),
2360    ///    ("c", 3),
2361    /// ]);
2362    ///
2363    /// // add 10 to the value if the key isn't "a"
2364    /// for (key, value) in map.iter_mut() {
2365    ///     if key != &"a" {
2366    ///         *value += 10;
2367    ///     }
2368    /// }
2369    /// ```
2370    pub fn iter_mut(&mut self) -> IterMut<'_,K, V> {
2371        let last_node_idx = self.set.inner.len() - 1;
2372        let len = self.set.len();
2373        let mut inner = self.set.inner.iter_mut();
2374        let front_iter = {
2375            if let Some(node) = inner.next() {
2376                node.iter_mut()
2377            } else {
2378                [].iter_mut()
2379            }
2380        };
2381        let back_iter = {
2382            if let Some(node) = inner.next_back() {
2383                node.iter_mut()
2384            } else {
2385                [].iter_mut()
2386            }
2387        };
2388
2389        IterMut {
2390            inner,
2391            current_front_node_idx: 0,
2392            current_front_idx: 0,
2393            current_back_node_idx: last_node_idx,
2394            current_back_idx: len - 1,
2395            current_front_iterator: front_iter,
2396            current_back_iterator: back_iter,
2397        }
2398    }
2399    /// Gets an iterator over the keys of the map, in sorted order.
2400    ///
2401    /// # Examples
2402    ///
2403    /// Basic usage:
2404    ///
2405    /// ```
2406    /// use wt_indexset::BTreeMap;
2407    ///
2408    /// let mut a = BTreeMap::new();
2409    /// a.insert(2, "b");
2410    /// a.insert(1, "a");
2411    ///
2412    /// let keys: Vec<_> = a.keys().cloned().collect();
2413    /// assert_eq!(keys, [1, 2]);
2414    /// ```
2415    pub fn keys(&self) -> Keys<'_, K, V> {
2416        Keys {
2417            inner: self.set.iter(),
2418        }
2419    }
2420    /// Returns the last key-value pair in the map.
2421    /// The key in this pair is the maximum key in the map.
2422    ///
2423    /// # Examples
2424    ///
2425    /// Basic usage:
2426    ///
2427    /// ```
2428    /// use wt_indexset::BTreeMap;
2429    ///
2430    /// let mut map = BTreeMap::new();
2431    /// map.insert(1, "b");
2432    /// map.insert(2, "a");
2433    /// assert_eq!(map.last_key_value(), Some((&2, &"a")));
2434    /// ```
2435    pub fn last_key_value(&self) -> Option<(&K, &V)> {
2436        let popping = self.set.last();
2437        if let Some(pop) = popping {
2438            return Some((&pop.key, &pop.value));
2439        }
2440
2441        None
2442    }
2443    /// Returns the number of elements in the map.
2444    ///
2445    /// # Examples
2446    ///
2447    /// Basic usage:
2448    ///
2449    /// ```
2450    /// use wt_indexset::BTreeMap;
2451    ///
2452    /// let mut a = BTreeMap::new();
2453    /// assert_eq!(a.len(), 0);
2454    /// a.insert(1, "a");
2455    /// assert_eq!(a.len(), 1);
2456    /// ```
2457    pub fn len(&self) -> usize {
2458        self.set.len()
2459    }
2460    /// Makes a new, empty `BTreeMap`.
2461    ///
2462    /// Allocates a vec of capacity 1024.
2463    ///
2464    /// # Examples
2465    ///
2466    /// Basic usage:
2467    ///
2468    /// ```
2469    /// use wt_indexset::BTreeMap;
2470    ///
2471    /// let mut map = BTreeMap::new();
2472    ///
2473    /// // entries can now be inserted into the empty map
2474    /// map.insert(1, "a");
2475    /// ```
2476    pub fn new() -> Self {
2477        Self {
2478            ..Default::default()
2479        }
2480    }
2481    /// Makes a new, empty `BTreeSet` with the given maximum node size. Allocates one vec with
2482    /// the capacity set to be the specified node size.
2483    ///
2484    /// # Examples
2485    ///
2486    /// ```
2487    /// # #![allow(unused_mut)]
2488    /// use wt_indexset::BTreeMap;
2489    ///
2490    /// let mut set: BTreeMap<usize, usize> = BTreeMap::with_maximum_node_size(128);
2491    pub fn with_maximum_node_size(maximum_node_size: usize) -> Self {
2492        Self {
2493            set: BTreeSet::with_maximum_node_size(maximum_node_size),
2494        }
2495    }
2496    /// Removes and returns the first element in the map.
2497    /// The key of this element is the minimum key that was in the map.
2498    ///
2499    /// # Examples
2500    ///
2501    /// Draining elements in ascending order, while keeping a usable map each iteration.
2502    ///
2503    /// ```
2504    /// use wt_indexset::BTreeMap;
2505    ///
2506    /// let mut map = BTreeMap::new();
2507    /// map.insert(1, "a");
2508    /// map.insert(2, "b");
2509    /// while let Some((key, _val)) = map.pop_first() {
2510    ///     assert!(map.iter().all(|(k, _v)| *k > key));
2511    /// }
2512    /// assert!(map.is_empty());
2513    /// ```
2514    pub fn pop_first(&mut self) -> Option<(K, V)> {
2515        let popping = self.set.pop_first();
2516        if let Some(pop) = popping {
2517            return Some((pop.key, pop.value));
2518        }
2519
2520        None
2521    }
2522    /// Removes the i-th element from the map and returns it, if any.
2523    ///
2524    /// # Examples
2525    ///
2526    /// ```
2527    /// use wt_indexset::BTreeMap;
2528    ///
2529    /// let mut map = BTreeMap::new();
2530    ///
2531    /// map.insert(1,"a");
2532    /// map.insert(2, "b");
2533    /// assert_eq!(map.pop_index(0), (1, "a"));
2534    /// assert_eq!(map.pop_index(0), (2, "b"));
2535    /// assert!(map.is_empty());
2536    /// ```
2537    pub fn pop_index(&mut self, index: usize) -> (K, V) {
2538        let popping = self.set.pop_index(index);
2539
2540        (popping.key, popping.value)
2541    }
2542    /// Removes and returns the last element in the map.
2543    /// The key of this element is the maximum key that was in the map.
2544    ///
2545    /// # Examples
2546    ///
2547    /// Draining elements in descending order, while keeping a usable map each iteration.
2548    ///
2549    /// ```
2550    /// use wt_indexset::BTreeMap;
2551    ///
2552    /// let mut map = BTreeMap::new();
2553    /// map.insert(1, "a");
2554    /// map.insert(2, "b");
2555    /// while let Some((key, _val)) = map.pop_last() {
2556    ///     assert!(map.iter().all(|(k, _v)| *k < key));
2557    /// }
2558    /// assert!(map.is_empty());
2559    /// ```
2560    pub fn pop_last(&mut self) -> Option<(K, V)> {
2561        let popping = self.set.pop_last();
2562        if let Some(pop) = popping {
2563            return Some((pop.key, pop.value));
2564        }
2565
2566        None
2567    }
2568    /// Constructs a double-ended iterator over a sub-range of elements in the map.
2569    /// The simplest way is to use the range syntax `min..max`, thus `range(min..max)` will
2570    /// yield elements from min (inclusive) to max (exclusive).
2571    /// The range may also be entered as `(Bound<T>, Bound<T>)`, so for example
2572    /// `range((Excluded(4), Included(10)))` will yield a left-exclusive, right-inclusive
2573    /// range from 4 to 10.
2574    ///
2575    /// # Panics
2576    ///
2577    /// Panics if range `start > end`.
2578    /// Panics if range `start == end` and both bounds are `Excluded`.
2579    ///
2580    /// # Examples
2581    ///
2582    /// Basic usage:
2583    ///
2584    /// ```
2585    /// use wt_indexset::BTreeMap;
2586    /// use std::ops::Bound::Included;
2587    ///
2588    /// let mut map = BTreeMap::new();
2589    /// map.insert(3, "a");
2590    /// map.insert(5, "b");
2591    /// map.insert(8, "c");
2592    /// for (&key, &value) in map.range((Included(&4), Included(&8))) {
2593    ///     println!("{key}: {value}");
2594    /// }
2595    /// assert_eq!(Some((&5, &"b")), map.range(4..).next());
2596    /// ```
2597    pub fn range<Q, R>(&self, range: R) -> RangeMap<'_, K, V>
2598    where
2599        Q: Ord + ?Sized,
2600        K: Borrow<Q>,
2601        R: RangeBounds<Q>,
2602    {
2603        let (start_idx, end_idx) = self.range_to_idx(range);
2604
2605        RangeMap {
2606            inner: self.set.range_idx(start_idx..=end_idx),
2607        }
2608    }
2609    pub fn range_idx<R>(&self, range: R) -> RangeMap<'_, K, V>
2610    where
2611        R: RangeBounds<usize>,
2612    {
2613        RangeMap {
2614            inner: self.set.range_idx(range),
2615        }
2616    }
2617    fn range_to_idx<Q, R>(&self, range: R) -> (usize, usize)
2618    where
2619        Q: Ord + ?Sized,
2620        K: Borrow<Q>,
2621        R: RangeBounds<Q>,
2622    {
2623        let start_idx = match range.start_bound() {
2624            Bound::Included(bound) => self
2625                .set
2626                .rank_cmp(|item: &Pair<K, V>| item.key.borrow() < bound),
2627            Bound::Excluded(bound) => {
2628                self.set
2629                    .rank_cmp(|item: &Pair<K, V>| item.key.borrow() < bound)
2630                    + 1
2631            }
2632            Bound::Unbounded => 0,
2633        };
2634        let end_idx = match range.end_bound() {
2635            Bound::Included(bound) => self
2636                .set
2637                .rank_cmp(|item: &Pair<K, V>| item.key.borrow() < bound),
2638            Bound::Excluded(bound) => {
2639                self.set
2640                    .rank_cmp(|item: &Pair<K, V>| item.key.borrow() < bound)
2641                    - 1
2642            }
2643            Bound::Unbounded => self.len() - 1,
2644        };
2645
2646        (start_idx, end_idx)
2647    }
2648    /// Constructs a mutable double-ended iterator over a sub-range of elements in the map.
2649    /// The simplest way is to use the range syntax `min..max`, thus `range(min..max)` will
2650    /// yield elements from min (inclusive) to max (exclusive).
2651    /// The range may also be entered as `(Bound<T>, Bound<T>)`, so for example
2652    /// `range((Excluded(4), Included(10)))` will yield a left-exclusive, right-inclusive
2653    /// range from 4 to 10.
2654    ///
2655    /// # Panics
2656    ///
2657    /// Panics if range `start > end`.
2658    /// Panics if range `start == end` and both bounds are `Excluded`.
2659    ///
2660    /// # Examples
2661    ///
2662    /// Basic usage:
2663    ///
2664    /// ```
2665    /// use wt_indexset::BTreeMap;
2666    ///
2667    /// let mut map: BTreeMap<&str, i32> =
2668    ///     [("Alice", 0), ("Bob", 0), ("Carol", 0), ("Cheryl", 0)].into();
2669    /// for (_, balance) in map.range_mut("B".."Cheryl") {
2670    ///     *balance += 100;
2671    /// }
2672    /// for (name, balance) in &map {
2673    ///     println!("{name} => {balance}");
2674    /// }
2675    /// ```
2676    pub fn range_mut<Q, R>(&mut self, range: R) -> RangeMut<'_, K, V>
2677    where
2678        Q: Ord + ?Sized,
2679        K: Borrow<Q>,
2680        R: RangeBounds<Q>,
2681    {
2682        let (start_idx, end_idx) = self.range_to_idx(range);
2683
2684        self.range_mut_idx(start_idx..=end_idx)
2685    }
2686    pub fn range_mut_idx<R>(&mut self, range: R) -> RangeMut<'_, K, V>
2687    where
2688        R: RangeBounds<usize>,
2689    {
2690        let (
2691            (global_front_idx, front_node_idx, front_start_idx),
2692            (global_back_idx, back_node_idx, back_start_idx),
2693        ) = self.set.resolve_range(range);
2694        let end = self.set.inner[back_node_idx].len();
2695
2696        let mut inner = self.set.inner.iter_mut();
2697
2698        let mut front_iter = {
2699            if let Some(node) = inner.nth(front_node_idx) {
2700                node.iter_mut()
2701            } else {
2702                [].iter_mut()
2703            }
2704        };
2705
2706        let mut back_iter = {
2707            if let Some(node) = inner.nth(back_node_idx - front_node_idx) {
2708                node.iter_mut()
2709            } else {
2710                [].iter_mut()
2711            }
2712        };
2713
2714        for _ in 0..front_start_idx {
2715            front_iter.next();
2716        }
2717        let offset = back_node_idx - front_node_idx;
2718        if offset > 0 {
2719            for _ in back_start_idx..end {
2720                back_iter.next_back();
2721            }
2722        } else {
2723            for _ in back_start_idx..end {
2724                front_iter.next_back();
2725            }
2726        }
2727
2728        RangeMut {
2729            inner: IterMut {
2730                inner,
2731                current_front_node_idx: front_node_idx,
2732                current_front_idx: global_front_idx,
2733                current_back_node_idx: back_node_idx,
2734                current_back_idx: global_back_idx,
2735                current_front_iterator: front_iter,
2736                current_back_iterator: back_iter,
2737            },
2738        }
2739    }
2740    /// Removes a key from the map, returning the value at the key if the key
2741    /// was previously in the map.
2742    ///
2743    /// The key may be any borrowed form of the map's key type, but the ordering
2744    /// on the borrowed form *must* match the ordering on the key type.
2745    ///
2746    /// # Examples
2747    ///
2748    /// Basic usage:
2749    ///
2750    /// ```
2751    /// use wt_indexset::BTreeMap;
2752    ///
2753    /// let mut map = BTreeMap::new();
2754    /// map.insert(1, "a");
2755    /// assert_eq!(map.remove(&1), Some("a"));
2756    /// assert_eq!(map.remove(&1), None);
2757    /// ```
2758    pub fn remove<Q>(&mut self, key: &Q) -> Option<V>
2759    where
2760        K: Borrow<Q> + Ord,
2761        Q: Ord + ?Sized,
2762    {
2763        let old_entry = self.set.delete_cmp(
2764            |item: &Pair<K, V>| item.key.borrow() < key,
2765            |item: &Pair<K, V>| item.key.borrow() == key,
2766        );
2767
2768        if old_entry.1 {
2769            return Some(old_entry.0?.value);
2770        }
2771
2772        None
2773    }
2774    /// Removes a key from the map, returning the stored key and value if the key
2775    /// was previously in the map.
2776    ///
2777    /// The key may be any borrowed form of the map's key type, but the ordering
2778    /// on the borrowed form *must* match the ordering on the key type.
2779    ///
2780    /// # Examples
2781    ///
2782    /// Basic usage:
2783    ///
2784    /// ```
2785    /// use wt_indexset::BTreeMap;
2786    ///
2787    /// let mut map = BTreeMap::new();
2788    /// map.insert(1, "a");
2789    /// assert_eq!(map.remove_entry(&1), Some((1, "a")));
2790    /// assert_eq!(map.remove_entry(&1), None);
2791    /// ```
2792    pub fn remove_entry<Q>(&mut self, key: &Q) -> Option<(K, V)>
2793    where
2794        K: Borrow<Q> + Ord,
2795        Q: Ord,
2796    {
2797        let old_entry = self.set.delete_cmp(
2798            |item: &Pair<K, V>| item.key.borrow() < key,
2799            |item| item.key.borrow() == key,
2800        );
2801
2802        if old_entry.1 {
2803            let key_value = old_entry.0?;
2804            return Some((key_value.key, key_value.value));
2805        }
2806
2807        None
2808    }
2809    /// Retains only the elements specified by the predicate.
2810    ///
2811    /// In other words, remove all pairs `(k, v)` for which `f(&k, &mut v)` returns `false`.
2812    /// The elements are visited in ascending key order.
2813    ///
2814    /// # Examples
2815    ///
2816    /// ```
2817    /// use wt_indexset::BTreeMap;
2818    ///
2819    /// let mut map: BTreeMap<i32, i32> = (0..8).map(|x| (x, x*10)).collect();
2820    /// // Keep only the elements with even-numbered keys.
2821    /// map.retain(|&k, _| k % 2 == 0);
2822    /// assert!(map.into_iter().eq(vec![(0, 0), (2, 20), (4, 40), (6, 60)]));
2823    /// ```
2824    pub fn retain<F, Q>(&mut self, mut f: F)
2825    where
2826        K: Borrow<Q> + Ord,
2827        Q: Ord,
2828        F: FnMut(&Q, &mut V) -> bool,
2829    {
2830        let mut positions_to_delete = vec![];
2831        for (node_idx, node) in self.set.inner.iter_mut().enumerate() {
2832            for (position_within_node, item) in node.iter_mut().enumerate() {
2833                if !f(item.key.borrow(), &mut item.value) {
2834                    positions_to_delete.push((node_idx, position_within_node));
2835                }
2836            }
2837        }
2838
2839        positions_to_delete.reverse();
2840
2841        positions_to_delete
2842            .into_iter()
2843            .for_each(|(node_idx, position_within_node)| {
2844                self.set.delete_at(node_idx, position_within_node);
2845            })
2846    }
2847    /// Splits the collection into two at the given key. Returns everything after the given key,
2848    /// including the key.
2849    ///
2850    /// # Examples
2851    ///
2852    /// Basic usage:
2853    ///
2854    /// ```
2855    /// use wt_indexset::BTreeMap;
2856    ///
2857    /// let mut a = BTreeMap::new();
2858    /// a.insert(1, "a");
2859    /// a.insert(2, "b");
2860    /// a.insert(3, "c");
2861    /// a.insert(17, "d");
2862    /// a.insert(41, "e");
2863    ///
2864    /// let b = a.split_off(&3);
2865    ///
2866    /// assert_eq!(a.len(), 2);
2867    /// assert_eq!(b.len(), 3);
2868    ///
2869    /// assert_eq!(a[&1], "a");
2870    /// assert_eq!(a[&2], "b");
2871    ///
2872    /// assert_eq!(b[&3], "c");
2873    /// assert_eq!(b[&17], "d");
2874    /// assert_eq!(b[&41], "e");
2875    /// ```
2876    pub fn split_off<Q>(&mut self, key: &Q) -> Self
2877    where
2878        K: Borrow<Q> + Ord,
2879        Q: Ord,
2880    {
2881        BTreeMap {
2882            set: self
2883                .set
2884                .split_off_cmp(|item: &Pair<K, V>| item.key.borrow() < key),
2885        }
2886    }
2887    /// Gets an iterator over the values of the map, in order by key.
2888    ///
2889    /// # Examples
2890    ///
2891    /// Basic usage:
2892    ///
2893    /// ```
2894    /// use wt_indexset::BTreeMap;
2895    ///
2896    /// let mut a = BTreeMap::new();
2897    /// a.insert(1, "hello");
2898    /// a.insert(2, "goodbye");
2899    ///
2900    /// let values: Vec<&str> = a.values().cloned().collect();
2901    /// assert_eq!(values, ["hello", "goodbye"]);
2902    /// ```
2903    pub fn values(&self) -> Values<'_, K, V> {
2904        Values {
2905            inner: self.set.iter(),
2906        }
2907    }
2908    /// Gets a mutable iterator over the values of the map, in order by key.
2909    ///
2910    /// # Examples
2911    ///
2912    /// Basic usage:
2913    ///
2914    /// ```
2915    /// use wt_indexset::BTreeMap;
2916    ///
2917    /// let mut a = BTreeMap::new();
2918    /// a.insert(1, String::from("hello"));
2919    /// a.insert(2, String::from("goodbye"));
2920    ///
2921    /// for value in a.values_mut() {
2922    ///     value.push_str("!");
2923    /// }
2924    ///
2925    /// let values: Vec<String> = a.values().cloned().collect();
2926    /// assert_eq!(values, [String::from("hello!"),
2927    ///                     String::from("goodbye!")]);
2928    /// ```
2929    pub fn values_mut(&mut self) -> ValuesMut<'_, K, V> {
2930        ValuesMut {
2931            inner: self.iter_mut(),
2932        }
2933    }
2934    /// Gets the given key's corresponding entry in the map for in-place manipulation.
2935    ///
2936    /// # Examples
2937    ///
2938    /// Basic usage:
2939    ///
2940    /// ```
2941    /// use std::collections::BTreeMap;
2942    ///
2943    /// let mut count: BTreeMap<&str, usize> = BTreeMap::new();
2944    ///
2945    /// // count the number of occurrences of letters in the vec
2946    /// for x in ["a", "b", "a", "c", "a", "b"] {
2947    ///     count.entry(x).and_modify(|curr| *curr += 1).or_insert(1);
2948    /// }
2949    ///
2950    /// assert_eq!(count["a"], 3);
2951    /// assert_eq!(count["b"], 2);
2952    /// assert_eq!(count["c"], 1);
2953    /// ```
2954    pub fn entry(&mut self, key: K) -> Entry<'_, K, V>
2955    where
2956        K: Ord,
2957    {
2958        if self.contains_key(&key) {
2959            let idx = self.set.rank_cmp(|item: &Pair<K, V>| item.key < key);
2960            return Occupied(OccupiedEntry { map: self, idx });
2961        }
2962
2963        Vacant(VacantEntry { map: self, key })
2964    }
2965    /// Returns the first entry in the map for in-place manipulation.
2966    /// The key of this entry is the minimum key in the map.
2967    ///
2968    /// # Examples
2969    ///
2970    /// ```
2971    /// use std::collections::BTreeMap;
2972    ///
2973    /// let mut map = BTreeMap::new();
2974    /// map.insert(1, "a");
2975    /// map.insert(2, "b");
2976    /// if let Some(mut entry) = map.first_entry() {
2977    ///     if *entry.key() > 0 {
2978    ///         entry.insert("first");
2979    ///     }
2980    /// }
2981    /// assert_eq!(*map.get(&1).unwrap(), "first");
2982    /// assert_eq!(*map.get(&2).unwrap(), "b");
2983    /// ```
2984    pub fn first_entry(&mut self) -> Option<OccupiedEntry<'_, K, V>>
2985    where
2986        K: Ord,
2987    {
2988        if !self.is_empty() {
2989            return Some(OccupiedEntry { map: self, idx: 0 });
2990        }
2991
2992        None
2993    }
2994    /// Returns the last entry in the map for in-place manipulation.
2995    /// The key of this entry is the maximum key in the map.
2996    ///
2997    /// # Examples
2998    ///
2999    /// ```
3000    /// use std::collections::BTreeMap;
3001    ///
3002    /// let mut map = BTreeMap::new();
3003    /// map.insert(1, "a");
3004    /// map.insert(2, "b");
3005    /// if let Some(mut entry) = map.last_entry() {
3006    ///     if *entry.key() > 0 {
3007    ///         entry.insert("last");
3008    ///     }
3009    /// }
3010    /// assert_eq!(*map.get(&1).unwrap(), "a");
3011    /// assert_eq!(*map.get(&2).unwrap(), "last");
3012    /// ```
3013    pub fn last_entry(&mut self) -> Option<OccupiedEntry<'_, K, V>>
3014    where
3015        K: Ord,
3016    {
3017        let len = self.len();
3018        if len > 0 {
3019            return Some(OccupiedEntry {
3020                map: self,
3021                idx: len - 1,
3022            });
3023        }
3024
3025        None
3026    }
3027    /// Returns a [`Cursor`] pointing at the first element that is above the
3028    /// given bound.
3029    ///
3030    /// If no such element exists then a cursor pointing at the "ghost"
3031    /// non-element is returned.
3032    ///
3033    /// Passing [`Bound::Unbounded`] will return a cursor pointing at the first
3034    /// element of the map.
3035    ///
3036    /// # Examples
3037    ///
3038    /// Basic usage:
3039    ///
3040    /// ```
3041    /// use wt_indexset::BTreeMap;
3042    /// use std::ops::Bound;
3043    ///
3044    /// let mut a = BTreeMap::new();
3045    /// a.insert(1, "a");
3046    /// a.insert(2, "b");
3047    /// a.insert(3, "c");
3048    /// a.insert(4, "c");
3049    /// let cursor = a.lower_bound(Bound::Excluded(&2));
3050    /// assert_eq!(cursor.key(), Some(&3));
3051    /// ```
3052    pub fn lower_bound<Q>(&self, bound: Bound<&Q>) -> CursorMap<'_, K, V>
3053    where
3054        K: Borrow<Q> + Ord,
3055        Q: Ord,
3056    {
3057        let start_idx = match bound {
3058            Bound::Included(start) => self
3059                .set
3060                .rank_cmp(|item: &Pair<K, V>| item.key.borrow() < start),
3061            Bound::Excluded(start) => {
3062                self.set
3063                    .rank_cmp(|item: &Pair<K, V>| item.key.borrow() < start)
3064                    + 1
3065            }
3066            Bound::Unbounded => 0,
3067        };
3068
3069        CursorMap {
3070            cursor: Cursor {
3071                set: &self.set,
3072                idx: start_idx,
3073            },
3074        }
3075    }
3076    /// Returns the position in which the given element would fall in the already-existing sorted
3077    /// order.
3078    ///
3079    /// The value may be any borrowed form of the set's element type,
3080    /// but the ordering on the borrowed form *must* match the
3081    /// ordering on the element type.
3082    ///
3083    /// # Examples
3084    ///
3085    /// ```
3086    /// use wt_indexset::BTreeMap;
3087    ///
3088    /// let set = BTreeMap::from_iter([(1, "a"), (2, "b"), (3, "c")]);
3089    /// assert_eq!(set.rank(&1), 0);
3090    /// assert_eq!(set.rank(&3), 2);
3091    /// assert_eq!(set.rank(&4), 3);
3092    /// assert_eq!(set.rank(&100), 3);
3093    /// ```
3094    pub fn rank<Q>(&self, value: &Q) -> usize
3095    where
3096        Q: Ord + ?Sized,
3097        K: Borrow<Q>,
3098    {
3099        self.set
3100            .rank_cmp(|item: &Pair<K, V>| item.key.borrow() < value)
3101    }
3102}
3103
3104impl<K, V, const N: usize> From<[(K, V); N]> for BTreeMap<K, V>
3105where
3106    K: Ord,
3107{
3108    fn from(value: [(K, V); N]) -> Self {
3109        let mut btree: BTreeMap<K, V> = Default::default();
3110
3111        value.into_iter().for_each(|(key, value)| {
3112            btree.insert(key, value);
3113        });
3114
3115        btree
3116    }
3117}
3118
3119impl<K, V> IntoIterator for BTreeMap<K, V>
3120where
3121    K: Ord,
3122{
3123    type Item = (K, V);
3124    type IntoIter = IntoIterMap<K, V>;
3125
3126    fn into_iter(self) -> Self::IntoIter {
3127        IntoIterMap {
3128            inner: self.set.into_iter(),
3129        }
3130    }
3131}
3132
3133impl<'a, K, V> IntoIterator for &'a BTreeMap<K, V>
3134where
3135    K: Ord,
3136{
3137    type Item = (&'a K, &'a V);
3138
3139    type IntoIter = IterMap<'a, K, V>;
3140
3141    fn into_iter(self) -> Self::IntoIter {
3142        IterMap {
3143            inner: self.set.iter(),
3144        }
3145    }
3146}
3147
3148/// An iterator over the entries of a `BTreeMap`.
3149///
3150/// This `struct` is created by the [`iter`] method on [`BTreeMap`]. See its
3151/// documentation for more.
3152///
3153/// [`iter`]: BTreeMap::iter
3154pub struct IterMap<'a, K, V>
3155where
3156    K: Ord,
3157{
3158    inner: Iter<'a, Pair<K, V>>,
3159}
3160
3161impl<'a, K, V> Iterator for IterMap<'a, K, V>
3162where
3163    K: Ord,
3164{
3165    type Item = (&'a K, &'a V);
3166
3167    fn next(&mut self) -> Option<Self::Item> {
3168        if let Some(entry) = self.inner.next() {
3169            return Some((&entry.key, &entry.value));
3170        }
3171
3172        None
3173    }
3174}
3175
3176impl<'a, K, V> DoubleEndedIterator for IterMap<'a, K, V>
3177where
3178    K: Ord,
3179{
3180    fn next_back(&mut self) -> Option<Self::Item> {
3181        if let Some(entry) = self.inner.next_back() {
3182            return Some((&entry.key, &entry.value));
3183        }
3184
3185        None
3186    }
3187}
3188
3189impl<'a, K, V> FusedIterator for IterMap<'a, K, V> where K: Ord {}
3190
3191/// An owning iterator over the entries of a `BTreeMap`.
3192///
3193/// This `struct` is created by the [`into_iter`] method on [`BTreeMap`]
3194/// (provided by the [`IntoIterator`] trait). See its documentation for more.
3195///
3196/// [`into_iter`]: IntoIterator::into_iter
3197pub struct IntoIterMap<K, V>
3198where
3199    K: Ord,
3200{
3201    inner: IntoIter<Pair<K, V>>,
3202}
3203
3204impl<K, V> Iterator for IntoIterMap<K, V>
3205where
3206    K: Ord,
3207{
3208    type Item = (K, V);
3209
3210    fn next(&mut self) -> Option<Self::Item> {
3211        if let Some(entry) = self.inner.next() {
3212            return Some((entry.key, entry.value));
3213        }
3214
3215        None
3216    }
3217}
3218
3219impl<K, V> DoubleEndedIterator for IntoIterMap<K, V>
3220where
3221    K: Ord,
3222{
3223    fn next_back(&mut self) -> Option<Self::Item> {
3224        if let Some(entry) = self.inner.next_back() {
3225            return Some((entry.key, entry.value));
3226        }
3227
3228        None
3229    }
3230}
3231
3232impl<K, V> FusedIterator for IntoIterMap<K, V> where K: Ord {}
3233
3234/// An owning iterator over the keys of a `BTreeMap`.
3235///
3236/// This `struct` is created by the [`into_keys`] method on [`BTreeMap`].
3237/// See its documentation for more.
3238///
3239/// [`into_keys`]: BTreeMap::into_keys
3240pub struct IntoKeys<K, V>
3241where
3242    K: Ord,
3243{
3244    inner: IntoIterMap<K, V>,
3245}
3246
3247impl<K, V> Iterator for IntoKeys<K, V>
3248where
3249    K: Ord,
3250{
3251    type Item = K;
3252
3253    fn next(&mut self) -> Option<Self::Item> {
3254        if let Some(entry) = self.inner.next() {
3255            return Some(entry.0);
3256        }
3257
3258        None
3259    }
3260}
3261
3262impl<K, V> DoubleEndedIterator for IntoKeys<K, V>
3263where
3264    K: Ord,
3265{
3266    fn next_back(&mut self) -> Option<Self::Item> {
3267        if let Some(entry) = self.inner.next_back() {
3268            return Some(entry.0);
3269        }
3270
3271        None
3272    }
3273}
3274
3275impl<K, V> FusedIterator for IntoKeys<K, V> where K: Ord {}
3276
3277/// An owning iterator over the values of a `BTreeMap`.
3278///
3279/// This `struct` is created by the [`into_values`] method on [`BTreeMap`].
3280/// See its documentation for more.
3281///
3282/// [`into_values`]: BTreeMap::into_values
3283pub struct IntoValues<K, V>
3284where
3285    K: Ord,
3286{
3287    inner: IntoIterMap<K, V>,
3288}
3289
3290impl<K, V> Iterator for IntoValues<K, V>
3291where
3292    K: Ord,
3293{
3294    type Item = V;
3295
3296    fn next(&mut self) -> Option<Self::Item> {
3297        if let Some(entry) = self.inner.next() {
3298            return Some(entry.1);
3299        }
3300
3301        None
3302    }
3303}
3304
3305impl<K, V> DoubleEndedIterator for IntoValues<K, V>
3306where
3307    K: Ord,
3308{
3309    fn next_back(&mut self) -> Option<Self::Item> {
3310        if let Some(entry) = self.inner.next_back() {
3311            return Some(entry.1);
3312        }
3313
3314        None
3315    }
3316}
3317
3318impl<K, V> FusedIterator for IntoValues<K, V> where K: Ord {}
3319
3320/// An iterator over a sub-range of entries in a `BTreeMap`.
3321///
3322/// This `struct` is created by the [`range`] method on [`BTreeMap`]. See its
3323/// documentation for more.
3324///
3325/// [`range`]: BTreeMap::range
3326pub struct RangeMap<'a, K, V>
3327where
3328    K: Ord,
3329{
3330    inner: Range<'a, Pair<K, V>>,
3331}
3332
3333impl<'a, K, V> Iterator for RangeMap<'a, K, V>
3334where
3335    K: Ord,
3336{
3337    type Item = (&'a K, &'a V);
3338
3339    fn next(&mut self) -> Option<Self::Item> {
3340        if let Some(entry) = self.inner.next() {
3341            return Some((&entry.key, &entry.value));
3342        }
3343
3344        None
3345    }
3346}
3347
3348impl<'a, K, V> DoubleEndedIterator for RangeMap<'a, K, V>
3349where
3350    K: Ord,
3351{
3352    fn next_back(&mut self) -> Option<Self::Item> {
3353        if let Some(entry) = self.inner.next_back() {
3354            return Some((&entry.key, &entry.value));
3355        }
3356
3357        None
3358    }
3359}
3360
3361impl<'a, K, V> FusedIterator for RangeMap<'a, K, V> where K: Ord {}
3362
3363/// An iterator over the values of a `BTreeMap`.
3364///
3365/// This `struct` is created by the [`values`] method on [`BTreeMap`]. See its
3366/// documentation for more.
3367///
3368/// [`values`]: BTreeMap::values
3369pub struct Values<'a, K, V>
3370where
3371    K: Ord,
3372{
3373    inner: Iter<'a, Pair<K, V>>,
3374}
3375
3376impl<'a, K, V> Iterator for Values<'a, K, V>
3377where
3378    K: Ord,
3379{
3380    type Item = &'a V;
3381
3382    fn next(&mut self) -> Option<Self::Item> {
3383        if let Some(entry) = self.inner.next() {
3384            return Some(&entry.value);
3385        }
3386
3387        None
3388    }
3389}
3390
3391impl<'a, K, V> DoubleEndedIterator for Values<'a, K, V>
3392where
3393    K: Ord,
3394{
3395    fn next_back(&mut self) -> Option<Self::Item> {
3396        if let Some(entry) = self.inner.next_back() {
3397            return Some(&entry.value);
3398        }
3399
3400        None
3401    }
3402}
3403
3404impl<'a, K, V> FusedIterator for Values<'a, K, V> where K: Ord {}
3405
3406/// An iterator over the keys of a `BTreeMap`.
3407///
3408/// This `struct` is created by the [`keys`] method on [`BTreeMap`]. See its
3409/// documentation for more.
3410///
3411/// [`keys`]: BTreeMap::keys
3412pub struct Keys<'a, K, V>
3413where
3414    K: Ord,
3415{
3416    inner: Iter<'a, Pair<K, V>>,
3417}
3418
3419impl<'a, K, V> Iterator for Keys<'a, K, V>
3420where
3421    K: Ord,
3422{
3423    type Item = &'a K;
3424
3425    fn next(&mut self) -> Option<Self::Item> {
3426        if let Some(entry) = self.inner.next() {
3427            return Some(&entry.key);
3428        }
3429
3430        None
3431    }
3432}
3433
3434impl<'a, K, V> DoubleEndedIterator for Keys<'a, K, V>
3435where
3436    K: Ord,
3437{
3438    fn next_back(&mut self) -> Option<Self::Item> {
3439        if let Some(entry) = self.inner.next_back() {
3440            return Some(&entry.key);
3441        }
3442
3443        None
3444    }
3445}
3446
3447impl<'a, K, V> FusedIterator for Keys<'a, K, V> where K: Ord {}
3448
3449/// A mutable iterator over the entries of a `BTreeMap`.
3450///
3451/// This `struct` is created by the [`iter_mut`] method on [`BTreeMap`]. See its
3452/// documentation for more.
3453///
3454/// [`iter_mut`]: BTreeMap::iter_mut
3455pub struct IterMut<'a, K: 'a, V: 'a>
3456where
3457    K: Ord,
3458{
3459    inner: std::slice::IterMut<'a, Node<Pair<K, V>>>,
3460    current_front_node_idx: usize,
3461    current_front_idx: usize,
3462    current_back_node_idx: usize,
3463    current_back_idx: usize,
3464    current_front_iterator: std::slice::IterMut<'a, Pair<K, V>>,
3465    current_back_iterator: std::slice::IterMut<'a, Pair<K, V>>,
3466}
3467
3468impl<'a, K, V> Iterator for IterMut<'a, K, V>
3469where
3470    K: Ord,
3471{
3472    type Item = (&'a K, &'a mut V);
3473
3474    fn next(&mut self) -> Option<Self::Item> {
3475        if self.current_front_idx == self.current_back_idx + 1 {
3476            return None;
3477        }
3478        if let Some(entry) = self.current_front_iterator.next() {
3479            self.current_front_idx += 1;
3480            return Some((&entry.key, &mut entry.value));
3481        } else {
3482            // If the current iterator has been exhausted, we have to check whether there are any
3483            // iterators left
3484            if self.current_front_node_idx == self.inner.size_hint().0 {
3485                return None;
3486            }
3487            if self.current_front_node_idx == self.current_back_node_idx - 1 {
3488                // take from the current back iter
3489                if let Some(entry) = self.current_back_iterator.next() {
3490                    self.current_front_idx += 1;
3491                    return Some((&entry.key, &mut entry.value));
3492                }
3493            } else {
3494                // advance front
3495                self.current_front_node_idx += 1;
3496                if let Some(node) = self.inner.next() {
3497                    self.current_front_iterator = node.iter_mut();
3498                }
3499
3500                return self.next();
3501            }
3502        };
3503
3504        None
3505    }
3506}
3507
3508impl<'a, K, V> DoubleEndedIterator for IterMut<'a, K, V>
3509where
3510    K: Ord,
3511{
3512    fn next_back(&mut self) -> Option<Self::Item> {
3513        if self.current_front_idx == self.current_back_idx + 1 {
3514            return None;
3515        }
3516        if let Some(entry) = self.current_back_iterator.next_back() {
3517            self.current_back_idx -= 1;
3518            return Some((&entry.key, &mut entry.value));
3519        } else {
3520            // If the current iterator has been exhausted, we have to check whether there are any
3521            // iterators left
3522            if self.current_back_node_idx == 0 {
3523                return None;
3524            }
3525            if self.current_front_node_idx == self.current_back_node_idx - 1 {
3526                // take from the current front iter
3527                if let Some(entry) = self.current_front_iterator.next_back() {
3528                    if self.current_back_idx > 0 {
3529                        self.current_back_idx -= 1;
3530                    }
3531                    return Some((&entry.key, &mut entry.value));
3532                }
3533            } else {
3534                // advance back
3535                self.current_back_node_idx -= 1;
3536                if let Some(node) = self.inner.next_back() {
3537                    self.current_back_iterator = node.iter_mut();
3538                }
3539
3540                return self.next_back();
3541            }
3542        };
3543
3544        None
3545    }
3546}
3547
3548impl<'a, K, V> FusedIterator for IterMut<'a, K, V> where K: Ord {}
3549
3550/// A mutable iterator over the values of a `BTreeMap`.
3551///
3552/// This `struct` is created by the [`values_mut`] method on [`BTreeMap`]. See its
3553/// documentation for more.
3554///
3555/// [`values_mut`]: BTreeMap::values_mut
3556pub struct ValuesMut<'a, K: 'a, V: 'a>
3557where
3558    K: Ord,
3559{
3560    inner: IterMut<'a, K, V>,
3561}
3562
3563impl<'a, K, V> Iterator for ValuesMut<'a, K, V>
3564where
3565    K: Ord,
3566{
3567    type Item = &'a mut V;
3568
3569    fn next(&mut self) -> Option<Self::Item> {
3570        if let Some(entry) = self.inner.next() {
3571            return Some(entry.1);
3572        }
3573
3574        None
3575    }
3576}
3577
3578impl<'a, K, V> DoubleEndedIterator for ValuesMut<'a, K, V>
3579where
3580    K: Ord,
3581{
3582    fn next_back(&mut self) -> Option<Self::Item> {
3583        if let Some(entry) = self.inner.next_back() {
3584            return Some(entry.1);
3585        }
3586
3587        None
3588    }
3589}
3590
3591impl<'a, K, V> FusedIterator for ValuesMut<'a, K, V> where K: Ord {}
3592
3593/// A mutable iterator over a sub-range of entries in a `BTreeMap`.
3594///
3595/// This `struct` is created by the [`range_mut`] method on [`BTreeMap`]. See its
3596/// documentation for more.
3597///
3598/// [`range_mut`]: BTreeMap::range_mut
3599pub struct RangeMut<'a, K: 'a, V: 'a>
3600where
3601    K: Ord,
3602{
3603    inner: IterMut<'a, K, V>,
3604}
3605
3606impl<'a, K, V> Iterator for RangeMut<'a, K, V>
3607where
3608    K: Ord,
3609{
3610    type Item = (&'a K, &'a mut V);
3611
3612    fn next(&mut self) -> Option<Self::Item> {
3613        self.inner.next()
3614    }
3615}
3616
3617impl<'a, K, V> DoubleEndedIterator for RangeMut<'a, K, V>
3618where
3619    K: Ord,
3620{
3621    fn next_back(&mut self) -> Option<Self::Item> {
3622        self.inner.next_back()
3623    }
3624}
3625
3626impl<'a, K, V> FusedIterator for RangeMut<'a, K, V> where K: Ord {}
3627
3628impl<K, Q, V> Index<&Q> for BTreeMap<K, V>
3629where
3630    K: Borrow<Q> + Ord,
3631
3632    Q: Ord + ?Sized,
3633{
3634    type Output = V;
3635
3636    fn index(&self, index: &Q) -> &Self::Output {
3637        self.get(index).unwrap()
3638    }
3639}
3640
3641pub struct Cursor<'a, T>
3642where
3643    T: Ord,
3644{
3645    set: &'a BTreeSet<T>,
3646    idx: usize,
3647}
3648
3649impl<'a, T: Ord> Cursor<'a, T> {
3650    pub fn move_next(&mut self) {
3651        if self.idx == self.set.len() {
3652            self.idx = 0
3653        } else {
3654            self.idx += 1;
3655        }
3656    }
3657    pub fn move_index(&mut self, index: usize) {
3658        self.idx = index
3659    }
3660    pub fn move_prev(&mut self) {
3661        if self.idx == 0 {
3662            self.idx = self.set.len()
3663        } else {
3664            self.idx -= 1;
3665        }
3666    }
3667    pub fn item(&self) -> Option<&'a T> {
3668        self.set.get_index(self.idx)
3669    }
3670    pub fn peek_next(&self) -> Option<&'a T> {
3671        if self.idx == self.set.len() {
3672            return self.set.first();
3673        }
3674
3675        self.set.get_index(self.idx + 1)
3676    }
3677    pub fn peek_index(&self, index: usize) -> Option<&'a T> {
3678        self.set.get_index(index)
3679    }
3680    pub fn peek_prev(&self) -> Option<&'a T> {
3681        if self.idx == 0 {
3682            return None;
3683        }
3684
3685        self.set.get_index(self.idx - 1)
3686    }
3687}
3688
3689pub struct CursorMap<'a, K, V>
3690where
3691    K: 'a + Ord,
3692    V: 'a,
3693{
3694    cursor: Cursor<'a, Pair<K, V>>,
3695}
3696
3697impl<'a, K: Ord, V> CursorMap<'a, K, V> {
3698    pub fn move_next(&mut self) {
3699        self.cursor.move_next()
3700    }
3701    pub fn move_index(&mut self, index: usize) {
3702        self.cursor.move_index(index)
3703    }
3704    pub fn move_prev(&mut self) {
3705        self.cursor.move_prev()
3706    }
3707    pub fn key(&self) -> Option<&'a K> {
3708        if let Some(entry) = self.cursor.item() {
3709            return Some(&entry.key);
3710        }
3711
3712        None
3713    }
3714    pub fn value(&self) -> Option<&'a V> {
3715        if let Some(entry) = self.cursor.item() {
3716            return Some(&entry.value);
3717        }
3718
3719        None
3720    }
3721    pub fn key_value(&self) -> Option<(&'a K, &'a V)> {
3722        if let Some(entry) = self.cursor.item() {
3723            return Some((&entry.key, &entry.value));
3724        }
3725
3726        None
3727    }
3728    pub fn peek_next(&self) -> Option<(&'a K, &'a V)> {
3729        if let Some(entry) = self.cursor.peek_next() {
3730            return Some((&entry.key, &entry.value));
3731        }
3732
3733        None
3734    }
3735    pub fn peek_index(&self, index: usize) -> Option<(&'a K, &'a V)> {
3736        if let Some(entry) = self.cursor.peek_index(index) {
3737            return Some((&entry.key, &entry.value));
3738        }
3739
3740        None
3741    }
3742    pub fn peek_prev(&self) -> Option<(&'a K, &'a V)> {
3743        if let Some(entry) = self.cursor.peek_prev() {
3744            return Some((&entry.key, &entry.value));
3745        }
3746
3747        None
3748    }
3749}
3750
3751#[cfg(test)]
3752mod tests {
3753    use super::core::constants::*;
3754    use super::core::node::*;
3755    use crate::{BTreeMap, BTreeSet, Node};
3756    use rand::{Rng, SeedableRng};
3757    use std::collections::Bound::Included;
3758
3759    #[test]
3760    fn test_insert() {
3761        let input: Vec<isize> = vec![1, 9, 2, 7, 6, 3, 5, 4, 10, 8];
3762
3763        let expected_output: Vec<isize> = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
3764
3765        let actual_node =
3766            input
3767                .iter()
3768                .fold(Node::with_capacity(DEFAULT_INNER_SIZE), |mut acc, curr| {
3769                    NodeLike::insert(&mut acc, *curr);
3770                    acc
3771                });
3772
3773        let actual_output: Vec<isize> = actual_node.iter().cloned().collect();
3774
3775        assert_eq!(expected_output, actual_output);
3776        assert_eq!(*actual_node.last().unwrap(), 10);
3777    }
3778
3779    #[test]
3780    fn test_halve() {
3781        let mut input: Vec<isize> = vec![];
3782        for item in 0..DEFAULT_INNER_SIZE {
3783            input.push(item.clone() as isize);
3784        }
3785
3786        let mut former_node = Node::with_capacity(DEFAULT_INNER_SIZE);
3787        input.iter().for_each(|item| {
3788            NodeLike::insert(&mut former_node, item.clone());
3789        });
3790        let latter_node = former_node.halve();
3791
3792        let expected_former_output: Vec<isize> = input[0..DEFAULT_CUTOFF].to_vec();
3793        let expected_latter_output: Vec<isize> = input[DEFAULT_CUTOFF..].to_vec();
3794
3795        let actual_former_output: Vec<isize> = former_node.iter().cloned().collect();
3796        let actual_latter_output: Vec<isize> = latter_node.iter().cloned().collect();
3797
3798        assert_eq!(expected_former_output, actual_former_output);
3799        assert_eq!(expected_latter_output, actual_latter_output);
3800    }
3801
3802    #[test]
3803    fn test_insert_btree() {
3804        // This will cause the btree to have at least more than one node
3805        let input: Vec<usize> = (0..(DEFAULT_INNER_SIZE + 1)).into_iter().rev().collect();
3806        let expected_output: Vec<usize> = (0..(DEFAULT_INNER_SIZE + 1)).collect();
3807
3808        let btree: BTreeSet<usize> = input.into_iter().fold(BTreeSet::new(), |mut acc, curr| {
3809            acc.insert(curr);
3810            acc
3811        });
3812        assert!(btree.inner.len() > 1);
3813
3814        let actual_output: Vec<usize> = btree.into_iter().collect();
3815
3816        assert_eq!(expected_output, actual_output);
3817    }
3818
3819    #[test]
3820    fn test_insert_duplicates() {
3821        let input: Vec<usize> = (0..(DEFAULT_INNER_SIZE + 1))
3822            .into_iter()
3823            .rev()
3824            .cycle()
3825            .take(DEFAULT_INNER_SIZE * 3)
3826            .collect();
3827        let expected_output: Vec<usize> = (0..(DEFAULT_INNER_SIZE + 1)).collect();
3828
3829        let btree: BTreeSet<usize> = input.into_iter().fold(BTreeSet::new(), |mut acc, curr| {
3830            acc.insert(curr);
3831            acc
3832        });
3833        assert!(btree.inner.len() > 1);
3834
3835        let actual_output: Vec<usize> = btree.into_iter().collect();
3836
3837        assert_eq!(expected_output.len(), actual_output.len());
3838        assert_eq!(expected_output, actual_output);
3839    }
3840
3841    #[test]
3842    fn test_remove() {
3843        let input: Vec<usize> = (0..(DEFAULT_INNER_SIZE + 1)).into_iter().collect();
3844
3845        let mut btree: BTreeSet<usize> = input.iter().fold(BTreeSet::new(), |mut acc, curr| {
3846            acc.insert(curr.clone());
3847            acc
3848        });
3849
3850        input.iter().for_each(|item| {
3851            assert!(btree.remove(item));
3852        });
3853
3854        let actual_output: Vec<usize> = btree.into_iter().collect();
3855        let expected_output: Vec<usize> = vec![];
3856
3857        assert_eq!(expected_output, actual_output);
3858    }
3859
3860    #[test]
3861    fn test_take() {
3862        let input: Vec<usize> = (0..(DEFAULT_INNER_SIZE + 1)).into_iter().collect();
3863
3864        let mut btree: BTreeSet<usize> = input.iter().fold(BTreeSet::new(), |mut acc, curr| {
3865            acc.insert(curr.clone());
3866            acc
3867        });
3868
3869        input.iter().for_each(|item| {
3870            assert_eq!(*item, btree.take(item).unwrap());
3871        });
3872
3873        let actual_output: Vec<usize> = btree.into_iter().collect();
3874        let expected_output: Vec<usize> = vec![];
3875
3876        assert_eq!(expected_output, actual_output);
3877    }
3878
3879    #[test]
3880    fn test_first_last_with_pop() {
3881        let input: Vec<usize> = (0..(DEFAULT_INNER_SIZE + 1)).into_iter().collect();
3882
3883        let btree: BTreeSet<usize> = input.iter().fold(BTreeSet::new(), |mut acc, curr| {
3884            acc.insert(curr.clone());
3885            acc
3886        });
3887
3888        let mut front_spine = btree.clone();
3889        let mut back_spine = btree.clone();
3890        btree.iter().for_each(|item| {
3891            if *item < DEFAULT_INNER_SIZE {
3892                assert_eq!(front_spine.get_index(0), front_spine.first());
3893                assert_eq!(
3894                    front_spine.pop_first().unwrap() + 1,
3895                    *front_spine.first().unwrap()
3896                );
3897            } else {
3898                assert_eq!(front_spine.pop_first().unwrap(), DEFAULT_INNER_SIZE);
3899                assert_eq!(front_spine.first(), None);
3900            }
3901        });
3902
3903        input.iter().rev().for_each(|item| {
3904            if *item > 0 {
3905                assert_eq!(
3906                    back_spine.get_index(back_spine.len() - 1),
3907                    back_spine.last()
3908                );
3909                assert_eq!(
3910                    back_spine.pop_last().unwrap() - 1,
3911                    *back_spine.last().unwrap()
3912                );
3913            } else {
3914                assert_eq!(back_spine.pop_last(), Some(0));
3915                assert_eq!(back_spine.last(), None);
3916            }
3917        });
3918    }
3919
3920    #[test]
3921    fn test_map_get() {
3922        let btree = BTreeMap::from_iter((0..(DEFAULT_INNER_SIZE * 10)).map(|i| (i, i)));
3923
3924        assert_eq!(btree.len(), DEFAULT_INNER_SIZE * 10);
3925
3926        for item in 0..DEFAULT_INNER_SIZE * 10 {
3927            assert_eq!(btree.get(&item), Some(&item));
3928        }
3929    }
3930
3931    #[test]
3932    fn test_get_contains_lower_bound() {
3933        let input: Vec<usize> = (0..(DEFAULT_INNER_SIZE + 1)).into_iter().rev().collect();
3934        let expected_output: Vec<usize> = (0..(DEFAULT_INNER_SIZE + 1)).collect();
3935
3936        let btree: BTreeSet<usize> = input.iter().fold(BTreeSet::new(), |mut acc, curr| {
3937            acc.insert(curr.clone());
3938            acc
3939        });
3940
3941        expected_output.into_iter().for_each(|item| {
3942            assert_eq!(*btree.get_index(item).unwrap(), item);
3943            assert_eq!(
3944                *btree.get_index(item).unwrap(),
3945                *btree.lower_bound(&item).unwrap()
3946            );
3947            assert!(btree.contains(&item));
3948        });
3949    }
3950
3951    #[test]
3952    fn test_iter() {
3953        let btree = BTreeSet::from_iter((0..(DEFAULT_INNER_SIZE * 10)).rev());
3954        assert_eq!(btree.inner.len(), 19);
3955        let expected_forward = Vec::from_iter(0..(DEFAULT_INNER_SIZE * 10));
3956        let actual_forward = Vec::from_iter(btree.iter().cloned());
3957        assert_eq!(expected_forward, actual_forward);
3958        let expected_backward = Vec::from_iter((0..(DEFAULT_INNER_SIZE * 10)).rev());
3959        let actual_backward = Vec::from_iter(btree.iter().cloned().rev());
3960        assert_eq!(expected_backward, actual_backward);
3961    }
3962
3963    #[test]
3964    fn test_iter_mut() {
3965        let btree = BTreeMap::from_iter((0..(DEFAULT_INNER_SIZE * 10)).enumerate().rev());
3966        assert_eq!(btree.set.inner.len(), 19);
3967        let expected_forward = Vec::from_iter((0..(DEFAULT_INNER_SIZE * 10)).enumerate());
3968        btree
3969            .clone()
3970            .iter_mut()
3971            .zip(expected_forward)
3972            .for_each(|(lhs, rhs)| {
3973                assert_eq!(*lhs.0, rhs.0);
3974                assert_eq!(*lhs.1, rhs.1);
3975            });
3976
3977        let expected_backward = Vec::from_iter((0..(DEFAULT_INNER_SIZE * 10)).enumerate().rev());
3978        btree
3979            .clone()
3980            .iter_mut()
3981            .rev()
3982            .zip(expected_backward)
3983            .for_each(|(lhs, rhs)| {
3984                assert_eq!(*lhs.0, rhs.0);
3985                assert_eq!(*lhs.1, rhs.1);
3986            });
3987    }
3988
3989    #[test]
3990    fn test_into_iter() {
3991        let btree = BTreeSet::from_iter((0..(DEFAULT_INNER_SIZE * 10)).rev());
3992        assert_eq!(btree.inner.len(), 19);
3993        let expected_forward = Vec::from_iter(0..(DEFAULT_INNER_SIZE * 10));
3994        let actual_forward = Vec::from_iter(btree.clone().into_iter());
3995        assert_eq!(expected_forward, actual_forward);
3996        let expected_backward = Vec::from_iter((0..(DEFAULT_INNER_SIZE * 10)).rev());
3997        let actual_backward = Vec::from_iter(btree.into_iter().rev());
3998        assert_eq!(expected_backward, actual_backward);
3999    }
4000
4001    #[test]
4002    fn test_range() {
4003        let btree = BTreeSet::from_iter(0..10);
4004        let first_to_second: Vec<usize> = (1..2).collect();
4005        let three_til_end: Vec<usize> = (3..10).collect();
4006        let start_til_four: Vec<usize> = (0..4).collect();
4007        let start_til_end: Vec<usize> = (0..10).collect();
4008        let five_til_six_included: Vec<usize> = (5..=6).collect();
4009        let start_til_seven_included: Vec<usize> = (0..=7).collect();
4010        assert_eq!(
4011            Vec::from_iter(btree.range_idx(..).cloned()),
4012            Vec::from_iter(btree.iter().cloned())
4013        );
4014        assert_eq!(
4015            Vec::from_iter(btree.range_idx(0..).cloned()),
4016            Vec::from_iter(btree.iter().cloned())
4017        );
4018        assert_eq!(
4019            Vec::from_iter(btree.range_idx(0..10).cloned()),
4020            Vec::from_iter(btree.iter().cloned())
4021        );
4022        assert_eq!(
4023            Vec::from_iter(btree.range_idx(..10).cloned()),
4024            Vec::from_iter(btree.iter().cloned())
4025        );
4026        assert_eq!(
4027            Vec::from_iter(btree.range_idx(1..2).cloned()),
4028            first_to_second
4029        );
4030        assert_eq!(
4031            Vec::from_iter(btree.range_idx(3..10).cloned()),
4032            three_til_end
4033        );
4034        assert_eq!(
4035            Vec::from_iter(btree.range_idx(0..4).cloned()),
4036            start_til_four
4037        );
4038        assert_eq!(
4039            Vec::from_iter(btree.range_idx(0..10).cloned()),
4040            start_til_end
4041        );
4042        assert_eq!(
4043            Vec::from_iter(btree.range_idx(5..=6).cloned()),
4044            five_til_six_included
4045        );
4046        assert_eq!(
4047            Vec::from_iter(btree.range_idx(0..=7).cloned()),
4048            start_til_seven_included
4049        );
4050    }
4051
4052    #[test]
4053    fn test_range_mut() {
4054        let btree = BTreeMap::from_iter((0..10).into_iter().enumerate());
4055        btree
4056            .clone()
4057            .range_mut_idx(..)
4058            .zip(btree.iter())
4059            .for_each(|(lhs, rhs)| {
4060                assert_eq!(lhs.0, rhs.0);
4061                assert_eq!(lhs.1, rhs.1);
4062            });
4063        btree
4064            .clone()
4065            .range_mut_idx(0..)
4066            .zip(btree.iter())
4067            .for_each(|(lhs, rhs)| {
4068                assert_eq!(lhs.0, rhs.0);
4069                assert_eq!(lhs.1, rhs.1);
4070            });
4071        btree
4072            .clone()
4073            .range_mut_idx(0..10)
4074            .zip(btree.iter())
4075            .for_each(|(lhs, rhs)| {
4076                assert_eq!(lhs.0, rhs.0);
4077                assert_eq!(lhs.1, rhs.1);
4078            });
4079        let first_to_second: Vec<(usize, usize)> = (1..2).map(|x| (x, x)).collect();
4080        let three_til_end: Vec<(usize, usize)> = (3..10).map(|x| (x, x)).collect();
4081        let start_til_four: Vec<(usize, usize)> = (0..4).map(|x| (x, x)).collect();
4082        let start_til_end: Vec<(usize, usize)> = (0..10).map(|x| (x, x)).collect();
4083        let five_til_six_included: Vec<(usize, usize)> = (5..=6).map(|x| (x, x)).collect();
4084        let start_til_seven_included: Vec<(usize, usize)> = (0..=7).map(|x| (x, x)).collect();
4085        btree
4086            .clone()
4087            .range_mut_idx(1..2)
4088            .zip(first_to_second)
4089            .for_each(|(lhs, rhs)| {
4090                assert_eq!(*lhs.0, rhs.0);
4091                assert_eq!(*lhs.1, rhs.1);
4092            });
4093        btree
4094            .clone()
4095            .range_mut_idx(3..10)
4096            .zip(three_til_end)
4097            .for_each(|(lhs, rhs)| {
4098                assert_eq!(*lhs.0, rhs.0);
4099                assert_eq!(*lhs.1, rhs.1);
4100            });
4101        btree
4102            .clone()
4103            .range_mut_idx(0..4)
4104            .zip(start_til_four)
4105            .for_each(|(lhs, rhs)| {
4106                assert_eq!(*lhs.0, rhs.0);
4107                assert_eq!(*lhs.1, rhs.1);
4108            });
4109        btree
4110            .clone()
4111            .range_mut_idx(0..10)
4112            .zip(start_til_end)
4113            .for_each(|(lhs, rhs)| {
4114                assert_eq!(*lhs.0, rhs.0);
4115                assert_eq!(*lhs.1, rhs.1);
4116            });
4117        btree
4118            .clone()
4119            .range_mut_idx(5..=6)
4120            .zip(five_til_six_included)
4121            .for_each(|(lhs, rhs)| {
4122                assert_eq!(*lhs.0, rhs.0);
4123                assert_eq!(*lhs.1, rhs.1);
4124            });
4125        btree
4126            .clone()
4127            .range_mut_idx(0..=7)
4128            .zip(start_til_seven_included)
4129            .for_each(|(lhs, rhs)| {
4130                assert_eq!(*lhs.0, rhs.0);
4131                assert_eq!(*lhs.1, rhs.1);
4132            });
4133    }
4134
4135    #[test]
4136    fn test_non_boolean_set_operations() {
4137        let left_spine = BTreeSet::from_iter((0..(DEFAULT_INNER_SIZE + 1)).into_iter());
4138        let right_spine = BTreeSet::from_iter(
4139            ((DEFAULT_INNER_SIZE - 1)..((DEFAULT_INNER_SIZE + 1) * 2)).into_iter(),
4140        );
4141
4142        let mut union = left_spine.clone();
4143        let mut temp_right_spine = right_spine.clone();
4144        union.append(&mut temp_right_spine);
4145
4146        assert_eq!(
4147            Vec::from_iter(union.iter().cloned()),
4148            Vec::from_iter(left_spine.union(&right_spine).cloned())
4149        );
4150        assert_eq!(
4151            Vec::from_iter(union.iter().cloned()),
4152            Vec::from_iter(right_spine.union(&left_spine).cloned()),
4153        );
4154
4155        let left_diff = Vec::from_iter(0..(DEFAULT_INNER_SIZE - 1));
4156        let right_diff = Vec::from_iter((DEFAULT_INNER_SIZE + 1)..((DEFAULT_INNER_SIZE + 1) * 2));
4157
4158        assert_eq!(
4159            left_diff,
4160            Vec::from_iter(left_spine.difference(&right_spine).cloned())
4161        );
4162        assert_eq!(
4163            right_diff,
4164            Vec::from_iter(right_spine.difference(&left_spine).cloned())
4165        );
4166
4167        let intersection = vec![DEFAULT_INNER_SIZE - 1, DEFAULT_INNER_SIZE];
4168        assert_eq!(
4169            intersection,
4170            Vec::from_iter(left_spine.intersection(&right_spine).cloned())
4171        );
4172
4173        let mut sym_diff = left_diff.clone();
4174        sym_diff.append(&mut right_diff.clone());
4175        assert_eq!(
4176            sym_diff,
4177            Vec::from_iter(left_spine.symmetric_difference(&right_spine).cloned())
4178        );
4179        assert_eq!(
4180            sym_diff,
4181            Vec::from_iter(right_spine.symmetric_difference(&left_spine).cloned())
4182        );
4183    }
4184
4185    #[test]
4186    fn test_boolean_set_operations() {
4187        let empty_set: BTreeSet<usize> = BTreeSet::new();
4188        assert!(empty_set.is_empty());
4189        let a = BTreeSet::from_iter((0..(DEFAULT_INNER_SIZE + 1)).into_iter());
4190        let b = BTreeSet::from_iter((0..(DEFAULT_INNER_SIZE + 2)).into_iter());
4191        let c =
4192            BTreeSet::from_iter(((DEFAULT_INNER_SIZE + 2)..(DEFAULT_INNER_SIZE + 4)).into_iter());
4193
4194        assert!(a.is_subset(&a));
4195        assert!(a.is_superset(&a));
4196        assert!(a.is_subset(&b));
4197        assert!(!b.is_subset(&a));
4198        assert!(b.is_superset(&a));
4199        assert!(c.is_disjoint(&a));
4200        assert!(c.is_disjoint(&b));
4201        assert!(!a.is_disjoint(&b));
4202        assert!(!b.is_disjoint(&a));
4203    }
4204
4205    #[test]
4206    fn test_split_off() {
4207        let btree: BTreeSet<usize> = BTreeSet::from_iter(0..(DEFAULT_INNER_SIZE * 10));
4208        for split in vec![
4209            1,
4210            (DEFAULT_INNER_SIZE * 3) - 6,
4211            DEFAULT_INNER_SIZE,
4212            DEFAULT_INNER_SIZE + 1,
4213            (DEFAULT_INNER_SIZE * 10) - 1,
4214        ] {
4215            let mut left = btree.clone();
4216            let right = left.split_off(&split);
4217            assert!(left.is_disjoint(&right));
4218            assert!(Vec::from_iter(left.intersection(&right)).is_empty());
4219            let expected_left = Vec::from_iter(0..split);
4220            let expected_right = Vec::from_iter(split..(DEFAULT_INNER_SIZE * 10));
4221
4222            assert_eq!(expected_left, Vec::from_iter(left));
4223            let actual_right = Vec::from_iter(right);
4224            assert_eq!(expected_right, actual_right)
4225        }
4226    }
4227
4228    #[test]
4229    fn test_out_of_bounds_range() {
4230        let btree: BTreeSet<usize> = BTreeSet::from_iter(0..10);
4231        assert_eq!(btree.range((Included(5), Included(10))).count(), 5);
4232        assert_eq!(btree.range((Included(5), Included(11))).count(), 5);
4233        assert_eq!(
4234            btree
4235                .range((Included(5), Included(10 + DEFAULT_INNER_SIZE)))
4236                .count(),
4237            5
4238        );
4239        assert_eq!(btree.range((Included(0), Included(11))).count(), 10);
4240    }
4241
4242    #[test]
4243    fn test_iterating_over_blocks() {
4244        let btree = BTreeSet::from_iter((0..(DEFAULT_INNER_SIZE + 10)).into_iter());
4245        assert_eq!(btree.iter().count(), (0..(DEFAULT_INNER_SIZE + 10)).count());
4246        assert_eq!(
4247            btree.range(0..DEFAULT_INNER_SIZE).count(),
4248            (0..DEFAULT_INNER_SIZE).count()
4249        );
4250        assert_eq!(
4251            btree.range(0..=DEFAULT_INNER_SIZE).count(),
4252            (0..=DEFAULT_INNER_SIZE).count()
4253        );
4254        assert_eq!(
4255            btree.range(0..=DEFAULT_INNER_SIZE + 1).count(),
4256            (0..=DEFAULT_INNER_SIZE + 1).count()
4257        );
4258
4259        assert_eq!(
4260            btree.iter().rev().count(),
4261            (0..(DEFAULT_INNER_SIZE + 10)).count()
4262        );
4263        assert_eq!(
4264            btree.range(0..DEFAULT_INNER_SIZE).rev().count(),
4265            (0..DEFAULT_INNER_SIZE).count()
4266        );
4267        assert_eq!(
4268            btree.range(0..=DEFAULT_INNER_SIZE).rev().count(),
4269            (0..=DEFAULT_INNER_SIZE).count()
4270        );
4271        assert_eq!(
4272            btree.range(0..=DEFAULT_INNER_SIZE + 1).rev().count(),
4273            (0..=DEFAULT_INNER_SIZE + 1).count()
4274        );
4275    }
4276
4277    #[test]
4278    fn test_empty_set() {
4279        let btree: BTreeSet<usize> = BTreeSet::new();
4280        assert_eq!(btree.iter().count(), 0);
4281        assert_eq!(btree.range(0..0).count(), 0);
4282        assert_eq!(btree.range(0..).count(), 0);
4283        assert_eq!(btree.range(..0).count(), 0);
4284        assert_eq!(btree.range(..).count(), 0);
4285        assert_eq!(btree.range(0..=0).count(), 0);
4286        assert_eq!(btree.range(..1).count(), 0);
4287
4288        assert_eq!(btree.iter().rev().count(), 0);
4289        assert_eq!(btree.range(0..0).rev().count(), 0);
4290        assert_eq!(btree.range(..).rev().count(), 0);
4291        assert_eq!(btree.range(..1).rev().count(), 0);
4292
4293        assert_eq!(btree.range(..DEFAULT_INNER_SIZE).count(), 0);
4294        assert_eq!(
4295            btree
4296                .range(DEFAULT_INNER_SIZE..DEFAULT_INNER_SIZE * 2)
4297                .count(),
4298            0
4299        );
4300    }
4301
4302    #[test]
4303    fn test_many_fuzzy_duplicates() {
4304        // The below seed reproduces a previous bug
4305        let mut rng = rand::rngs::StdRng::from_seed([41u8; 32]);
4306        let mut btree = BTreeSet::new();
4307        let n = 100_000;
4308        for _ in 0..n {
4309            let value: u64 = rng.random_range(1..10000);
4310            let lower: u64 = 1650;
4311            let len_before = btree.len();
4312            // Use max to increase the number of duplicates
4313            if btree.insert(value.max(lower)) {
4314                assert_eq!(btree.len(), len_before + 1)
4315            } else {
4316                assert_eq!(btree.len(), len_before);
4317            }
4318        }
4319        let expected = btree.iter().cloned().collect::<Vec<_>>();
4320        assert_eq!(expected.len(), btree.len());
4321        for (i, expected_item) in expected.iter().enumerate() {
4322            if let Some(item) = btree.get_index(i) {
4323                assert_eq!(expected_item, item, "mismatch on index {i}");
4324            } else {
4325                panic!("missing index {i}")
4326            }
4327        }
4328    }
4329}