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