rune_alloc/btree/
set.rs

1//! An ordered set based on a B-Tree.
2
3use core::borrow::Borrow;
4use core::cmp::Ordering::{self, Equal, Greater, Less};
5use core::cmp::{max, min};
6use core::fmt;
7use core::hash::{Hash, Hasher};
8use core::iter::{FusedIterator, Peekable};
9use core::ops::RangeBounds;
10
11use super::map::{infallible_cmp, into_ok, BTreeMap, CmpFn, Keys};
12use super::merge_iter::MergeIterInner;
13use super::set_val::SetValZST;
14use super::Recover;
15
16use crate::alloc::{AllocError, Allocator, Global};
17use crate::clone::TryClone;
18use crate::error::Error;
19use crate::iter::{TryExtend, TryFromIteratorIn};
20#[cfg(test)]
21use crate::testing::*;
22
23/// An ordered set based on a B-Tree.
24///
25/// See [`BTreeMap`]'s documentation for a detailed discussion of this collection's performance
26/// benefits and drawbacks.
27///
28/// It is a logic error for an item to be modified in such a way that the item's ordering relative
29/// to any other item, as determined by the [`Ord`] trait, changes while it is in the set. This is
30/// normally only possible through [`Cell`], [`RefCell`], global state, I/O, or unsafe code.
31/// The behavior resulting from such a logic error is not specified, but will be encapsulated to the
32/// `BTreeSet` that observed the logic error and not result in undefined behavior. This could
33/// include panics, incorrect results, aborts, memory leaks, and non-termination.
34///
35/// Iterators returned by [`BTreeSet::iter`] produce their items in order, and take worst-case
36/// logarithmic and amortized constant time per item returned.
37///
38/// [`Cell`]: core::cell::Cell
39/// [`RefCell`]: core::cell::RefCell
40///
41/// # Examples
42///
43/// ```
44/// use rune::alloc::BTreeSet;
45///
46/// // Type inference lets us omit an explicit type signature (which
47/// // would be `BTreeSet<&str>` in this example).
48/// let mut books = BTreeSet::new();
49///
50/// // Add some books.
51/// books.try_insert("A Dance With Dragons")?;
52/// books.try_insert("To Kill a Mockingbird")?;
53/// books.try_insert("The Odyssey")?;
54/// books.try_insert("The Great Gatsby")?;
55///
56/// // Check for a specific one.
57/// if !books.contains("The Winds of Winter") {
58///     println!("We have {} books, but The Winds of Winter ain't one.",
59///              books.len());
60/// }
61///
62/// // Remove a book.
63/// books.remove("The Odyssey");
64///
65/// // Iterate over everything.
66/// for book in &books {
67///     println!("{book}");
68/// }
69/// # Ok::<_, rune::alloc::Error>(())
70/// ```
71///
72/// A `BTreeSet` with a known list of items can be initialized from an array:
73///
74/// ```
75/// use rune::alloc::BTreeSet;
76///
77/// let set = BTreeSet::try_from([1, 2, 3])?;
78/// # Ok::<_, rune::alloc::Error>(())
79/// ```
80pub struct BTreeSet<T, A = Global>
81where
82    A: Allocator,
83{
84    map: BTreeMap<T, SetValZST, A>,
85}
86
87impl<T, A> Hash for BTreeSet<T, A>
88where
89    T: Hash,
90    A: Allocator,
91{
92    #[inline]
93    fn hash<H>(&self, state: &mut H)
94    where
95        H: Hasher,
96    {
97        self.map.hash(state)
98    }
99}
100
101impl<T, A> PartialEq for BTreeSet<T, A>
102where
103    T: PartialEq,
104    A: Allocator,
105{
106    #[inline]
107    fn eq(&self, other: &BTreeSet<T, A>) -> bool {
108        self.map.eq(&other.map)
109    }
110}
111
112impl<T, A> Eq for BTreeSet<T, A>
113where
114    T: Eq,
115    A: Allocator,
116{
117}
118
119impl<T, A> PartialOrd for BTreeSet<T, A>
120where
121    T: PartialOrd,
122    A: Allocator,
123{
124    #[inline]
125    fn partial_cmp(&self, other: &BTreeSet<T, A>) -> Option<Ordering> {
126        self.map.partial_cmp(&other.map)
127    }
128}
129
130impl<T, A> Ord for BTreeSet<T, A>
131where
132    T: Ord,
133    A: Allocator,
134{
135    #[inline]
136    fn cmp(&self, other: &BTreeSet<T, A>) -> Ordering {
137        self.map.cmp(&other.map)
138    }
139}
140
141impl<T, A> TryClone for BTreeSet<T, A>
142where
143    T: TryClone,
144    A: Allocator + Clone,
145{
146    #[inline]
147    fn try_clone(&self) -> Result<Self, Error> {
148        Ok(BTreeSet {
149            map: self.map.try_clone()?,
150        })
151    }
152}
153
154#[cfg(test)]
155impl<T, A> Clone for BTreeSet<T, A>
156where
157    T: TryClone,
158    A: Allocator + Clone,
159{
160    #[inline]
161    fn clone(&self) -> Self {
162        self.try_clone().abort()
163    }
164}
165
166/// An iterator over the items of a `BTreeSet`.
167///
168/// This `struct` is created by the [`iter`] method on [`BTreeSet`]. See its
169/// documentation for more.
170///
171/// [`iter`]: BTreeSet::iter
172#[must_use = "iterators are lazy and do nothing unless consumed"]
173pub struct Iter<'a, T>
174where
175    T: 'a,
176{
177    iter: Keys<'a, T, SetValZST>,
178}
179
180impl<T> fmt::Debug for Iter<'_, T>
181where
182    T: fmt::Debug,
183{
184    #[inline]
185    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
186        f.debug_tuple("Iter").field(&self.iter.clone()).finish()
187    }
188}
189
190/// An owning iterator over the items of a `BTreeSet`.
191///
192/// This `struct` is created by the [`into_iter`] method on [`BTreeSet`]
193/// (provided by the [`IntoIterator`] trait). See its documentation for more.
194///
195/// [`into_iter`]: BTreeSet#method.into_iter
196#[derive(Debug)]
197pub struct IntoIter<T, A = Global>
198where
199    A: Allocator,
200{
201    iter: super::map::IntoIter<T, SetValZST, A>,
202}
203
204/// An iterator over a sub-range of items in a `BTreeSet`.
205///
206/// This `struct` is created by the [`range`] method on [`BTreeSet`].
207/// See its documentation for more.
208///
209/// [`range`]: BTreeSet::range
210#[must_use = "iterators are lazy and do nothing unless consumed"]
211#[derive(Debug)]
212pub struct Range<'a, T>
213where
214    T: 'a,
215{
216    iter: super::map::Range<'a, T, SetValZST>,
217}
218
219/// A lazy iterator producing elements in the difference of `BTreeSet`s.
220///
221/// This `struct` is created by the [`difference`] method on [`BTreeSet`].
222/// See its documentation for more.
223///
224/// [`difference`]: BTreeSet::difference
225#[must_use = "this returns the difference as an iterator, \
226              without modifying either input set"]
227pub struct Difference<'a, T, A = Global>
228where
229    T: 'a,
230    A: Allocator,
231{
232    inner: DifferenceInner<'a, T, A>,
233}
234
235enum DifferenceInner<'a, T, A>
236where
237    T: 'a,
238    A: Allocator,
239{
240    Stitch {
241        // iterate all of `self` and some of `other`, spotting matches along the way
242        self_iter: Iter<'a, T>,
243        other_iter: Peekable<Iter<'a, T>>,
244    },
245    Search {
246        // iterate `self`, look up in `other`
247        self_iter: Iter<'a, T>,
248        other_set: &'a BTreeSet<T, A>,
249    },
250    Iterate(Iter<'a, T>), // simply produce all elements in `self`
251}
252
253// Explicit Debug impl necessary because of issue #26925
254impl<T, A> fmt::Debug for DifferenceInner<'_, T, A>
255where
256    T: fmt::Debug,
257    A: Allocator,
258{
259    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
260        match self {
261            DifferenceInner::Stitch {
262                self_iter,
263                other_iter,
264            } => f
265                .debug_struct("Stitch")
266                .field("self_iter", self_iter)
267                .field("other_iter", other_iter)
268                .finish(),
269            DifferenceInner::Search {
270                self_iter,
271                other_set,
272            } => f
273                .debug_struct("Search")
274                .field("self_iter", self_iter)
275                .field("other_iter", other_set)
276                .finish(),
277            DifferenceInner::Iterate(x) => f.debug_tuple("Iterate").field(x).finish(),
278        }
279    }
280}
281
282impl<T, A> fmt::Debug for Difference<'_, T, A>
283where
284    T: fmt::Debug,
285    A: Allocator,
286{
287    #[inline]
288    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
289        f.debug_tuple("Difference").field(&self.inner).finish()
290    }
291}
292
293/// A lazy iterator producing elements in the symmetric difference of `BTreeSet`s.
294///
295/// This `struct` is created by the [`symmetric_difference`] method on
296/// [`BTreeSet`]. See its documentation for more.
297///
298/// [`symmetric_difference`]: BTreeSet::symmetric_difference
299#[must_use = "this returns the difference as an iterator, \
300              without modifying either input set"]
301pub struct SymmetricDifference<'a, T>(MergeIterInner<Iter<'a, T>>)
302where
303    T: 'a;
304
305impl<T> fmt::Debug for SymmetricDifference<'_, T>
306where
307    T: fmt::Debug,
308{
309    #[inline]
310    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
311        f.debug_tuple("SymmetricDifference").field(&self.0).finish()
312    }
313}
314
315/// A lazy iterator producing elements in the intersection of `BTreeSet`s.
316///
317/// This `struct` is created by the [`intersection`] method on [`BTreeSet`].
318/// See its documentation for more.
319///
320/// [`intersection`]: BTreeSet::intersection
321#[must_use = "this returns the intersection as an iterator, \
322              without modifying either input set"]
323pub struct Intersection<'a, T, A = Global>
324where
325    T: 'a,
326    A: Allocator,
327{
328    inner: IntersectionInner<'a, T, A>,
329}
330
331enum IntersectionInner<'a, T, A>
332where
333    T: 'a,
334    A: Allocator,
335{
336    Stitch {
337        // iterate similarly sized sets jointly, spotting matches along the way
338        a: Iter<'a, T>,
339        b: Iter<'a, T>,
340    },
341    Search {
342        // iterate a small set, look up in the large set
343        small_iter: Iter<'a, T>,
344        large_set: &'a BTreeSet<T, A>,
345    },
346    Answer(Option<&'a T>), // return a specific element or emptiness
347}
348
349// Explicit Debug impl necessary because of issue #26925
350impl<T, A> fmt::Debug for IntersectionInner<'_, T, A>
351where
352    T: fmt::Debug,
353    A: Allocator,
354{
355    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
356        match self {
357            IntersectionInner::Stitch { a, b } => f
358                .debug_struct("Stitch")
359                .field("a", a)
360                .field("b", b)
361                .finish(),
362            IntersectionInner::Search {
363                small_iter,
364                large_set,
365            } => f
366                .debug_struct("Search")
367                .field("small_iter", small_iter)
368                .field("large_set", large_set)
369                .finish(),
370            IntersectionInner::Answer(x) => f.debug_tuple("Answer").field(x).finish(),
371        }
372    }
373}
374
375impl<T, A> fmt::Debug for Intersection<'_, T, A>
376where
377    T: fmt::Debug,
378    A: Allocator,
379{
380    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
381        f.debug_tuple("Intersection").field(&self.inner).finish()
382    }
383}
384
385/// A lazy iterator producing elements in the union of `BTreeSet`s.
386///
387/// This `struct` is created by the [`union`] method on [`BTreeSet`].
388/// See its documentation for more.
389///
390/// [`union`]: BTreeSet::union
391#[must_use = "this returns the union as an iterator, \
392              without modifying either input set"]
393pub struct Union<'a, T>(MergeIterInner<Iter<'a, T>>)
394where
395    T: 'a;
396
397impl<T> fmt::Debug for Union<'_, T>
398where
399    T: fmt::Debug,
400{
401    #[inline]
402    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
403        f.debug_tuple("Union").field(&self.0).finish()
404    }
405}
406
407// This constant is used by functions that compare two sets.
408// It estimates the relative size at which searching performs better
409// than iterating, based on the benchmarks in
410// https://github.com/ssomers/rust_bench_btreeset_intersection.
411// It's used to divide rather than multiply sizes, to rule out overflow,
412// and it's a power of two to make that division cheap.
413const ITER_PERFORMANCE_TIPPING_SIZE_DIFF: usize = 16;
414
415impl<T> BTreeSet<T> {
416    /// Makes a new, empty `BTreeSet`.
417    ///
418    /// Does not allocate anything on its own.
419    ///
420    /// # Examples
421    ///
422    /// ```
423    /// use rune::alloc::BTreeSet;
424    ///
425    /// let mut set: BTreeSet<i32> = BTreeSet::new();
426    /// ```
427    #[must_use]
428    pub const fn new() -> BTreeSet<T> {
429        BTreeSet {
430            map: BTreeMap::new(),
431        }
432    }
433
434    #[cfg(test)]
435    pub(crate) fn from<const N: usize>(values: [T; N]) -> Self
436    where
437        T: Ord,
438    {
439        Self::try_from(values).abort()
440    }
441}
442
443impl<T, A> BTreeSet<T, A>
444where
445    A: Allocator,
446{
447    /// Makes a new `BTreeSet` with a reasonable choice of B.
448    ///
449    /// # Examples
450    ///
451    /// ```
452    /// use rune::alloc::BTreeSet;
453    /// use rune::alloc::alloc::Global;
454    ///
455    /// let mut set: BTreeSet<i32> = BTreeSet::new_in(Global);
456    /// ```
457    pub fn new_in(alloc: A) -> BTreeSet<T, A> {
458        BTreeSet {
459            map: BTreeMap::new_in(alloc),
460        }
461    }
462
463    /// Constructs a double-ended iterator over a sub-range of elements in the set.
464    /// The simplest way is to use the range syntax `min..max`, thus `range(min..max)` will
465    /// yield elements from min (inclusive) to max (exclusive).
466    /// The range may also be entered as `(Bound<T>, Bound<T>)`, so for example
467    /// `range((Excluded(4), Included(10)))` will yield a left-exclusive, right-inclusive
468    /// range from 4 to 10.
469    ///
470    /// # Panics
471    ///
472    /// Panics if range `start > end`.
473    /// Panics if range `start == end` and both bounds are `Excluded`.
474    ///
475    /// # Examples
476    ///
477    /// ```
478    /// use rune::alloc::BTreeSet;
479    /// use std::ops::Bound::Included;
480    ///
481    /// let mut set = BTreeSet::new();
482    /// set.try_insert(3)?;
483    /// set.try_insert(5)?;
484    /// set.try_insert(8)?;
485    /// for &elem in set.range((Included(&4), Included(&8))) {
486    ///     println!("{elem}");
487    /// }
488    /// assert_eq!(Some(&5), set.range(4..).next());
489    /// # Ok::<_, rune::alloc::Error>(())
490    /// ```
491    pub fn range<K, R>(&self, range: R) -> Range<'_, T>
492    where
493        K: ?Sized + Ord,
494        T: Borrow<K> + Ord,
495        R: RangeBounds<K>,
496    {
497        Range {
498            iter: self.map.range(range),
499        }
500    }
501
502    /// Visits the elements representing the difference,
503    /// i.e., the elements that are in `self` but not in `other`,
504    /// in ascending order.
505    ///
506    /// # Examples
507    ///
508    /// ```
509    /// use rune::alloc::{BTreeSet, Vec};
510    /// use rune::alloc::prelude::*;
511    ///
512    /// let mut a = BTreeSet::new();
513    /// a.try_insert(1)?;
514    /// a.try_insert(2)?;
515    ///
516    /// let mut b = BTreeSet::new();
517    /// b.try_insert(2)?;
518    /// b.try_insert(3)?;
519    ///
520    /// let diff: Vec<_> = a.difference(&b).cloned().try_collect()?;
521    /// assert_eq!(diff, [1]);
522    /// # Ok::<_, rune::alloc::Error>(())
523    /// ```
524    pub fn difference<'a>(&'a self, other: &'a BTreeSet<T, A>) -> Difference<'a, T, A>
525    where
526        T: Ord,
527    {
528        let (self_min, self_max) =
529            if let (Some(self_min), Some(self_max)) = (self.first(), self.last()) {
530                (self_min, self_max)
531            } else {
532                return Difference {
533                    inner: DifferenceInner::Iterate(self.iter()),
534                };
535            };
536        let (other_min, other_max) =
537            if let (Some(other_min), Some(other_max)) = (other.first(), other.last()) {
538                (other_min, other_max)
539            } else {
540                return Difference {
541                    inner: DifferenceInner::Iterate(self.iter()),
542                };
543            };
544        Difference {
545            inner: match (self_min.cmp(other_max), self_max.cmp(other_min)) {
546                (Greater, _) | (_, Less) => DifferenceInner::Iterate(self.iter()),
547                (Equal, _) => {
548                    let mut self_iter = self.iter();
549                    self_iter.next();
550                    DifferenceInner::Iterate(self_iter)
551                }
552                (_, Equal) => {
553                    let mut self_iter = self.iter();
554                    self_iter.next_back();
555                    DifferenceInner::Iterate(self_iter)
556                }
557                _ if self.len() <= other.len() / ITER_PERFORMANCE_TIPPING_SIZE_DIFF => {
558                    DifferenceInner::Search {
559                        self_iter: self.iter(),
560                        other_set: other,
561                    }
562                }
563                _ => DifferenceInner::Stitch {
564                    self_iter: self.iter(),
565                    other_iter: other.iter().peekable(),
566                },
567            },
568        }
569    }
570
571    /// Visits the elements representing the symmetric difference,
572    /// i.e., the elements that are in `self` or in `other` but not in both,
573    /// in ascending order.
574    ///
575    /// # Examples
576    ///
577    /// ```
578    /// use rune::alloc::{BTreeSet, Vec};
579    /// use rune::alloc::prelude::*;
580    ///
581    /// let mut a = BTreeSet::new();
582    /// a.try_insert(1)?;
583    /// a.try_insert(2)?;
584    ///
585    /// let mut b = BTreeSet::new();
586    /// b.try_insert(2)?;
587    /// b.try_insert(3)?;
588    ///
589    /// let sym_diff: Vec<_> = a.symmetric_difference(&b).cloned().try_collect()?;
590    /// assert_eq!(sym_diff, [1, 3]);
591    /// # Ok::<_, rune::alloc::Error>(())
592    /// ```
593    pub fn symmetric_difference<'a>(
594        &'a self,
595        other: &'a BTreeSet<T, A>,
596    ) -> SymmetricDifference<'a, T>
597    where
598        T: Ord,
599    {
600        SymmetricDifference(MergeIterInner::new(self.iter(), other.iter()))
601    }
602
603    /// Visits the elements representing the intersection,
604    /// i.e., the elements that are both in `self` and `other`,
605    /// in ascending order.
606    ///
607    /// # Examples
608    ///
609    /// ```
610    /// use rune::alloc::{BTreeSet, Vec};
611    /// use rune::alloc::prelude::*;
612    ///
613    /// let mut a = BTreeSet::new();
614    /// a.try_insert(1)?;
615    /// a.try_insert(2)?;
616    ///
617    /// let mut b = BTreeSet::new();
618    /// b.try_insert(2)?;
619    /// b.try_insert(3)?;
620    ///
621    /// let intersection: Vec<_> = a.intersection(&b).cloned().try_collect()?;
622    /// assert_eq!(intersection, [2]);
623    /// # Ok::<_, rune::alloc::Error>(())
624    /// ```
625    pub fn intersection<'a>(&'a self, other: &'a BTreeSet<T, A>) -> Intersection<'a, T, A>
626    where
627        T: Ord,
628    {
629        let (self_min, self_max) =
630            if let (Some(self_min), Some(self_max)) = (self.first(), self.last()) {
631                (self_min, self_max)
632            } else {
633                return Intersection {
634                    inner: IntersectionInner::Answer(None),
635                };
636            };
637        let (other_min, other_max) =
638            if let (Some(other_min), Some(other_max)) = (other.first(), other.last()) {
639                (other_min, other_max)
640            } else {
641                return Intersection {
642                    inner: IntersectionInner::Answer(None),
643                };
644            };
645        Intersection {
646            inner: match (self_min.cmp(other_max), self_max.cmp(other_min)) {
647                (Greater, _) | (_, Less) => IntersectionInner::Answer(None),
648                (Equal, _) => IntersectionInner::Answer(Some(self_min)),
649                (_, Equal) => IntersectionInner::Answer(Some(self_max)),
650                _ if self.len() <= other.len() / ITER_PERFORMANCE_TIPPING_SIZE_DIFF => {
651                    IntersectionInner::Search {
652                        small_iter: self.iter(),
653                        large_set: other,
654                    }
655                }
656                _ if other.len() <= self.len() / ITER_PERFORMANCE_TIPPING_SIZE_DIFF => {
657                    IntersectionInner::Search {
658                        small_iter: other.iter(),
659                        large_set: self,
660                    }
661                }
662                _ => IntersectionInner::Stitch {
663                    a: self.iter(),
664                    b: other.iter(),
665                },
666            },
667        }
668    }
669
670    /// Visits the elements representing the union,
671    /// i.e., all the elements in `self` or `other`, without duplicates,
672    /// in ascending order.
673    ///
674    /// # Examples
675    ///
676    /// ```
677    /// use rune::alloc::{BTreeSet, Vec};
678    /// use rune::alloc::prelude::*;
679    ///
680    /// let mut a = BTreeSet::new();
681    /// a.try_insert(1)?;
682    ///
683    /// let mut b = BTreeSet::new();
684    /// b.try_insert(2)?;
685    ///
686    /// let union: Vec<_> = a.union(&b).cloned().try_collect()?;
687    /// assert_eq!(union, [1, 2]);
688    /// # Ok::<_, rune::alloc::Error>(())
689    /// ```
690    pub fn union<'a>(&'a self, other: &'a BTreeSet<T, A>) -> Union<'a, T>
691    where
692        T: Ord,
693    {
694        Union(MergeIterInner::new(self.iter(), other.iter()))
695    }
696
697    /// Clears the set, removing all elements.
698    ///
699    /// # Examples
700    ///
701    /// ```
702    /// use rune::alloc::{BTreeSet, Vec};
703    /// use rune::alloc::prelude::*;
704    ///
705    /// let mut v = BTreeSet::new();
706    /// v.try_insert(1)?;
707    /// v.clear();
708    /// assert!(v.is_empty());
709    /// # Ok::<_, rune::alloc::Error>(())
710    /// ```
711    pub fn clear(&mut self) {
712        self.map.clear()
713    }
714
715    /// Returns `true` if the set contains an element equal to the value.
716    ///
717    /// The value may be any borrowed form of the set's element type,
718    /// but the ordering on the borrowed form *must* match the
719    /// ordering on the element type.
720    ///
721    /// # Examples
722    ///
723    /// ```
724    /// use rune::alloc::BTreeSet;
725    ///
726    /// let set = BTreeSet::try_from([1, 2, 3])?;
727    /// assert_eq!(set.contains(&1), true);
728    /// assert_eq!(set.contains(&4), false);
729    /// # Ok::<_, rune::alloc::Error>(())
730    /// ```
731    pub fn contains<Q>(&self, value: &Q) -> bool
732    where
733        T: Borrow<Q> + Ord,
734        Q: ?Sized + Ord,
735    {
736        self.map.contains_key(value)
737    }
738
739    /// Returns a reference to the element in the set, if any, that is equal to
740    /// the value.
741    ///
742    /// The value may be any borrowed form of the set's element type,
743    /// but the ordering on the borrowed form *must* match the
744    /// ordering on the element type.
745    ///
746    /// # Examples
747    ///
748    /// ```
749    /// use rune::alloc::BTreeSet;
750    ///
751    /// let set = BTreeSet::try_from([1, 2, 3])?;
752    /// assert_eq!(set.get(&2), Some(&2));
753    /// assert_eq!(set.get(&4), None);
754    /// # Ok::<_, rune::alloc::Error>(())
755    /// ```
756    pub fn get<Q>(&self, value: &Q) -> Option<&T>
757    where
758        T: Borrow<Q> + Ord,
759        Q: ?Sized + Ord,
760    {
761        into_ok(self.get_with(&mut (), value, infallible_cmp))
762    }
763
764    pub(crate) fn get_with<C: ?Sized, Q: ?Sized, E>(
765        &self,
766        cx: &mut C,
767        value: &Q,
768        cmp: CmpFn<C, Q, E>,
769    ) -> Result<Option<&T>, E>
770    where
771        T: Borrow<Q>,
772    {
773        Recover::get(&self.map, cx, value, cmp)
774    }
775
776    /// Returns `true` if `self` has no elements in common with `other`. This is
777    /// equivalent to checking for an empty intersection.
778    ///
779    /// # Examples
780    ///
781    /// ```
782    /// use rune::alloc::BTreeSet;
783    ///
784    /// let a = BTreeSet::try_from([1, 2, 3])?;
785    /// let mut b = BTreeSet::new();
786    ///
787    /// assert_eq!(a.is_disjoint(&b), true);
788    /// b.try_insert(4)?;
789    /// assert_eq!(a.is_disjoint(&b), true);
790    /// b.try_insert(1)?;
791    /// assert_eq!(a.is_disjoint(&b), false);
792    /// # Ok::<_, rune::alloc::Error>(())
793    /// ```
794    #[must_use]
795    pub fn is_disjoint(&self, other: &BTreeSet<T, A>) -> bool
796    where
797        T: Ord,
798    {
799        self.intersection(other).next().is_none()
800    }
801
802    /// Returns `true` if the set is a subset of another,
803    /// i.e., `other` contains at least all the elements in `self`.
804    ///
805    /// # Examples
806    ///
807    /// ```
808    /// use rune::alloc::BTreeSet;
809    ///
810    /// let sup = BTreeSet::try_from([1, 2, 3])?;
811    /// let mut set = BTreeSet::new();
812    ///
813    /// assert_eq!(set.is_subset(&sup), true);
814    /// set.try_insert(2)?;
815    /// assert_eq!(set.is_subset(&sup), true);
816    /// set.try_insert(4)?;
817    /// assert_eq!(set.is_subset(&sup), false);
818    /// # Ok::<_, rune::alloc::Error>(())
819    /// ```
820    #[must_use]
821    pub fn is_subset(&self, other: &BTreeSet<T, A>) -> bool
822    where
823        T: Ord,
824    {
825        // Same result as self.difference(other).next().is_none()
826        // but the code below is faster (hugely in some cases).
827        if self.len() > other.len() {
828            return false;
829        }
830        let (self_min, self_max) =
831            if let (Some(self_min), Some(self_max)) = (self.first(), self.last()) {
832                (self_min, self_max)
833            } else {
834                return true; // self is empty
835            };
836        let (other_min, other_max) =
837            if let (Some(other_min), Some(other_max)) = (other.first(), other.last()) {
838                (other_min, other_max)
839            } else {
840                return false; // other is empty
841            };
842        let mut self_iter = self.iter();
843        match self_min.cmp(other_min) {
844            Less => return false,
845            Equal => {
846                self_iter.next();
847            }
848            Greater => (),
849        }
850        match self_max.cmp(other_max) {
851            Greater => return false,
852            Equal => {
853                self_iter.next_back();
854            }
855            Less => (),
856        }
857        if self_iter.len() <= other.len() / ITER_PERFORMANCE_TIPPING_SIZE_DIFF {
858            for next in self_iter {
859                if !other.contains(next) {
860                    return false;
861                }
862            }
863        } else {
864            let mut other_iter = other.iter();
865            other_iter.next();
866            other_iter.next_back();
867            let mut self_next = self_iter.next();
868            while let Some(self1) = self_next {
869                match other_iter.next().map_or(Less, |other1| self1.cmp(other1)) {
870                    Less => return false,
871                    Equal => self_next = self_iter.next(),
872                    Greater => (),
873                }
874            }
875        }
876        true
877    }
878
879    /// Returns `true` if the set is a superset of another,
880    /// i.e., `self` contains at least all the elements in `other`.
881    ///
882    /// # Examples
883    ///
884    /// ```
885    /// use rune::alloc::BTreeSet;
886    ///
887    /// let sub = BTreeSet::try_from([1, 2])?;
888    /// let mut set = BTreeSet::new();
889    ///
890    /// assert_eq!(set.is_superset(&sub), false);
891    ///
892    /// set.try_insert(0)?;
893    /// set.try_insert(1)?;
894    /// assert_eq!(set.is_superset(&sub), false);
895    ///
896    /// set.try_insert(2)?;
897    /// assert_eq!(set.is_superset(&sub), true);
898    /// # Ok::<_, rune::alloc::Error>(())
899    /// ```
900    #[must_use]
901    pub fn is_superset(&self, other: &BTreeSet<T, A>) -> bool
902    where
903        T: Ord,
904    {
905        other.is_subset(self)
906    }
907
908    /// Returns a reference to the first element in the set, if any.
909    /// This element is always the minimum of all elements in the set.
910    ///
911    /// # Examples
912    ///
913    /// Basic usage:
914    ///
915    /// ```
916    /// use rune::alloc::BTreeSet;
917    ///
918    /// let mut set = BTreeSet::new();
919    /// assert_eq!(set.first(), None);
920    /// set.try_insert(1)?;
921    /// assert_eq!(set.first(), Some(&1));
922    /// set.try_insert(2)?;
923    /// assert_eq!(set.first(), Some(&1));
924    /// # Ok::<_, rune::alloc::Error>(())
925    /// ```
926    #[must_use]
927    pub fn first(&self) -> Option<&T>
928    where
929        T: Ord,
930    {
931        self.map.first_key_value().map(|(k, _)| k)
932    }
933
934    /// Returns a reference to the last element in the set, if any.
935    /// This element is always the maximum of all elements in the set.
936    ///
937    /// # Examples
938    ///
939    /// Basic usage:
940    ///
941    /// ```
942    /// use rune::alloc::BTreeSet;
943    ///
944    /// let mut set = BTreeSet::new();
945    /// assert_eq!(set.last(), None);
946    /// set.try_insert(1)?;
947    /// assert_eq!(set.last(), Some(&1));
948    /// set.try_insert(2)?;
949    /// assert_eq!(set.last(), Some(&2));
950    /// # Ok::<_, rune::alloc::Error>(())
951    /// ```
952    #[must_use]
953    pub fn last(&self) -> Option<&T>
954    where
955        T: Ord,
956    {
957        self.map.last_key_value().map(|(k, _)| k)
958    }
959
960    /// Removes the first element from the set and returns it, if any.
961    /// The first element is always the minimum element in the set.
962    ///
963    /// # Examples
964    ///
965    /// ```
966    /// use rune::alloc::BTreeSet;
967    ///
968    /// let mut set = BTreeSet::new();
969    ///
970    /// set.try_insert(1)?;
971    ///
972    /// while let Some(n) = set.pop_first() {
973    ///     assert_eq!(n, 1);
974    /// }
975    ///
976    /// assert!(set.is_empty());
977    /// # Ok::<_, rune::alloc::Error>(())
978    /// ```
979    pub fn pop_first(&mut self) -> Option<T>
980    where
981        T: Ord,
982    {
983        self.map.pop_first().map(|kv| kv.0)
984    }
985
986    /// Removes the last element from the set and returns it, if any. The last
987    /// element is always the maximum element in the set.
988    ///
989    /// # Examples
990    ///
991    /// ```
992    /// use rune::alloc::BTreeSet;
993    ///
994    /// let mut set = BTreeSet::new();
995    ///
996    /// set.try_insert(1)?;
997    ///
998    /// while let Some(n) = set.pop_last() {
999    ///     assert_eq!(n, 1);
1000    /// }
1001    ///
1002    /// assert!(set.is_empty());
1003    /// # Ok::<_, rune::alloc::Error>(())
1004    /// ```
1005    pub fn pop_last(&mut self) -> Option<T>
1006    where
1007        T: Ord,
1008    {
1009        self.map.pop_last().map(|kv| kv.0)
1010    }
1011
1012    /// Adds a value to the set.
1013    ///
1014    /// Returns whether the value was newly inserted. That is:
1015    ///
1016    /// - If the set did not previously contain an equal value, `true` is
1017    ///   returned.
1018    /// - If the set already contained an equal value, `false` is returned, and
1019    ///   the entry is not updated.
1020    ///
1021    /// See the [module-level documentation] for more.
1022    ///
1023    /// [module-level documentation]: index.html#insert-and-complex-keys
1024    ///
1025    /// # Examples
1026    ///
1027    /// ```
1028    /// use rune::alloc::BTreeSet;
1029    ///
1030    /// let mut set = BTreeSet::new();
1031    ///
1032    /// assert_eq!(set.try_insert(2)?, true);
1033    /// assert_eq!(set.try_insert(2)?, false);
1034    /// assert_eq!(set.len(), 1);
1035    /// # Ok::<_, rune::alloc::Error>(())
1036    /// ```
1037    pub fn try_insert(&mut self, value: T) -> Result<bool, AllocError>
1038    where
1039        T: Ord,
1040    {
1041        Ok(self.map.try_insert(value, SetValZST)?.is_none())
1042    }
1043
1044    #[cfg(test)]
1045    pub(crate) fn insert(&mut self, value: T) -> bool
1046    where
1047        T: Ord,
1048    {
1049        self.try_insert(value).abort()
1050    }
1051
1052    /// Adds a value to the set, replacing the existing element, if any, that is
1053    /// equal to the value. Returns the replaced element.
1054    ///
1055    /// # Examples
1056    ///
1057    /// ```
1058    /// use rune::alloc::{Vec, BTreeSet};
1059    ///
1060    /// let mut set = BTreeSet::new();
1061    /// set.try_insert(Vec::<i32>::new())?;
1062    ///
1063    /// assert_eq!(set.get(&[][..]).unwrap().capacity(), 0);
1064    /// set.try_replace(Vec::try_with_capacity(10)?)?;
1065    /// assert_eq!(set.get(&[][..]).unwrap().capacity(), 10);
1066    /// # Ok::<_, rune::alloc::Error>(())
1067    /// ```
1068    pub fn try_replace(&mut self, value: T) -> Result<Option<T>, AllocError>
1069    where
1070        T: Ord,
1071    {
1072        into_ok(self.try_replace_with(&mut (), value, infallible_cmp))
1073    }
1074
1075    #[cfg(test)]
1076    pub(crate) fn replace(&mut self, value: T) -> Option<T>
1077    where
1078        T: Ord,
1079    {
1080        self.try_replace(value).abort()
1081    }
1082
1083    pub(crate) fn try_replace_with<C: ?Sized, E>(
1084        &mut self,
1085        cx: &mut C,
1086        value: T,
1087        cmp: CmpFn<C, T, E>,
1088    ) -> Result<Result<Option<T>, AllocError>, E> {
1089        Recover::try_replace(&mut self.map, cx, value, cmp)
1090    }
1091
1092    /// If the set contains an element equal to the value, removes it from the
1093    /// set and drops it. Returns whether such an element was present.
1094    ///
1095    /// The value may be any borrowed form of the set's element type,
1096    /// but the ordering on the borrowed form *must* match the
1097    /// ordering on the element type.
1098    ///
1099    /// # Examples
1100    ///
1101    /// ```
1102    /// use rune::alloc::BTreeSet;
1103    ///
1104    /// let mut set = BTreeSet::new();
1105    ///
1106    /// set.try_insert(2)?;
1107    /// assert_eq!(set.remove(&2), true);
1108    /// assert_eq!(set.remove(&2), false);
1109    /// # Ok::<_, rune::alloc::Error>(())
1110    /// ```
1111    pub fn remove<Q>(&mut self, value: &Q) -> bool
1112    where
1113        T: Borrow<Q> + Ord,
1114        Q: ?Sized + Ord,
1115    {
1116        self.map.remove(value).is_some()
1117    }
1118
1119    /// Removes and returns the element in the set, if any, that is equal to
1120    /// the value.
1121    ///
1122    /// The value may be any borrowed form of the set's element type,
1123    /// but the ordering on the borrowed form *must* match the
1124    /// ordering on the element type.
1125    ///
1126    /// # Examples
1127    ///
1128    /// ```
1129    /// use rune::alloc::BTreeSet;
1130    ///
1131    /// let mut set = BTreeSet::try_from([1, 2, 3])?;
1132    /// assert_eq!(set.take(&2), Some(2));
1133    /// assert_eq!(set.take(&2), None);
1134    /// # Ok::<_, rune::alloc::Error>(())
1135    /// ```
1136    pub fn take<Q>(&mut self, value: &Q) -> Option<T>
1137    where
1138        T: Borrow<Q> + Ord,
1139        Q: ?Sized + Ord,
1140    {
1141        into_ok(self.take_with(&mut (), value, infallible_cmp))
1142    }
1143
1144    pub(crate) fn take_with<C: ?Sized, Q: ?Sized, E>(
1145        &mut self,
1146        cx: &mut C,
1147        value: &Q,
1148        cmp: CmpFn<C, Q, E>,
1149    ) -> Result<Option<T>, E>
1150    where
1151        T: Borrow<Q>,
1152    {
1153        Recover::take(&mut self.map, cx, value, cmp)
1154    }
1155
1156    /// Retains only the elements specified by the predicate.
1157    ///
1158    /// In other words, remove all elements `e` for which `f(&e)` returns `false`.
1159    /// The elements are visited in ascending order.
1160    ///
1161    /// # Examples
1162    ///
1163    /// ```
1164    /// use rune::alloc::BTreeSet;
1165    ///
1166    /// let mut set = BTreeSet::try_from([1, 2, 3, 4, 5, 6])?;
1167    /// // Keep only the even numbers.
1168    /// set.retain(|&k| k % 2 == 0);
1169    /// assert!(set.iter().eq([2, 4, 6].iter()));
1170    /// # Ok::<_, rune::alloc::Error>(())
1171    /// ```
1172    pub fn retain<F>(&mut self, mut f: F)
1173    where
1174        T: Ord,
1175        F: FnMut(&T) -> bool,
1176    {
1177        self.extract_if(|v| !f(v)).for_each(drop);
1178    }
1179
1180    /// Moves all elements from `other` into `self`, leaving `other` empty.
1181    ///
1182    /// # Examples
1183    ///
1184    /// ```
1185    /// use rune::alloc::BTreeSet;
1186    ///
1187    /// let mut a = BTreeSet::new();
1188    /// a.try_insert(1)?;
1189    /// a.try_insert(2)?;
1190    /// a.try_insert(3)?;
1191    ///
1192    /// let mut b = BTreeSet::new();
1193    /// b.try_insert(3)?;
1194    /// b.try_insert(4)?;
1195    /// b.try_insert(5)?;
1196    ///
1197    /// a.try_append(&mut b)?;
1198    ///
1199    /// assert_eq!(a.len(), 5);
1200    /// assert_eq!(b.len(), 0);
1201    ///
1202    /// assert!(a.contains(&1));
1203    /// assert!(a.contains(&2));
1204    /// assert!(a.contains(&3));
1205    /// assert!(a.contains(&4));
1206    /// assert!(a.contains(&5));
1207    /// # Ok::<_, rune::alloc::Error>(())
1208    /// ```
1209    pub fn try_append(&mut self, other: &mut Self) -> Result<(), AllocError>
1210    where
1211        T: Ord,
1212    {
1213        self.map.try_append(&mut other.map)
1214    }
1215
1216    #[cfg(test)]
1217    pub(crate) fn append(&mut self, other: &mut Self)
1218    where
1219        T: Ord,
1220    {
1221        self.try_append(other).abort()
1222    }
1223
1224    /// Splits the collection into two at the value. Returns a new collection
1225    /// with all elements greater than or equal to the value.
1226    ///
1227    /// # Examples
1228    ///
1229    /// Basic usage:
1230    ///
1231    /// ```
1232    /// use rune::alloc::BTreeSet;
1233    ///
1234    /// let mut a = BTreeSet::new();
1235    /// a.try_insert(1)?;
1236    /// a.try_insert(2)?;
1237    /// a.try_insert(3)?;
1238    /// a.try_insert(17)?;
1239    /// a.try_insert(41)?;
1240    ///
1241    /// let b = a.try_split_off(&3)?;
1242    ///
1243    /// assert_eq!(a.len(), 2);
1244    /// assert_eq!(b.len(), 3);
1245    ///
1246    /// assert!(a.contains(&1));
1247    /// assert!(a.contains(&2));
1248    ///
1249    /// assert!(b.contains(&3));
1250    /// assert!(b.contains(&17));
1251    /// assert!(b.contains(&41));
1252    /// # Ok::<_, rune::alloc::Error>(())
1253    /// ```
1254    pub fn try_split_off<Q>(&mut self, value: &Q) -> Result<Self, Error>
1255    where
1256        Q: ?Sized + Ord,
1257        T: Borrow<Q> + Ord,
1258        A: Clone,
1259    {
1260        Ok(BTreeSet {
1261            map: self.map.try_split_off(value)?,
1262        })
1263    }
1264
1265    #[cfg(test)]
1266    pub(crate) fn split_off<Q>(&mut self, value: &Q) -> Self
1267    where
1268        Q: ?Sized + Ord,
1269        T: Borrow<Q> + Ord,
1270        A: Clone,
1271    {
1272        self.try_split_off(value).abort()
1273    }
1274
1275    /// Creates an iterator that visits all elements in ascending order and
1276    /// uses a closure to determine if an element should be removed.
1277    ///
1278    /// If the closure returns `true`, the element is removed from the set and
1279    /// yielded. If the closure returns `false`, or panics, the element remains
1280    /// in the set and will not be yielded.
1281    ///
1282    /// If the returned `ExtractIf` is not exhausted, e.g. because it is dropped without iterating
1283    /// or the iteration short-circuits, then the remaining elements will be retained.
1284    /// Use [`retain`] with a negated predicate if you do not need the returned iterator.
1285    ///
1286    /// [`retain`]: BTreeSet::retain
1287    /// # Examples
1288    ///
1289    /// Splitting a set into even and odd values, reusing the original set:
1290    ///
1291    /// ```
1292    /// use rune::alloc::{BTreeSet, Vec};
1293    /// use rune::alloc::prelude::*;
1294    ///
1295    /// let mut set: BTreeSet<i32> = (0..8).try_collect()?;
1296    /// let evens: BTreeSet<_> = set.extract_if(|v| v % 2 == 0).try_collect()?;
1297    /// let odds = set;
1298    /// assert_eq!(evens.into_iter().try_collect::<Vec<_>>()?, [0, 2, 4, 6]);
1299    /// assert_eq!(odds.into_iter().try_collect::<Vec<_>>()?, [1, 3, 5, 7]);
1300    /// # Ok::<_, rune::alloc::Error>(())
1301    /// ```
1302    pub fn extract_if<'a, F>(&'a mut self, pred: F) -> ExtractIf<'a, T, F, A>
1303    where
1304        T: Ord,
1305        F: 'a + FnMut(&T) -> bool,
1306    {
1307        let (inner, alloc) = self.map.extract_if_inner();
1308        ExtractIf { pred, inner, alloc }
1309    }
1310
1311    /// Gets an iterator that visits the elements in the `BTreeSet` in ascending
1312    /// order.
1313    ///
1314    /// # Examples
1315    ///
1316    /// ```
1317    /// use rune::alloc::BTreeSet;
1318    ///
1319    /// let set = BTreeSet::try_from([1, 2, 3])?;
1320    /// let mut set_iter = set.iter();
1321    /// assert_eq!(set_iter.next(), Some(&1));
1322    /// assert_eq!(set_iter.next(), Some(&2));
1323    /// assert_eq!(set_iter.next(), Some(&3));
1324    /// assert_eq!(set_iter.next(), None);
1325    /// # Ok::<_, rune::alloc::Error>(())
1326    /// ```
1327    ///
1328    /// Values returned by the iterator are returned in ascending order:
1329    ///
1330    /// ```
1331    /// use rune::alloc::BTreeSet;
1332    ///
1333    /// let set = BTreeSet::try_from([3, 1, 2])?;
1334    /// let mut set_iter = set.iter();
1335    /// assert_eq!(set_iter.next(), Some(&1));
1336    /// assert_eq!(set_iter.next(), Some(&2));
1337    /// assert_eq!(set_iter.next(), Some(&3));
1338    /// assert_eq!(set_iter.next(), None);
1339    /// # Ok::<_, rune::alloc::Error>(())
1340    /// ```
1341    pub fn iter(&self) -> Iter<'_, T> {
1342        Iter {
1343            iter: self.map.keys(),
1344        }
1345    }
1346
1347    /// Returns the number of elements in the set.
1348    ///
1349    /// # Examples
1350    ///
1351    /// ```
1352    /// use rune::alloc::BTreeSet;
1353    ///
1354    /// let mut v = BTreeSet::new();
1355    /// assert_eq!(v.len(), 0);
1356    /// v.try_insert(1)?;
1357    /// assert_eq!(v.len(), 1);
1358    /// # Ok::<_, rune::alloc::Error>(())
1359    /// ```
1360    #[must_use]
1361    pub const fn len(&self) -> usize {
1362        self.map.len()
1363    }
1364
1365    /// Returns `true` if the set contains no elements.
1366    ///
1367    /// # Examples
1368    ///
1369    /// ```
1370    /// use rune::alloc::BTreeSet;
1371    ///
1372    /// let mut v = BTreeSet::new();
1373    /// assert!(v.is_empty());
1374    /// v.try_insert(1)?;
1375    /// assert!(!v.is_empty());
1376    /// # Ok::<_, rune::alloc::Error>(())
1377    /// ```
1378    #[must_use]
1379    pub const fn is_empty(&self) -> bool {
1380        self.len() == 0
1381    }
1382}
1383
1384impl<T, A> IntoIterator for BTreeSet<T, A>
1385where
1386    A: Allocator,
1387{
1388    type Item = T;
1389    type IntoIter = IntoIter<T, A>;
1390
1391    /// Gets an iterator for moving out the `BTreeSet`'s contents.
1392    ///
1393    /// # Examples
1394    ///
1395    /// ```
1396    /// use rune::alloc::{BTreeSet, Vec};
1397    /// use rune::alloc::prelude::*;
1398    ///
1399    /// let set = BTreeSet::try_from([1, 2, 3, 4])?;
1400    ///
1401    /// let v: Vec<_> = set.into_iter().try_collect()?;
1402    /// assert_eq!(v, [1, 2, 3, 4]);
1403    /// # Ok::<_, rune::alloc::Error>(())
1404    /// ```
1405    #[inline]
1406    fn into_iter(self) -> IntoIter<T, A> {
1407        IntoIter {
1408            iter: self.map.into_iter(),
1409        }
1410    }
1411}
1412
1413impl<'a, T, A> IntoIterator for &'a BTreeSet<T, A>
1414where
1415    A: Allocator,
1416{
1417    type Item = &'a T;
1418    type IntoIter = Iter<'a, T>;
1419
1420    #[inline]
1421    fn into_iter(self) -> Iter<'a, T> {
1422        self.iter()
1423    }
1424}
1425
1426/// An iterator produced by calling `extract_if` on BTreeSet.
1427#[must_use = "iterators are lazy and do nothing unless consumed"]
1428pub struct ExtractIf<'a, T, F, A = Global>
1429where
1430    T: 'a,
1431    F: 'a + FnMut(&T) -> bool,
1432    A: Allocator,
1433{
1434    pred: F,
1435    inner: super::map::ExtractIfInner<'a, T, SetValZST>,
1436    /// The BTreeMap will outlive this IntoIter so we don't care about drop order for `alloc`.
1437    alloc: &'a A,
1438}
1439
1440impl<T, F, A> fmt::Debug for ExtractIf<'_, T, F, A>
1441where
1442    T: fmt::Debug,
1443    F: FnMut(&T) -> bool,
1444    A: Allocator,
1445{
1446    #[inline]
1447    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1448        f.debug_tuple("ExtractIf")
1449            .field(&self.inner.peek().map(|(k, _)| k))
1450            .finish()
1451    }
1452}
1453
1454impl<T, F, A> Iterator for ExtractIf<'_, T, F, A>
1455where
1456    F: FnMut(&T) -> bool,
1457    A: Allocator,
1458{
1459    type Item = T;
1460
1461    fn next(&mut self) -> Option<T> {
1462        let pred = &mut self.pred;
1463        let mut mapped_pred = |k: &T, _v: &mut SetValZST| pred(k);
1464        self.inner
1465            .next(&mut mapped_pred, self.alloc)
1466            .map(|(k, _)| k)
1467    }
1468
1469    fn size_hint(&self) -> (usize, Option<usize>) {
1470        self.inner.size_hint()
1471    }
1472}
1473
1474impl<T, F, A> FusedIterator for ExtractIf<'_, T, F, A>
1475where
1476    F: FnMut(&T) -> bool,
1477    A: Allocator,
1478{
1479}
1480
1481impl<T, A> TryExtend<T> for BTreeSet<T, A>
1482where
1483    T: Ord,
1484    A: Allocator,
1485{
1486    #[inline]
1487    fn try_extend<Iter: IntoIterator<Item = T>>(&mut self, iter: Iter) -> Result<(), Error> {
1488        for elem in iter {
1489            self.try_insert(elem)?;
1490        }
1491
1492        Ok(())
1493    }
1494}
1495
1496#[cfg(test)]
1497impl<T, A> Extend<T> for BTreeSet<T, A>
1498where
1499    T: Ord,
1500    A: Allocator,
1501{
1502    #[inline]
1503    fn extend<Iter: IntoIterator<Item = T>>(&mut self, iter: Iter) {
1504        self.try_extend(iter).abort()
1505    }
1506}
1507
1508impl<'a, T, A> TryExtend<&'a T> for BTreeSet<T, A>
1509where
1510    T: 'a + Ord + Copy,
1511    A: Allocator,
1512{
1513    fn try_extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) -> Result<(), Error> {
1514        self.try_extend(iter.into_iter().copied())
1515    }
1516}
1517
1518#[cfg(test)]
1519impl<'a, T, A> Extend<&'a T> for BTreeSet<T, A>
1520where
1521    T: 'a + Ord + Copy,
1522    A: Allocator,
1523{
1524    fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
1525        self.try_extend(iter).abort()
1526    }
1527}
1528
1529impl<T> Default for BTreeSet<T> {
1530    /// Creates an empty `BTreeSet`.
1531    #[inline]
1532    fn default() -> BTreeSet<T> {
1533        BTreeSet::new()
1534    }
1535}
1536
1537impl<T, A> fmt::Debug for BTreeSet<T, A>
1538where
1539    T: fmt::Debug,
1540    A: Allocator,
1541{
1542    #[inline]
1543    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1544        f.debug_set().entries(self.iter()).finish()
1545    }
1546}
1547
1548impl<T> Clone for Iter<'_, T> {
1549    #[inline]
1550    fn clone(&self) -> Self {
1551        Iter {
1552            iter: self.iter.clone(),
1553        }
1554    }
1555}
1556impl<'a, T> Iterator for Iter<'a, T> {
1557    type Item = &'a T;
1558
1559    #[inline]
1560    fn next(&mut self) -> Option<&'a T> {
1561        self.iter.next()
1562    }
1563
1564    #[inline]
1565    fn size_hint(&self) -> (usize, Option<usize>) {
1566        self.iter.size_hint()
1567    }
1568
1569    #[inline]
1570    fn last(mut self) -> Option<&'a T> {
1571        self.next_back()
1572    }
1573
1574    #[inline]
1575    fn min(mut self) -> Option<&'a T>
1576    where
1577        &'a T: Ord,
1578    {
1579        self.next()
1580    }
1581
1582    #[inline]
1583    fn max(mut self) -> Option<&'a T>
1584    where
1585        &'a T: Ord,
1586    {
1587        self.next_back()
1588    }
1589}
1590
1591impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
1592    #[inline]
1593    fn next_back(&mut self) -> Option<&'a T> {
1594        self.iter.next_back()
1595    }
1596}
1597
1598impl<T> ExactSizeIterator for Iter<'_, T> {
1599    #[inline]
1600    fn len(&self) -> usize {
1601        self.iter.len()
1602    }
1603}
1604
1605impl<T> FusedIterator for Iter<'_, T> {}
1606
1607impl<T, A> Iterator for IntoIter<T, A>
1608where
1609    A: Allocator,
1610{
1611    type Item = T;
1612
1613    #[inline]
1614    fn next(&mut self) -> Option<T> {
1615        self.iter.next().map(|(k, _)| k)
1616    }
1617
1618    #[inline]
1619    fn size_hint(&self) -> (usize, Option<usize>) {
1620        self.iter.size_hint()
1621    }
1622}
1623
1624impl<T> Default for Iter<'_, T> {
1625    /// Creates an empty `btree_set::Iter`.
1626    ///
1627    /// ```
1628    /// use rune::alloc::btree_set;
1629    ///
1630    /// let iter: btree_set::Iter<'_, u8> = Default::default();
1631    /// assert_eq!(iter.len(), 0);
1632    /// ```
1633    fn default() -> Self {
1634        Iter {
1635            iter: Default::default(),
1636        }
1637    }
1638}
1639
1640impl<T, A> DoubleEndedIterator for IntoIter<T, A>
1641where
1642    A: Allocator,
1643{
1644    #[inline]
1645    fn next_back(&mut self) -> Option<T> {
1646        self.iter.next_back().map(|(k, _)| k)
1647    }
1648}
1649
1650impl<T, A> ExactSizeIterator for IntoIter<T, A>
1651where
1652    A: Allocator,
1653{
1654    #[inline]
1655    fn len(&self) -> usize {
1656        self.iter.len()
1657    }
1658}
1659
1660impl<T, A> FusedIterator for IntoIter<T, A> where A: Allocator {}
1661
1662impl<T, A> Default for IntoIter<T, A>
1663where
1664    A: Allocator + Default + Clone,
1665{
1666    /// Creates an empty `btree_set::IntoIter`.
1667    ///
1668    /// ```
1669    /// use rune::alloc::btree_set;
1670    ///
1671    /// let iter: btree_set::IntoIter<u8> = Default::default();
1672    /// assert_eq!(iter.len(), 0);
1673    /// ```
1674    #[inline]
1675    fn default() -> Self {
1676        IntoIter {
1677            iter: Default::default(),
1678        }
1679    }
1680}
1681
1682impl<T> Clone for Range<'_, T> {
1683    #[inline]
1684    fn clone(&self) -> Self {
1685        Range {
1686            iter: self.iter.clone(),
1687        }
1688    }
1689}
1690
1691impl<'a, T> Iterator for Range<'a, T> {
1692    type Item = &'a T;
1693
1694    #[inline]
1695    fn next(&mut self) -> Option<&'a T> {
1696        self.iter.next().map(|(k, _)| k)
1697    }
1698
1699    #[inline]
1700    fn last(mut self) -> Option<&'a T> {
1701        self.next_back()
1702    }
1703
1704    #[inline]
1705    fn min(mut self) -> Option<&'a T>
1706    where
1707        &'a T: Ord,
1708    {
1709        self.next()
1710    }
1711
1712    #[inline]
1713    fn max(mut self) -> Option<&'a T>
1714    where
1715        &'a T: Ord,
1716    {
1717        self.next_back()
1718    }
1719}
1720
1721impl<'a, T> DoubleEndedIterator for Range<'a, T> {
1722    #[inline]
1723    fn next_back(&mut self) -> Option<&'a T> {
1724        self.iter.next_back().map(|(k, _)| k)
1725    }
1726}
1727
1728impl<T> FusedIterator for Range<'_, T> {}
1729
1730impl<T> Default for Range<'_, T> {
1731    /// Creates an empty `btree_set::Range`.
1732    ///
1733    /// ```
1734    /// use rune::alloc::btree_set;
1735    ///
1736    /// let iter: btree_set::Range<'_, u8> = Default::default();
1737    /// assert_eq!(iter.count(), 0);
1738    /// ```
1739    #[inline]
1740    fn default() -> Self {
1741        Range {
1742            iter: Default::default(),
1743        }
1744    }
1745}
1746
1747impl<T, A> Clone for Difference<'_, T, A>
1748where
1749    A: Allocator,
1750{
1751    fn clone(&self) -> Self {
1752        Difference {
1753            inner: match &self.inner {
1754                DifferenceInner::Stitch {
1755                    self_iter,
1756                    other_iter,
1757                } => DifferenceInner::Stitch {
1758                    self_iter: self_iter.clone(),
1759                    other_iter: other_iter.clone(),
1760                },
1761                DifferenceInner::Search {
1762                    self_iter,
1763                    other_set,
1764                } => DifferenceInner::Search {
1765                    self_iter: self_iter.clone(),
1766                    other_set,
1767                },
1768                DifferenceInner::Iterate(iter) => DifferenceInner::Iterate(iter.clone()),
1769            },
1770        }
1771    }
1772}
1773
1774impl<'a, T, A> Iterator for Difference<'a, T, A>
1775where
1776    T: Ord,
1777    A: Allocator,
1778{
1779    type Item = &'a T;
1780
1781    fn next(&mut self) -> Option<&'a T> {
1782        match &mut self.inner {
1783            DifferenceInner::Stitch {
1784                self_iter,
1785                other_iter,
1786            } => {
1787                let mut self_next = self_iter.next()?;
1788
1789                loop {
1790                    match other_iter
1791                        .peek()
1792                        .map_or(Less, |other_next| self_next.cmp(other_next))
1793                    {
1794                        Less => return Some(self_next),
1795                        Equal => {
1796                            self_next = self_iter.next()?;
1797                            other_iter.next();
1798                        }
1799                        Greater => {
1800                            other_iter.next();
1801                        }
1802                    }
1803                }
1804            }
1805            DifferenceInner::Search {
1806                self_iter,
1807                other_set,
1808            } => loop {
1809                let self_next = self_iter.next()?;
1810
1811                if !other_set.contains(self_next) {
1812                    return Some(self_next);
1813                }
1814            },
1815            DifferenceInner::Iterate(iter) => iter.next(),
1816        }
1817    }
1818
1819    fn size_hint(&self) -> (usize, Option<usize>) {
1820        let (self_len, other_len) = match &self.inner {
1821            DifferenceInner::Stitch {
1822                self_iter,
1823                other_iter,
1824            } => (self_iter.len(), other_iter.len()),
1825            DifferenceInner::Search {
1826                self_iter,
1827                other_set,
1828            } => (self_iter.len(), other_set.len()),
1829            DifferenceInner::Iterate(iter) => (iter.len(), 0),
1830        };
1831        (self_len.saturating_sub(other_len), Some(self_len))
1832    }
1833
1834    #[inline]
1835    fn min(mut self) -> Option<&'a T> {
1836        self.next()
1837    }
1838}
1839
1840impl<T, A> FusedIterator for Difference<'_, T, A>
1841where
1842    T: Ord,
1843    A: Allocator,
1844{
1845}
1846
1847impl<T> Clone for SymmetricDifference<'_, T> {
1848    #[inline]
1849    fn clone(&self) -> Self {
1850        SymmetricDifference(self.0.clone())
1851    }
1852}
1853
1854impl<'a, T> Iterator for SymmetricDifference<'a, T>
1855where
1856    T: Ord,
1857{
1858    type Item = &'a T;
1859
1860    fn next(&mut self) -> Option<&'a T> {
1861        loop {
1862            let (a_next, b_next) = self.0.nexts(Self::Item::cmp);
1863
1864            if a_next.and(b_next).is_none() {
1865                return a_next.or(b_next);
1866            }
1867        }
1868    }
1869
1870    #[inline]
1871    fn size_hint(&self) -> (usize, Option<usize>) {
1872        let (a_len, b_len) = self.0.lens();
1873        // No checked_add, because even if a and b refer to the same set,
1874        // and T is a zero-sized type, the storage overhead of sets limits
1875        // the number of elements to less than half the range of usize.
1876        (0, Some(a_len + b_len))
1877    }
1878
1879    #[inline]
1880    fn min(mut self) -> Option<&'a T> {
1881        self.next()
1882    }
1883}
1884
1885impl<T> FusedIterator for SymmetricDifference<'_, T> where T: Ord {}
1886
1887impl<T, A> Clone for Intersection<'_, T, A>
1888where
1889    A: Allocator,
1890{
1891    fn clone(&self) -> Self {
1892        Intersection {
1893            inner: match &self.inner {
1894                IntersectionInner::Stitch { a, b } => IntersectionInner::Stitch {
1895                    a: a.clone(),
1896                    b: b.clone(),
1897                },
1898                IntersectionInner::Search {
1899                    small_iter,
1900                    large_set,
1901                } => IntersectionInner::Search {
1902                    small_iter: small_iter.clone(),
1903                    large_set,
1904                },
1905                IntersectionInner::Answer(answer) => IntersectionInner::Answer(*answer),
1906            },
1907        }
1908    }
1909}
1910impl<'a, T, A> Iterator for Intersection<'a, T, A>
1911where
1912    T: Ord,
1913    A: Allocator,
1914{
1915    type Item = &'a T;
1916
1917    fn next(&mut self) -> Option<&'a T> {
1918        match &mut self.inner {
1919            IntersectionInner::Stitch { a, b } => {
1920                let mut a_next = a.next()?;
1921                let mut b_next = b.next()?;
1922                loop {
1923                    match a_next.cmp(b_next) {
1924                        Less => a_next = a.next()?,
1925                        Greater => b_next = b.next()?,
1926                        Equal => return Some(a_next),
1927                    }
1928                }
1929            }
1930            IntersectionInner::Search {
1931                small_iter,
1932                large_set,
1933            } => loop {
1934                let small_next = small_iter.next()?;
1935                if large_set.contains(small_next) {
1936                    return Some(small_next);
1937                }
1938            },
1939            IntersectionInner::Answer(answer) => answer.take(),
1940        }
1941    }
1942
1943    fn size_hint(&self) -> (usize, Option<usize>) {
1944        match &self.inner {
1945            IntersectionInner::Stitch { a, b } => (0, Some(min(a.len(), b.len()))),
1946            IntersectionInner::Search { small_iter, .. } => (0, Some(small_iter.len())),
1947            IntersectionInner::Answer(None) => (0, Some(0)),
1948            IntersectionInner::Answer(Some(_)) => (1, Some(1)),
1949        }
1950    }
1951
1952    #[inline]
1953    fn min(mut self) -> Option<&'a T> {
1954        self.next()
1955    }
1956}
1957
1958impl<T, A> FusedIterator for Intersection<'_, T, A>
1959where
1960    T: Ord,
1961    A: Allocator,
1962{
1963}
1964
1965impl<T> Clone for Union<'_, T> {
1966    #[inline]
1967    fn clone(&self) -> Self {
1968        Union(self.0.clone())
1969    }
1970}
1971
1972impl<'a, T> Iterator for Union<'a, T>
1973where
1974    T: Ord,
1975{
1976    type Item = &'a T;
1977
1978    #[inline]
1979    fn next(&mut self) -> Option<&'a T> {
1980        let (a_next, b_next) = self.0.nexts(Self::Item::cmp);
1981        a_next.or(b_next)
1982    }
1983
1984    #[inline]
1985    fn size_hint(&self) -> (usize, Option<usize>) {
1986        let (a_len, b_len) = self.0.lens();
1987        // No checked_add - see SymmetricDifference::size_hint.
1988        (max(a_len, b_len), Some(a_len + b_len))
1989    }
1990
1991    #[inline]
1992    fn min(mut self) -> Option<&'a T> {
1993        self.next()
1994    }
1995}
1996
1997impl<T> FusedIterator for Union<'_, T> where T: Ord {}
1998
1999impl<T, A> TryFromIteratorIn<T, A> for BTreeSet<T, A>
2000where
2001    T: Ord,
2002    A: Allocator,
2003{
2004    #[inline]
2005    fn try_from_iter_in<I>(iter: I, alloc: A) -> Result<Self, Error>
2006    where
2007        I: IntoIterator<Item = T>,
2008    {
2009        let mut this = BTreeSet::new_in(alloc);
2010
2011        for value in iter {
2012            this.try_insert(value)?;
2013        }
2014
2015        Ok(this)
2016    }
2017}
2018
2019#[cfg(test)]
2020impl<T> FromIterator<T> for BTreeSet<T>
2021where
2022    T: Ord,
2023{
2024    fn from_iter<I>(iter: I) -> Self
2025    where
2026        I: IntoIterator<Item = T>,
2027    {
2028        Self::try_from_iter_in(iter, Global).abort()
2029    }
2030}
2031
2032impl<T, const N: usize> TryFrom<[T; N]> for BTreeSet<T>
2033where
2034    T: Ord,
2035{
2036    type Error = Error;
2037
2038    #[inline]
2039    fn try_from(values: [T; N]) -> Result<Self, Self::Error> {
2040        let mut this = BTreeSet::new();
2041
2042        for value in values {
2043            this.try_insert(value)?;
2044        }
2045
2046        Ok(this)
2047    }
2048}
2049
2050#[cfg(test)]
2051mod tests;