scapegoat/
set.rs

1use core::borrow::Borrow;
2use core::fmt::{self, Debug};
3use core::iter::FromIterator;
4use core::ops::RangeBounds;
5use core::ops::{BitAnd, BitOr, BitXor, Sub};
6
7use crate::set_types::{
8    Difference, Intersection, IntoIter, Iter, Range, SymmetricDifference, Union,
9};
10use crate::tree::{SgError, SgTree};
11
12/// Safe, fallible, embedded-friendly ordered set.
13///
14/// ### Fallible APIs
15///
16/// * [`try_insert`][crate::set::SgSet::try_insert]
17/// * [`try_append`][crate::set::SgSet::try_append]
18/// * [`try_extend`][crate::set::SgSet::try_extend]
19/// * [`try_from_iter`][crate::set::SgSet::try_from_iter]
20/// * [`try_replace`][crate::set::SgSet::try_replace]
21///
22/// [`TryFrom`](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html) isn't implemented because it would collide with the blanket implementation.
23/// See [this open GitHub issue](https://github.com/rust-lang/rust/issues/50133#issuecomment-64690839) from 2018,
24/// this is a known Rust limitation that should be fixed via specialization in the future.
25///
26/// ### Attribution Note
27///
28/// The majority of API examples and descriptions are adapted or directly copied from the standard library's [`BTreeSet`](https://doc.rust-lang.org/std/collections/struct.BTreeSet.html).
29/// The goal is to offer embedded developers familiar, ergonomic APIs on resource constrained systems that otherwise don't get the luxury of dynamic collections.
30#[derive(Default, Clone, Hash, PartialEq, Eq, Ord, PartialOrd)]
31pub struct SgSet<T: Ord + Default, const N: usize> {
32    pub(crate) bst: SgTree<T, (), N>,
33}
34
35impl<T: Ord + Default, const N: usize> SgSet<T, N> {
36    /// Makes a new, empty `SgSet`.
37    ///
38    /// # Examples
39    ///
40    /// ```
41    /// use scapegoat::SgSet;
42    ///
43    /// let mut set: SgSet<i32, 10> = SgSet::new();
44    /// ```
45    pub fn new() -> Self {
46        SgSet { bst: SgTree::new() }
47    }
48
49    /// The [original scapegoat tree paper's](https://people.csail.mit.edu/rivest/pubs/GR93.pdf) alpha, `a`, can be chosen in the range `0.5 <= a < 1.0`.
50    /// `a` tunes how "aggressively" the data structure self-balances.
51    /// It controls the trade-off between total rebuild time and maximum height guarantees.
52    ///
53    /// * As `a` approaches `0.5`, the tree will rebalance more often. Ths means slower insertions, but faster lookups and deletions.
54    ///     * An `a` equal to `0.5` means a tree that always maintains a perfect balance (e.g."complete" binary tree, at all times).
55    ///
56    /// * As `a` approaches `1.0`, the tree will rebalance less often. This means quicker insertions, but slower lookups and deletions.
57    ///     * If `a` reached `1.0`, it'd mean a tree that never rebalances.
58    ///
59    /// Returns `Err` if `0.5 <= alpha_num / alpha_denom < 1.0` isn't `true` (invalid `a`, out of range).
60    ///
61    /// # Examples
62    ///
63    /// ```
64    /// use scapegoat::SgSet;
65    ///
66    /// let mut set: SgSet<isize, 10> = SgSet::new();
67    ///
68    /// // Set 2/3, e.g. `a = 0.666...` (it's default value).
69    /// assert!(set.set_rebal_param(2.0, 3.0).is_ok());
70    /// ```
71    #[doc(alias = "rebalance")]
72    #[doc(alias = "alpha")]
73    pub fn set_rebal_param(&mut self, alpha_num: f32, alpha_denom: f32) -> Result<(), SgError> {
74        self.bst.set_rebal_param(alpha_num, alpha_denom)
75    }
76
77    /// Get the current rebalance parameter, alpha, as a tuple of `(alpha_numerator, alpha_denominator)`.
78    /// See [the corresponding setter method][SgSet::set_rebal_param] for more details.
79    ///
80    /// # Examples
81    ///
82    /// ```
83    /// use scapegoat::SgSet;
84    ///
85    /// let mut set: SgSet<isize, 10> = SgSet::new();
86    ///
87    /// // Set 2/3, e.g. `a = 0.666...` (it's default value).
88    /// assert!(set.set_rebal_param(2.0, 3.0).is_ok());
89    ///
90    /// // Get the currently set value
91    /// assert_eq!(set.rebal_param(), (2.0, 3.0));
92    /// ```
93    #[doc(alias = "rebalance")]
94    #[doc(alias = "alpha")]
95    pub fn rebal_param(&self) -> (f32, f32) {
96        self.bst.rebal_param()
97    }
98
99    /// Total capacity, e.g. maximum number of set elements.
100    ///
101    /// # Examples
102    ///
103    /// ```
104    /// use scapegoat::SgSet;
105    ///
106    /// let mut set: SgSet<i32, 10> = SgSet::new();
107    ///
108    /// assert!(set.capacity() == 10)
109    /// ```
110    pub fn capacity(&self) -> usize {
111        self.bst.capacity()
112    }
113
114    /// Moves all elements from `other` into `self`, leaving `other` empty.
115    ///
116    /// # Examples
117    ///
118    /// ```
119    /// use scapegoat::SgSet;
120    ///
121    /// let mut a = SgSet::<_, 10>::new();
122    /// a.insert(1);
123    /// a.insert(2);
124    /// a.insert(3);
125    ///
126    /// let mut b = SgSet::<_, 10>::new();
127    /// b.insert(3);
128    /// b.insert(4);
129    /// b.insert(5);
130    ///
131    /// a.append(&mut b);
132    ///
133    /// assert_eq!(a.len(), 5);
134    /// assert_eq!(b.len(), 0);
135    ///
136    /// assert!(a.contains(&1));
137    /// assert!(a.contains(&2));
138    /// assert!(a.contains(&3));
139    /// assert!(a.contains(&4));
140    /// assert!(a.contains(&5));
141    /// ```
142    pub fn append(&mut self, other: &mut SgSet<T, N>)
143    where
144        T: Ord,
145    {
146        self.bst.append(&mut other.bst);
147    }
148
149    /// Attempts to move all elements from `other` into `self`, leaving `other` empty.
150    ///
151    /// # Examples
152    ///
153    /// ```
154    /// use core::iter::FromIterator;
155    /// use scapegoat::{SgSet, SgError};
156    ///
157    /// let mut a = SgSet::<_, 10>::new();
158    /// assert!(a.try_insert(1).is_ok());
159    /// assert!(a.try_insert(2).is_ok());
160    /// assert!(a.try_insert(3).is_ok());
161    ///
162    /// let mut b = SgSet::<_, 10>::new();
163    /// assert!(b.try_insert(3).is_ok()); // Overwrite previous
164    /// assert!(b.try_insert(4).is_ok());
165    /// assert!(b.try_insert(5).is_ok());
166    ///
167    /// // Successful append
168    /// assert!(a.try_append(&mut b).is_ok());
169    ///
170    /// // Elements moved
171    /// assert_eq!(a.len(), 5);
172    /// assert_eq!(b.len(), 0);
173    ///
174    /// assert!(a.contains(&1));
175    /// assert!(a.contains(&2));
176    /// assert!(a.contains(&3));
177    /// assert!(a.contains(&4));
178    /// assert!(a.contains(&5));
179    ///
180    /// // Fill remaining capacity
181    /// let mut key = 6;
182    /// while a.len() < a.capacity() {
183    ///     assert!(a.try_insert(key).is_ok());
184    ///     key += 1;
185    /// }
186    ///
187    /// // Full
188    /// assert!(a.is_full());
189    ///
190    /// // More data
191    /// let mut c = SgSet::<_, 10>::from_iter([11, 12]);
192    /// let mut d = SgSet::<_, 10>::from_iter([1, 2]);
193    ///
194    /// // Cannot append new pairs
195    /// assert_eq!(a.try_append(&mut c), Err(SgError::StackCapacityExceeded));
196    ///
197    /// // Can still replace existing pairs
198    /// assert!(a.try_append(&mut d).is_ok());
199    /// ```
200    pub fn try_append(&mut self, other: &mut SgSet<T, N>) -> Result<(), SgError> {
201        self.bst.try_append(&mut other.bst)
202    }
203
204    /// Adds a value to the set.
205    /// If the set did not have this value present, `true` is returned.
206    /// If the set did have this value present, `false` is returned, and the entry is overwritten.
207    ///
208    /// # Examples
209    ///
210    /// ```
211    /// use scapegoat::SgSet;
212    ///
213    /// let mut set = SgSet::<_, 10>::new();
214    ///
215    /// assert_eq!(set.insert(2), true);
216    /// assert_eq!(set.insert(2), false);
217    /// assert_eq!(set.len(), 1);
218    /// ```
219    pub fn insert(&mut self, value: T) -> bool
220    where
221        T: Ord,
222    {
223        self.bst.insert(value, ()).is_none()
224    }
225
226    /// Adds a value to the set.
227    /// Returns `Err` if the operation can't be completed, else the `Ok` contains:
228    /// * `true` if the set did not have this value present.
229    /// * `false` if the set did have this value present (and that old entry is overwritten).
230    ///
231    /// # Examples
232    ///
233    /// ```
234    /// use scapegoat::{SgSet, SgError};
235    ///
236    /// let mut set = SgSet::<_, 10>::new();
237    ///
238    /// // Add a new element
239    /// assert_eq!(set.try_insert(2), Ok(true));
240    ///
241    /// // Replace existing element
242    /// assert_eq!(set.try_insert(2), Ok(false));
243    /// assert_eq!(set.len(), 1);
244    ///
245    /// // Fill remaining capacity
246    /// let mut elem = 3;
247    /// while set.len() < set.capacity() {
248    ///     assert!(set.try_insert(elem).is_ok());
249    ///     elem += 1;
250    /// }
251    ///
252    /// // Full
253    /// assert!(set.is_full());
254    ///
255    /// // Cannot insert new element
256    /// assert_eq!(set.try_insert(elem), Err(SgError::StackCapacityExceeded));
257    ///
258    /// // Can still replace existing element
259    /// assert_eq!(set.try_insert(elem - 1), Ok(false));
260    /// ```
261    pub fn try_insert(&mut self, value: T) -> Result<bool, SgError>
262    where
263        T: Ord,
264    {
265        match self.bst.try_insert(value, ()) {
266            Ok(opt_val) => Ok(opt_val.is_none()),
267            Err(_) => Err(SgError::StackCapacityExceeded),
268        }
269    }
270
271    /// Attempt to extend a collection with the contents of an iterator.
272    ///
273    /// # Examples
274    ///
275    /// ```
276    /// use core::iter::FromIterator;
277    /// use scapegoat::{SgSet, SgError};
278    ///
279    /// let mut a = SgSet::<_, 2>::new();
280    /// let mut b = SgSet::<_, 3>::from_iter([1, 2, 3]);
281    /// let mut c = SgSet::<_, 2>::from_iter([1, 2]);
282    ///
283    /// // Too big
284    /// assert_eq!(a.try_extend(b.into_iter()), Err(SgError::StackCapacityExceeded));
285    ///
286    /// // Fits
287    /// assert!(a.try_extend(c.into_iter()).is_ok());
288    /// ```
289    ///
290    /// ### Note
291    ///
292    /// There is no `TryExtend` trait in `core`/`std`.
293    pub fn try_extend<I: ExactSizeIterator + IntoIterator<Item = T>>(
294        &mut self,
295        iter: I,
296    ) -> Result<(), SgError> {
297        // Derp :P
298        if iter.len() <= (self.capacity() - self.len()) {
299            let map: crate::SgMap<T, (), N> = iter.into_iter().map(|e| (e, ())).collect();
300            self.bst.try_extend(map.into_iter())
301        } else {
302            Err(SgError::StackCapacityExceeded)
303        }
304    }
305
306    /// Attempt conversion from an iterator.
307    /// Will fail if iterator length exceeds `u16::MAX`.
308    ///
309    /// # Examples
310    ///
311    /// ```
312    /// use scapegoat::{SgSet, SgError};
313    ///
314    /// const CAPACITY_1: usize = 1_000;
315    /// assert!(SgSet::<_, CAPACITY_1>::try_from_iter((0..CAPACITY_1)).is_ok());
316    ///
317    /// const CAPACITY_2: usize = (u16::MAX as usize) + 1;
318    /// assert_eq!(
319    ///     SgSet::<_, CAPACITY_2>::try_from_iter((0..CAPACITY_2)),
320    ///     Err(SgError::MaximumCapacityExceeded)
321    /// );
322    /// ```
323    ///
324    /// ### Note
325    ///
326    /// There is no `TryFromIterator` trait in `core`/`std`.
327    pub fn try_from_iter<I: ExactSizeIterator + IntoIterator<Item = T>>(
328        iter: I,
329    ) -> Result<Self, SgError> {
330        match iter.len() <= SgTree::<T, (), N>::max_capacity() {
331            true => Ok(SgSet::from_iter(iter)),
332            false => Err(SgError::MaximumCapacityExceeded),
333        }
334    }
335
336    /// Gets an iterator that visits the values in the `SgSet` in ascending order.
337    ///
338    /// # Examples
339    ///
340    /// ```
341    /// use scapegoat::SgSet;
342    ///
343    /// let set: SgSet<usize, 3> = [1, 2, 3].iter().cloned().collect();
344    /// let mut set_iter = set.iter();
345    /// assert_eq!(set_iter.next(), Some(&1));
346    /// assert_eq!(set_iter.next(), Some(&2));
347    /// assert_eq!(set_iter.next(), Some(&3));
348    /// assert_eq!(set_iter.next(), None);
349    /// ```
350    ///
351    /// Values returned by the iterator are returned in ascending order:
352    ///
353    /// ```
354    /// use scapegoat::SgSet;
355    ///
356    /// let set: SgSet<usize, 3> = [3, 1, 2].iter().cloned().collect();
357    /// let mut set_iter = set.iter();
358    /// assert_eq!(set_iter.next(), Some(&1));
359    /// assert_eq!(set_iter.next(), Some(&2));
360    /// assert_eq!(set_iter.next(), Some(&3));
361    /// assert_eq!(set_iter.next(), None);
362    /// ```
363    pub fn iter(&self) -> Iter<'_, T, N> {
364        Iter::new(self)
365    }
366
367    /// Removes a value from the set. Returns whether the value was
368    /// present in the set.
369    ///
370    /// The value may be any borrowed form of the set's value type,
371    /// but the ordering on the borrowed form *must* match the
372    /// ordering on the value type.
373    ///
374    /// # Examples
375    ///
376    /// ```
377    /// use scapegoat::SgSet;
378    ///
379    /// let mut set = SgSet::<_, 10>::new();
380    ///
381    /// set.insert(2);
382    /// assert_eq!(set.remove(&2), true);
383    /// assert_eq!(set.remove(&2), false);
384    /// ```
385    pub fn remove<Q>(&mut self, value: &Q) -> bool
386    where
387        T: Borrow<Q> + Ord,
388        Q: Ord + ?Sized,
389    {
390        self.bst.remove(value).is_some()
391    }
392
393    /// Splits the collection into two at the given value. Returns everything after the given value,
394    /// including the value.
395    ///
396    /// # Examples
397    ///
398    /// ```
399    /// use scapegoat::SgSet;
400    ///
401    /// let mut a = SgSet::<_, 5>::new();
402    /// a.insert(1);
403    /// a.insert(2);
404    /// a.insert(3);
405    /// a.insert(17);
406    /// a.insert(41);
407    ///
408    /// let b = a.split_off(&3);
409    ///
410    /// assert_eq!(a.len(), 2);
411    /// assert_eq!(b.len(), 3);
412    ///
413    /// assert!(a.contains(&1));
414    /// assert!(a.contains(&2));
415    ///
416    /// assert!(b.contains(&3));
417    /// assert!(b.contains(&17));
418    /// assert!(b.contains(&41));
419    /// ```
420    pub fn split_off<Q>(&mut self, value: &Q) -> SgSet<T, N>
421    where
422        T: Borrow<Q> + Ord,
423        Q: Ord + ?Sized,
424    {
425        SgSet {
426            bst: self.bst.split_off(value),
427        }
428    }
429
430    /// Adds a value to the set, replacing the existing value, if any, that is equal to the given
431    /// one. Returns the replaced value.
432    ///
433    /// # Examples
434    ///
435    /// ```
436    /// use scapegoat::SgSet;
437    ///
438    /// let mut set = SgSet::<_, 10>::new();
439    /// set.insert(Vec::<i32>::new());
440    ///
441    /// assert_eq!(set.get(&[][..]).unwrap().capacity(), 0);
442    /// set.replace(Vec::with_capacity(10));
443    /// assert_eq!(set.get(&[][..]).unwrap().capacity(), 10);
444    /// ```
445    pub fn replace(&mut self, value: T) -> Option<T>
446    where
447        T: Ord,
448    {
449        let removed = self.bst.remove_entry(&value).map(|(k, _)| k);
450        self.insert(value);
451        removed
452    }
453
454    // TODO: add example
455    /// Attempts to add a value to the set, replacing the existing value, if any, that is equal to the given
456    /// one. Returns the replaced value.
457    pub fn try_replace(&mut self, value: T) -> Result<Option<T>, SgError>
458    where
459        T: Ord,
460    {
461        let removed = self.bst.remove_entry(&value).map(|(k, _)| k);
462        self.try_insert(value)?;
463        Ok(removed)
464    }
465
466    /// Removes and returns the value in the set, if any, that is equal to the given one.
467    ///
468    /// The value may be any borrowed form of the set's value type,
469    /// but the ordering on the borrowed form *must* match the
470    /// ordering on the value type.
471    ///
472    /// # Examples
473    ///
474    /// ```
475    /// use scapegoat::SgSet;
476    ///
477    /// let mut set: SgSet<_, 10> = [1, 2, 3].iter().cloned().collect();
478    /// assert_eq!(set.take(&2), Some(2));
479    /// assert_eq!(set.take(&2), None);
480    /// ```
481    pub fn take<Q>(&mut self, value: &Q) -> Option<T>
482    where
483        T: Borrow<Q> + Ord,
484        Q: Ord + ?Sized,
485    {
486        self.bst.remove_entry(value).map(|(k, _)| k)
487    }
488
489    /// Retains only the elements specified by the predicate.
490    ///
491    /// In other words, remove all elements `e` such that `f(&e)` returns `false`.
492    /// The elements are visited in ascending order.
493    ///
494    /// # Examples
495    ///
496    /// ```
497    /// use scapegoat::SgSet;
498    ///
499    /// let xs = [1, 2, 3, 4, 5, 6];
500    /// let mut set: SgSet<i32, 10> = xs.iter().cloned().collect();
501    /// // Keep only the even numbers.
502    /// set.retain(|&k| k % 2 == 0);
503    /// assert!(set.iter().eq([2, 4, 6].iter()));
504    /// ```
505    pub fn retain<F>(&mut self, mut f: F)
506    where
507        T: Ord,
508        F: FnMut(&T) -> bool,
509    {
510        self.bst.retain(|k, _| f(k));
511    }
512
513    /// Returns a reference to the value in the set, if any, that is equal to the given value.
514    ///
515    /// The value may be any borrowed form of the set's value type,
516    /// but the ordering on the borrowed form *must* match the
517    /// ordering on the value type.
518    ///
519    /// # Examples
520    ///
521    /// ```
522    /// use scapegoat::SgSet;
523    ///
524    /// let set: SgSet<_, 10> = [1, 2, 3].iter().cloned().collect();
525    /// assert_eq!(set.get(&2), Some(&2));
526    /// assert_eq!(set.get(&4), None);
527    /// ```
528    pub fn get<Q>(&self, value: &Q) -> Option<&T>
529    where
530        T: Borrow<Q> + Ord,
531        Q: Ord + ?Sized,
532    {
533        self.bst.get_key_value(value).map(|(k, _)| k)
534    }
535
536    /// Clears the set, removing all values.
537    ///
538    /// # Examples
539    ///
540    /// ```
541    /// use scapegoat::SgSet;
542    ///
543    /// let mut v = SgSet::<_, 10>::new();
544    /// v.insert(1);
545    /// v.clear();
546    /// assert!(v.is_empty());;
547    /// ```
548    pub fn clear(&mut self) {
549        self.bst.clear()
550    }
551
552    /// Returns `true` if the set contains a value.
553    ///
554    /// The value may be any borrowed form of the set's value type,
555    /// but the ordering on the borrowed form *must* match the
556    /// ordering on the value type.
557    ///
558    /// # Examples
559    ///
560    /// ```
561    /// use scapegoat::SgSet;
562    ///
563    /// let set: SgSet<_, 10> = [1, 2, 3].iter().cloned().collect();
564    /// assert_eq!(set.contains(&1), true);
565    /// assert_eq!(set.contains(&4), false);
566    /// ```
567    pub fn contains<Q>(&self, value: &Q) -> bool
568    where
569        T: Borrow<Q> + Ord,
570        Q: Ord + ?Sized,
571    {
572        self.bst.contains_key(value)
573    }
574
575    /// Returns a reference to the first/minium value in the set, if any.
576    ///
577    /// # Examples
578    ///
579    /// ```
580    /// use scapegoat::SgSet;
581    ///
582    /// let mut set = SgSet::<_, 2>::new();
583    /// assert_eq!(set.first(), None);
584    /// set.insert(1);
585    /// assert_eq!(set.first(), Some(&1));
586    /// set.insert(2);
587    /// assert_eq!(set.first(), Some(&1));
588    /// ```
589    pub fn first(&self) -> Option<&T>
590    where
591        T: Ord,
592    {
593        self.bst.first_key()
594    }
595
596    /// Removes the first value from the set and returns it, if any.
597    /// The first value is the minimum value that was in the set.
598    ///
599    /// # Examples
600    ///
601    /// ```
602    /// use scapegoat::SgSet;
603    ///
604    /// let mut set = SgSet::<_, 10>::new();
605    ///
606    /// set.insert(1);
607    /// while let Some(n) = set.pop_first() {
608    ///     assert_eq!(n, 1);
609    /// }
610    /// assert!(set.is_empty());
611    /// ```
612    pub fn pop_first(&mut self) -> Option<T>
613    where
614        T: Ord,
615    {
616        self.bst.pop_first().map(|(k, _)| k)
617    }
618
619    /// Returns the last/maximum value in the set, if any.
620    ///
621    /// # Examples
622    ///
623    /// ```
624    /// use scapegoat::SgSet;
625    ///
626    /// let mut set = SgSet::<_, 10>::new();
627    /// assert_eq!(set.first(), None);
628    /// set.insert(1);
629    /// assert_eq!(set.last(), Some(&1));
630    /// set.insert(2);
631    /// assert_eq!(set.last(), Some(&2));
632    /// ```
633    pub fn last(&self) -> Option<&T>
634    where
635        T: Ord,
636    {
637        self.bst.last_key()
638    }
639
640    /// Removes the last value from the set and returns it, if any.
641    /// The last value is the maximum value that was in the set.
642    ///
643    /// # Examples
644    ///
645    /// ```
646    /// use scapegoat::SgSet;
647    ///
648    /// let mut set = SgSet::<_, 10>::new();
649    ///
650    /// set.insert(1);
651    /// while let Some(n) = set.pop_last() {
652    ///     assert_eq!(n, 1);
653    /// }
654    /// assert!(set.is_empty());
655    /// ```
656    pub fn pop_last(&mut self) -> Option<T>
657    where
658        T: Ord,
659    {
660        self.bst.pop_last().map(|(k, _)| k)
661    }
662
663    /// Returns the number of elements in the set.
664    ///
665    /// # Examples
666    ///
667    /// ```
668    /// use scapegoat::SgSet;
669    ///
670    /// let mut v = SgSet::<_, 10>::new();
671    /// assert_eq!(v.len(), 0);
672    /// v.insert(1);
673    /// assert_eq!(v.len(), 1);
674    /// ```
675    pub fn len(&self) -> usize {
676        self.bst.len()
677    }
678
679    /// Constructs a double-ended iterator over a sub-range of elements in the set.
680    /// The simplest way is to use the range syntax `min..max`, thus `range(min..max)` will
681    /// yield elements from min (inclusive) to max (exclusive).
682    /// The range may also be entered as `(Bound<T>, Bound<T>)`, so for example
683    /// `range((Excluded(4), Included(10)))` will yield a left-exclusive, right-inclusive
684    /// range from 4 to 10.
685    ///
686    /// # Panics
687    ///
688    /// Panics if range `start > end`.
689    /// Panics if range `start == end` and both bounds are `Excluded`.
690    ///
691    /// # Examples
692    ///
693    /// ```
694    /// use scapegoat::SgSet;
695    /// use core::ops::Bound::Included;
696    ///
697    /// let mut set = SgSet::<_, 5>::new();
698    /// set.insert(3);
699    /// set.insert(5);
700    /// set.insert(8);
701    /// for &elem in set.range((Included(&4), Included(&8))) {
702    ///     println!("{}", elem);
703    /// }
704    /// assert_eq!(Some(&5), set.range(4..).next());
705    /// ```
706    pub fn range<K, R>(&self, range: R) -> Range<'_, T, N>
707    where
708        K: Ord + ?Sized,
709        T: Borrow<K> + Ord,
710        R: RangeBounds<K>,
711    {
712        SgTree::<T, (), N>::assert_valid_range(&range);
713        Range {
714            table: self,
715            node_idx_iter: self.bst.range_search(&range).into_iter(),
716        }
717    }
718
719    /// Returns an iterator over values representing set difference, e.g., values in `self` but not in `other`, in ascending order.
720    ///
721    /// # Examples
722    ///
723    /// ```
724    /// use scapegoat::SgSet;
725    ///
726    /// let mut a = SgSet::<_, 10>::new();
727    /// a.insert(1);
728    /// a.insert(2);
729    ///
730    /// let mut b = SgSet::<_, 10>::new();
731    /// b.insert(2);
732    /// b.insert(3);
733    ///
734    /// let diff: Vec<_> = a.difference(&b).cloned().collect();
735    /// assert_eq!(diff, [1]);
736    /// ```
737    pub fn difference(&self, other: &SgSet<T, N>) -> Difference<T, N>
738    where
739        T: Ord,
740    {
741        Difference::new(self, other)
742    }
743
744    /// Returns an iterator over values representing symmetric set difference, e.g., values in `self` or `other` but not both, in ascending order.
745    ///
746    /// # Examples
747    ///
748    /// ```
749    /// use scapegoat::SgSet;
750    ///
751    /// let mut a = SgSet::<_, 10>::new();
752    /// a.insert(1);
753    /// a.insert(2);
754    ///
755    /// let mut b = SgSet::<_, 10>::new();
756    /// b.insert(2);
757    /// b.insert(3);
758    ///
759    /// let sym_diff: Vec<_> = a.symmetric_difference(&b).cloned().collect();
760    /// assert_eq!(sym_diff, [1, 3]);
761    /// ```
762    ///
763    /// ### Warning
764    ///
765    /// At present, this function may panic if set capacity `N` exceeds `2048`.
766    /// The issue is that this function's returned iterator needs to be `2 * N` long to support disjoint sets,
767    /// but without unstable `feature(generic_const_exprs)` we can't compute `2 * N`.
768    /// So we use `4096` instead of `2 * N` as a workaround, hence `N` should be `<= 2048` to ensure no panic.
769    /// An `N > 2048` may or may not panic, depending on the size of sets' intersection.
770    pub fn symmetric_difference<'a>(&'a self, other: &'a SgSet<T, N>) -> SymmetricDifference<T, N>
771    where
772        T: Ord,
773    {
774        SymmetricDifference::new(self, other)
775    }
776
777    /// Returns an iterator over values representing set intersection, e.g., values in both `self` and `other`, in ascending order.
778    ///
779    /// # Examples
780    ///
781    /// ```
782    /// use scapegoat::SgSet;
783    ///
784    /// let mut a = SgSet::<_, 10>::new();
785    /// a.insert(1);
786    /// a.insert(2);
787    ///
788    /// let mut b = SgSet::<_, 10>::new();
789    /// b.insert(2);
790    /// b.insert(3);
791    ///
792    /// let intersection: Vec<_> = a.intersection(&b).cloned().collect();
793    /// assert_eq!(intersection, [2]);
794    /// ```
795    pub fn intersection(&self, other: &SgSet<T, N>) -> Intersection<T, N>
796    where
797        T: Ord,
798    {
799        Intersection::new(self, other)
800    }
801
802    /// Returns an iterator over values representing set union, e.g., values in `self` or `other`, in ascending order.
803    ///
804    /// # Examples
805    ///
806    /// ```
807    /// use scapegoat::SgSet;
808    ///
809    /// let mut a = SgSet::<_, 10>::new();
810    /// a.insert(1);
811    ///
812    /// let mut b = SgSet::<_, 10>::new();
813    /// b.insert(2);
814    ///
815    /// let union: Vec<_> = a.union(&b).cloned().collect();
816    /// assert_eq!(union, [1, 2]);
817    /// ```
818    ///
819    /// ### Warning
820    ///
821    /// At present, this function may panic if set capacity `N` exceeds `2048`.
822    /// The issue is that this function's returned iterator needs to be `2 * N` long to support disjoint sets,
823    /// but without unstable `feature(generic_const_exprs)` we can't compute `2 * N`.
824    /// So we use `4096` instead of `2 * N` as a workaround, hence `N` should be `<= 2048` to ensure no panic.
825    /// An `N > 2048` may or may not panic, depending on the size of sets' intersection.
826    pub fn union<'a>(&'a self, other: &'a SgSet<T, N>) -> Union<T, N>
827    where
828        T: Ord,
829    {
830        Union::new(self, other)
831    }
832
833    /// Returns `true` if the set contains no elements.
834    ///
835    /// # Examples
836    ///
837    /// ```
838    /// use scapegoat::SgSet;
839    ///
840    /// let mut v = SgSet::<_, 10>::new();
841    /// assert!(v.is_empty());
842    /// v.insert(1);
843    /// assert!(!v.is_empty());
844    /// ```
845    pub fn is_empty(&self) -> bool {
846        self.bst.is_empty()
847    }
848
849    /// Returns `true` if the set's capacity is filled.
850    ///
851    /// # Examples
852    ///
853    /// ```
854    /// use scapegoat::SgSet;
855    ///
856    /// let mut a = SgSet::<_, 2>::new();
857    /// a.insert(1);
858    /// assert!(!a.is_full());
859    /// a.insert(2);
860    /// assert!(a.is_full());
861    /// ```
862    pub fn is_full(&self) -> bool {
863        self.bst.is_full()
864    }
865
866    /// Returns `true` if `self` has no elements in common with other (empty intersection).
867    ///
868    /// # Examples
869    ///
870    /// ```
871    /// use scapegoat::SgSet;
872    /// let a: SgSet<_, 10> = [1, 2, 3].iter().cloned().collect();
873    /// let mut b = SgSet::new();
874    ///
875    /// assert_eq!(a.is_disjoint(&b), true);
876    /// b.insert(4);
877    /// assert_eq!(a.is_disjoint(&b), true);
878    /// b.insert(1);
879    /// assert_eq!(a.is_disjoint(&b), false);
880    /// ```
881    pub fn is_disjoint(&self, other: &SgSet<T, N>) -> bool
882    where
883        T: Ord,
884    {
885        self.intersection(other).count() == 0
886    }
887
888    /// Returns `true` if `self` is a subset of `other`, e.g., `other` contains at least all the values in `self`.
889    ///
890    /// # Examples
891    ///
892    /// ```
893    /// use scapegoat::SgSet;
894    ///
895    /// let sup: SgSet<_, 10> = [1, 2, 3].iter().cloned().collect();
896    /// let mut set = SgSet::new();
897    ///
898    /// assert_eq!(set.is_subset(&sup), true);
899    /// set.insert(2);
900    /// assert_eq!(set.is_subset(&sup), true);
901    /// set.insert(4);
902    /// assert_eq!(set.is_subset(&sup), false);
903    /// ```
904    pub fn is_subset(&self, other: &SgSet<T, N>) -> bool
905    where
906        T: Ord,
907    {
908        self.intersection(other).count() == self.len()
909    }
910
911    /// Returns `true` if `self` is a superset of `other`, e.g., `self` contains at least all the values in `other`.
912    ///
913    /// # Examples
914    ///
915    /// ```
916    /// use scapegoat::SgSet;
917    ///
918    /// let sub: SgSet<_, 3> = [1, 2].iter().cloned().collect();
919    /// let mut set = SgSet::new();
920    ///
921    /// assert_eq!(set.is_superset(&sub), false);
922    ///
923    /// set.insert(0);
924    /// set.insert(1);
925    /// assert_eq!(set.is_superset(&sub), false);
926    ///
927    /// set.insert(2);
928    /// assert_eq!(set.is_superset(&sub), true);
929    /// ```
930    pub fn is_superset(&self, other: &SgSet<T, N>) -> bool
931    where
932        T: Ord,
933    {
934        other.is_subset(self)
935    }
936}
937
938// Convenience Traits --------------------------------------------------------------------------------------------------
939
940// Debug
941impl<T, const N: usize> Debug for SgSet<T, N>
942where
943    T: Ord + Default + Debug,
944{
945    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
946        f.debug_set()
947            .entries(self.bst.iter().map(|(k, _)| k))
948            .finish()
949    }
950}
951
952// From array.
953impl<T, const N: usize> From<[T; N]> for SgSet<T, N>
954where
955    T: Ord + Default,
956{
957    /// ```
958    /// use scapegoat::SgSet;
959    ///
960    /// let set1 = SgSet::from([1, 2, 3, 4]);
961    /// let set2: SgSet<_, 4> = [1, 2, 3, 4].into();
962    /// assert_eq!(set1, set2);
963    /// ```
964    ///
965    /// ### Warning
966    ///
967    /// [`TryFrom`](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html) isn't implemented because it would collide with the blanket implementation.
968    /// See [this open GitHub issue](https://github.com/rust-lang/rust/issues/50133#issuecomment-64690839) from 2018,
969    /// this is a known Rust limitation that should be fixed via specialization in the future.
970    #[doc(alias = "tryfrom")]
971    #[doc(alias = "try_from")]
972    #[doc(alias = "TryFrom")]
973    fn from(arr: [T; N]) -> Self {
974        IntoIterator::into_iter(arr).collect()
975    }
976}
977
978// Construct from iterator.
979impl<T, const N: usize> FromIterator<T> for SgSet<T, N>
980where
981    T: Ord + Default,
982{
983    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
984        let mut sgs = SgSet::new();
985        sgs.bst = SgTree::from_iter(iter.into_iter().map(|e| (e, ())));
986        sgs
987    }
988}
989
990// Extension from iterator.
991impl<T, const N: usize> Extend<T> for SgSet<T, N>
992where
993    T: Ord + Default,
994{
995    fn extend<TreeIter: IntoIterator<Item = T>>(&mut self, iter: TreeIter) {
996        self.bst.extend(iter.into_iter().map(|e| (e, ())));
997    }
998}
999
1000// Extension from reference iterator.
1001impl<'a, T, const N: usize> Extend<&'a T> for SgSet<T, N>
1002where
1003    T: 'a + Ord + Default + Copy,
1004{
1005    fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
1006        self.extend(iter.into_iter().cloned());
1007    }
1008}
1009
1010// General Iterators ---------------------------------------------------------------------------------------------------
1011
1012// Reference iterator
1013impl<'a, T: Ord + Default, const N: usize> IntoIterator for &'a SgSet<T, N> {
1014    type Item = &'a T;
1015    type IntoIter = Iter<'a, T, N>;
1016
1017    fn into_iter(self) -> Self::IntoIter {
1018        self.iter()
1019    }
1020}
1021
1022// Consuming iterator
1023impl<T: Ord + Default, const N: usize> IntoIterator for SgSet<T, N> {
1024    type Item = T;
1025    type IntoIter = IntoIter<T, N>;
1026
1027    fn into_iter(self) -> Self::IntoIter {
1028        IntoIter::new(self)
1029    }
1030}
1031
1032// Operator Overloading ------------------------------------------------------------------------------------------------
1033
1034impl<T: Ord + Default + Clone, const N: usize> Sub<&SgSet<T, N>> for &SgSet<T, N> {
1035    type Output = SgSet<T, N>;
1036
1037    /// Returns the difference of `self` and `rhs` as a new `SgSet<T, N>`.
1038    ///
1039    /// # Examples
1040    ///
1041    /// ```
1042    /// use scapegoat::SgSet;
1043    ///
1044    /// let a: SgSet<_, 10> = vec![1, 2, 3].into_iter().collect();
1045    /// let b: SgSet<_, 10> = vec![3, 4, 5].into_iter().collect();
1046    ///
1047    /// let result = &a - &b;
1048    /// let result_vec: Vec<_> = result.into_iter().collect();
1049    /// assert_eq!(result_vec, [1, 2]);
1050    /// ```
1051    fn sub(self, rhs: &SgSet<T, N>) -> SgSet<T, N> {
1052        self.difference(rhs).cloned().collect()
1053    }
1054}
1055
1056impl<T: Ord + Default + Clone, const N: usize> BitAnd<&SgSet<T, N>> for &SgSet<T, N> {
1057    type Output = SgSet<T, N>;
1058
1059    /// Returns the intersection of `self` and `rhs` as a new `SgSet<T, N>`.
1060    ///
1061    /// # Examples
1062    ///
1063    /// ```
1064    /// use scapegoat::SgSet;
1065    ///
1066    /// let a: SgSet<_, 10> = vec![1, 2, 3].into_iter().collect();
1067    /// let b: SgSet<_, 10> = vec![2, 3, 4].into_iter().collect();
1068    ///
1069    /// let result = &a & &b;
1070    /// let result_vec: Vec<_> = result.into_iter().collect();
1071    /// assert_eq!(result_vec, [2, 3]);
1072    /// ```
1073    fn bitand(self, rhs: &SgSet<T, N>) -> SgSet<T, N> {
1074        self.intersection(rhs).cloned().collect()
1075    }
1076}
1077
1078impl<T: Ord + Default + Clone, const N: usize> BitOr<&SgSet<T, N>> for &SgSet<T, N> {
1079    type Output = SgSet<T, N>;
1080
1081    /// Returns the union of `self` and `rhs` as a new `SgSet<T, N>`.
1082    ///
1083    /// # Examples
1084    ///
1085    /// ```
1086    /// use scapegoat::SgSet;
1087    ///
1088    /// let a: SgSet<_, 10> = vec![1, 2, 3].into_iter().collect();
1089    /// let b: SgSet<_, 10> = vec![3, 4, 5].into_iter().collect();
1090    ///
1091    /// let result = &a | &b;
1092    /// let result_vec: Vec<_> = result.into_iter().collect();
1093    /// assert_eq!(result_vec, [1, 2, 3, 4, 5]);
1094    /// ```
1095    fn bitor(self, rhs: &SgSet<T, N>) -> SgSet<T, N> {
1096        self.union(rhs).cloned().collect()
1097    }
1098}
1099
1100impl<T: Ord + Default + Clone, const N: usize> BitXor<&SgSet<T, N>> for &SgSet<T, N> {
1101    type Output = SgSet<T, N>;
1102
1103    /// Returns the symmetric difference of `self` and `rhs` as a new `SgSet<T, N>`.
1104    ///
1105    /// # Examples
1106    ///
1107    /// ```
1108    /// use scapegoat::SgSet;
1109    ///
1110    /// let a: SgSet<_, 10> = vec![1, 2, 3].into_iter().collect();
1111    /// let b: SgSet<_, 10> = vec![2, 3, 4].into_iter().collect();
1112    ///
1113    /// let result = &a ^ &b;
1114    /// let result_vec: Vec<_> = result.into_iter().collect();
1115    /// assert_eq!(result_vec, [1, 4]);
1116    /// ```
1117    fn bitxor(self, rhs: &SgSet<T, N>) -> SgSet<T, N> {
1118        self.symmetric_difference(rhs).cloned().collect()
1119    }
1120}