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