1 // This is pretty much entirely stolen from TreeSet, since BTreeMap has an identical interface
5 use core::borrow::Borrow;
6 use core::cmp::Ordering::{Equal, Greater, Less};
7 use core::cmp::{max, min};
8 use core::fmt::{self, Debug};
9 use core::iter::{FromIterator, FusedIterator, Peekable};
10 use core::ops::{BitAnd, BitOr, BitXor, RangeBounds, Sub};
12 use super::map::{BTreeMap, Keys};
13 use super::merge_iter::MergeIterInner;
16 // FIXME(conventions): implement bounded iterators
18 /// A set based on a B-Tree.
20 /// See [`BTreeMap`]'s documentation for a detailed discussion of this collection's performance
21 /// benefits and drawbacks.
23 /// It is a logic error for an item to be modified in such a way that the item's ordering relative
24 /// to any other item, as determined by the [`Ord`] trait, changes while it is in the set. This is
25 /// normally only possible through [`Cell`], [`RefCell`], global state, I/O, or unsafe code.
26 /// The behavior resulting from such a logic error is not specified (it could include panics,
27 /// incorrect results, aborts, memory leaks, or non-termination) but will not be undefined
30 /// [`Ord`]: core::cmp::Ord
31 /// [`Cell`]: core::cell::Cell
32 /// [`RefCell`]: core::cell::RefCell
37 /// use std::collections::BTreeSet;
39 /// // Type inference lets us omit an explicit type signature (which
40 /// // would be `BTreeSet<&str>` in this example).
41 /// let mut books = BTreeSet::new();
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");
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.",
56 /// books.remove("The Odyssey");
58 /// // Iterate over everything.
59 /// for book in &books {
60 /// println!("{}", book);
64 /// A `BTreeSet` with a known list of items can be initialized from an array:
67 /// use std::collections::BTreeSet;
69 /// let set = BTreeSet::from([1, 2, 3]);
71 #[derive(Hash, PartialEq, Eq, Ord, PartialOrd)]
72 #[stable(feature = "rust1", since = "1.0.0")]
73 #[cfg_attr(not(test), rustc_diagnostic_item = "BTreeSet")]
74 pub struct BTreeSet<T> {
78 #[stable(feature = "rust1", since = "1.0.0")]
79 impl<T: Clone> Clone for BTreeSet<T> {
80 fn clone(&self) -> Self {
81 BTreeSet { map: self.map.clone() }
84 fn clone_from(&mut self, other: &Self) {
85 self.map.clone_from(&other.map);
89 /// An iterator over the items of a `BTreeSet`.
91 /// This `struct` is created by the [`iter`] method on [`BTreeSet`].
92 /// See its documentation for more.
94 /// [`iter`]: BTreeSet::iter
95 #[must_use = "iterators are lazy and do nothing unless consumed"]
96 #[stable(feature = "rust1", since = "1.0.0")]
97 pub struct Iter<'a, T: 'a> {
98 iter: Keys<'a, T, ()>,
101 #[stable(feature = "collection_debug", since = "1.17.0")]
102 impl<T: fmt::Debug> fmt::Debug for Iter<'_, T> {
103 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
104 f.debug_tuple("Iter").field(&self.iter.clone()).finish()
108 /// An owning iterator over the items of a `BTreeSet`.
110 /// This `struct` is created by the [`into_iter`] method on [`BTreeSet`]
111 /// (provided by the [`IntoIterator`] trait). See its documentation for more.
113 /// [`into_iter`]: BTreeSet#method.into_iter
114 /// [`IntoIterator`]: core::iter::IntoIterator
115 #[stable(feature = "rust1", since = "1.0.0")]
117 pub struct IntoIter<T> {
118 iter: super::map::IntoIter<T, ()>,
121 /// An iterator over a sub-range of items in a `BTreeSet`.
123 /// This `struct` is created by the [`range`] method on [`BTreeSet`].
124 /// See its documentation for more.
126 /// [`range`]: BTreeSet::range
127 #[must_use = "iterators are lazy and do nothing unless consumed"]
129 #[stable(feature = "btree_range", since = "1.17.0")]
130 pub struct Range<'a, T: 'a> {
131 iter: super::map::Range<'a, T, ()>,
134 /// A lazy iterator producing elements in the difference of `BTreeSet`s.
136 /// This `struct` is created by the [`difference`] method on [`BTreeSet`].
137 /// See its documentation for more.
139 /// [`difference`]: BTreeSet::difference
140 #[must_use = "this returns the difference as an iterator, \
141 without modifying either input set"]
142 #[stable(feature = "rust1", since = "1.0.0")]
143 pub struct Difference<'a, T: 'a> {
144 inner: DifferenceInner<'a, T>,
147 enum DifferenceInner<'a, T: 'a> {
149 // iterate all of `self` and some of `other`, spotting matches along the way
150 self_iter: Iter<'a, T>,
151 other_iter: Peekable<Iter<'a, T>>,
154 // iterate `self`, look up in `other`
155 self_iter: Iter<'a, T>,
156 other_set: &'a BTreeSet<T>,
158 Iterate(Iter<'a, T>), // simply produce all values in `self`
161 #[stable(feature = "collection_debug", since = "1.17.0")]
162 impl<T: fmt::Debug> fmt::Debug for Difference<'_, T> {
163 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
164 f.debug_tuple("Difference").field(&self.inner).finish()
168 /// A lazy iterator producing elements in the symmetric difference of `BTreeSet`s.
170 /// This `struct` is created by the [`symmetric_difference`] method on
171 /// [`BTreeSet`]. See its documentation for more.
173 /// [`symmetric_difference`]: BTreeSet::symmetric_difference
174 #[must_use = "this returns the difference as an iterator, \
175 without modifying either input set"]
176 #[stable(feature = "rust1", since = "1.0.0")]
177 pub struct SymmetricDifference<'a, T: 'a>(MergeIterInner<Iter<'a, T>>);
179 #[stable(feature = "collection_debug", since = "1.17.0")]
180 impl<T: fmt::Debug> fmt::Debug for SymmetricDifference<'_, T> {
181 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
182 f.debug_tuple("SymmetricDifference").field(&self.0).finish()
186 /// A lazy iterator producing elements in the intersection of `BTreeSet`s.
188 /// This `struct` is created by the [`intersection`] method on [`BTreeSet`].
189 /// See its documentation for more.
191 /// [`intersection`]: BTreeSet::intersection
192 #[must_use = "this returns the intersection as an iterator, \
193 without modifying either input set"]
194 #[stable(feature = "rust1", since = "1.0.0")]
195 pub struct Intersection<'a, T: 'a> {
196 inner: IntersectionInner<'a, T>,
199 enum IntersectionInner<'a, T: 'a> {
201 // iterate similarly sized sets jointly, spotting matches along the way
206 // iterate a small set, look up in the large set
207 small_iter: Iter<'a, T>,
208 large_set: &'a BTreeSet<T>,
210 Answer(Option<&'a T>), // return a specific value or emptiness
213 #[stable(feature = "collection_debug", since = "1.17.0")]
214 impl<T: fmt::Debug> fmt::Debug for Intersection<'_, T> {
215 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
216 f.debug_tuple("Intersection").field(&self.inner).finish()
220 /// A lazy iterator producing elements in the union of `BTreeSet`s.
222 /// This `struct` is created by the [`union`] method on [`BTreeSet`].
223 /// See its documentation for more.
225 /// [`union`]: BTreeSet::union
226 #[must_use = "this returns the union as an iterator, \
227 without modifying either input set"]
228 #[stable(feature = "rust1", since = "1.0.0")]
229 pub struct Union<'a, T: 'a>(MergeIterInner<Iter<'a, T>>);
231 #[stable(feature = "collection_debug", since = "1.17.0")]
232 impl<T: fmt::Debug> fmt::Debug for Union<'_, T> {
233 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
234 f.debug_tuple("Union").field(&self.0).finish()
238 // This constant is used by functions that compare two sets.
239 // It estimates the relative size at which searching performs better
240 // than iterating, based on the benchmarks in
241 // https://github.com/ssomers/rust_bench_btreeset_intersection.
242 // It's used to divide rather than multiply sizes, to rule out overflow,
243 // and it's a power of two to make that division cheap.
244 const ITER_PERFORMANCE_TIPPING_SIZE_DIFF: usize = 16;
246 impl<T> BTreeSet<T> {
247 /// Makes a new, empty `BTreeSet`.
249 /// Does not allocate anything on its own.
254 /// # #![allow(unused_mut)]
255 /// use std::collections::BTreeSet;
257 /// let mut set: BTreeSet<i32> = BTreeSet::new();
259 #[stable(feature = "rust1", since = "1.0.0")]
260 #[rustc_const_unstable(feature = "const_btree_new", issue = "71835")]
262 pub const fn new() -> BTreeSet<T> {
263 BTreeSet { map: BTreeMap::new() }
266 /// Constructs a double-ended iterator over a sub-range of elements in the set.
267 /// The simplest way is to use the range syntax `min..max`, thus `range(min..max)` will
268 /// yield elements from min (inclusive) to max (exclusive).
269 /// The range may also be entered as `(Bound<T>, Bound<T>)`, so for example
270 /// `range((Excluded(4), Included(10)))` will yield a left-exclusive, right-inclusive
271 /// range from 4 to 10.
276 /// use std::collections::BTreeSet;
277 /// use std::ops::Bound::Included;
279 /// let mut set = BTreeSet::new();
283 /// for &elem in set.range((Included(&4), Included(&8))) {
284 /// println!("{}", elem);
286 /// assert_eq!(Some(&5), set.range(4..).next());
288 #[stable(feature = "btree_range", since = "1.17.0")]
289 pub fn range<K: ?Sized, R>(&self, range: R) -> Range<'_, T>
295 Range { iter: self.map.range(range) }
298 /// Visits the values representing the difference,
299 /// i.e., the values that are in `self` but not in `other`,
300 /// in ascending order.
305 /// use std::collections::BTreeSet;
307 /// let mut a = BTreeSet::new();
311 /// let mut b = BTreeSet::new();
315 /// let diff: Vec<_> = a.difference(&b).cloned().collect();
316 /// assert_eq!(diff, [1]);
318 #[stable(feature = "rust1", since = "1.0.0")]
319 pub fn difference<'a>(&'a self, other: &'a BTreeSet<T>) -> Difference<'a, T>
323 let (self_min, self_max) =
324 if let (Some(self_min), Some(self_max)) = (self.first(), self.last()) {
327 return Difference { inner: DifferenceInner::Iterate(self.iter()) };
329 let (other_min, other_max) =
330 if let (Some(other_min), Some(other_max)) = (other.first(), other.last()) {
331 (other_min, other_max)
333 return Difference { inner: DifferenceInner::Iterate(self.iter()) };
336 inner: match (self_min.cmp(other_max), self_max.cmp(other_min)) {
337 (Greater, _) | (_, Less) => DifferenceInner::Iterate(self.iter()),
339 let mut self_iter = self.iter();
341 DifferenceInner::Iterate(self_iter)
344 let mut self_iter = self.iter();
345 self_iter.next_back();
346 DifferenceInner::Iterate(self_iter)
348 _ if self.len() <= other.len() / ITER_PERFORMANCE_TIPPING_SIZE_DIFF => {
349 DifferenceInner::Search { self_iter: self.iter(), other_set: other }
351 _ => DifferenceInner::Stitch {
352 self_iter: self.iter(),
353 other_iter: other.iter().peekable(),
359 /// Visits the values representing the symmetric difference,
360 /// i.e., the values that are in `self` or in `other` but not in both,
361 /// in ascending order.
366 /// use std::collections::BTreeSet;
368 /// let mut a = BTreeSet::new();
372 /// let mut b = BTreeSet::new();
376 /// let sym_diff: Vec<_> = a.symmetric_difference(&b).cloned().collect();
377 /// assert_eq!(sym_diff, [1, 3]);
379 #[stable(feature = "rust1", since = "1.0.0")]
380 pub fn symmetric_difference<'a>(&'a self, other: &'a BTreeSet<T>) -> SymmetricDifference<'a, T>
384 SymmetricDifference(MergeIterInner::new(self.iter(), other.iter()))
387 /// Visits the values representing the intersection,
388 /// i.e., the values that are both in `self` and `other`,
389 /// in ascending order.
394 /// use std::collections::BTreeSet;
396 /// let mut a = BTreeSet::new();
400 /// let mut b = BTreeSet::new();
404 /// let intersection: Vec<_> = a.intersection(&b).cloned().collect();
405 /// assert_eq!(intersection, [2]);
407 #[stable(feature = "rust1", since = "1.0.0")]
408 pub fn intersection<'a>(&'a self, other: &'a BTreeSet<T>) -> Intersection<'a, T>
412 let (self_min, self_max) =
413 if let (Some(self_min), Some(self_max)) = (self.first(), self.last()) {
416 return Intersection { inner: IntersectionInner::Answer(None) };
418 let (other_min, other_max) =
419 if let (Some(other_min), Some(other_max)) = (other.first(), other.last()) {
420 (other_min, other_max)
422 return Intersection { inner: IntersectionInner::Answer(None) };
425 inner: match (self_min.cmp(other_max), self_max.cmp(other_min)) {
426 (Greater, _) | (_, Less) => IntersectionInner::Answer(None),
427 (Equal, _) => IntersectionInner::Answer(Some(self_min)),
428 (_, Equal) => IntersectionInner::Answer(Some(self_max)),
429 _ if self.len() <= other.len() / ITER_PERFORMANCE_TIPPING_SIZE_DIFF => {
430 IntersectionInner::Search { small_iter: self.iter(), large_set: other }
432 _ if other.len() <= self.len() / ITER_PERFORMANCE_TIPPING_SIZE_DIFF => {
433 IntersectionInner::Search { small_iter: other.iter(), large_set: self }
435 _ => IntersectionInner::Stitch { a: self.iter(), b: other.iter() },
440 /// Visits the values representing the union,
441 /// i.e., all the values in `self` or `other`, without duplicates,
442 /// in ascending order.
447 /// use std::collections::BTreeSet;
449 /// let mut a = BTreeSet::new();
452 /// let mut b = BTreeSet::new();
455 /// let union: Vec<_> = a.union(&b).cloned().collect();
456 /// assert_eq!(union, [1, 2]);
458 #[stable(feature = "rust1", since = "1.0.0")]
459 pub fn union<'a>(&'a self, other: &'a BTreeSet<T>) -> Union<'a, T>
463 Union(MergeIterInner::new(self.iter(), other.iter()))
466 /// Clears the set, removing all values.
471 /// use std::collections::BTreeSet;
473 /// let mut v = BTreeSet::new();
476 /// assert!(v.is_empty());
478 #[stable(feature = "rust1", since = "1.0.0")]
479 pub fn clear(&mut self) {
483 /// Returns `true` if the set contains a value.
485 /// The value may be any borrowed form of the set's value type,
486 /// but the ordering on the borrowed form *must* match the
487 /// ordering on the value type.
492 /// use std::collections::BTreeSet;
494 /// let set: BTreeSet<_> = [1, 2, 3].iter().cloned().collect();
495 /// assert_eq!(set.contains(&1), true);
496 /// assert_eq!(set.contains(&4), false);
498 #[stable(feature = "rust1", since = "1.0.0")]
499 pub fn contains<Q: ?Sized>(&self, value: &Q) -> bool
504 self.map.contains_key(value)
507 /// Returns a reference to the value in the set, if any, that is equal to the given value.
509 /// The value may be any borrowed form of the set's value type,
510 /// but the ordering on the borrowed form *must* match the
511 /// ordering on the value type.
516 /// use std::collections::BTreeSet;
518 /// let set: BTreeSet<_> = [1, 2, 3].iter().cloned().collect();
519 /// assert_eq!(set.get(&2), Some(&2));
520 /// assert_eq!(set.get(&4), None);
522 #[stable(feature = "set_recovery", since = "1.9.0")]
523 pub fn get<Q: ?Sized>(&self, value: &Q) -> Option<&T>
528 Recover::get(&self.map, value)
531 /// Returns `true` if `self` has no elements in common with `other`.
532 /// This is equivalent to checking for an empty intersection.
537 /// use std::collections::BTreeSet;
539 /// let a: BTreeSet<_> = [1, 2, 3].iter().cloned().collect();
540 /// let mut b = BTreeSet::new();
542 /// assert_eq!(a.is_disjoint(&b), true);
544 /// assert_eq!(a.is_disjoint(&b), true);
546 /// assert_eq!(a.is_disjoint(&b), false);
549 #[stable(feature = "rust1", since = "1.0.0")]
550 pub fn is_disjoint(&self, other: &BTreeSet<T>) -> bool
554 self.intersection(other).next().is_none()
557 /// Returns `true` if the set is a subset of another,
558 /// i.e., `other` contains at least all the values in `self`.
563 /// use std::collections::BTreeSet;
565 /// let sup: BTreeSet<_> = [1, 2, 3].iter().cloned().collect();
566 /// let mut set = BTreeSet::new();
568 /// assert_eq!(set.is_subset(&sup), true);
570 /// assert_eq!(set.is_subset(&sup), true);
572 /// assert_eq!(set.is_subset(&sup), false);
575 #[stable(feature = "rust1", since = "1.0.0")]
576 pub fn is_subset(&self, other: &BTreeSet<T>) -> bool
580 // Same result as self.difference(other).next().is_none()
581 // but the code below is faster (hugely in some cases).
582 if self.len() > other.len() {
585 let (self_min, self_max) =
586 if let (Some(self_min), Some(self_max)) = (self.first(), self.last()) {
589 return true; // self is empty
591 let (other_min, other_max) =
592 if let (Some(other_min), Some(other_max)) = (other.first(), other.last()) {
593 (other_min, other_max)
595 return false; // other is empty
597 let mut self_iter = self.iter();
598 match self_min.cmp(other_min) {
599 Less => return false,
605 match self_max.cmp(other_max) {
606 Greater => return false,
608 self_iter.next_back();
612 if self_iter.len() <= other.len() / ITER_PERFORMANCE_TIPPING_SIZE_DIFF {
613 for next in self_iter {
614 if !other.contains(next) {
619 let mut other_iter = other.iter();
621 other_iter.next_back();
622 let mut self_next = self_iter.next();
623 while let Some(self1) = self_next {
624 match other_iter.next().map_or(Less, |other1| self1.cmp(other1)) {
625 Less => return false,
626 Equal => self_next = self_iter.next(),
634 /// Returns `true` if the set is a superset of another,
635 /// i.e., `self` contains at least all the values in `other`.
640 /// use std::collections::BTreeSet;
642 /// let sub: BTreeSet<_> = [1, 2].iter().cloned().collect();
643 /// let mut set = BTreeSet::new();
645 /// assert_eq!(set.is_superset(&sub), false);
649 /// assert_eq!(set.is_superset(&sub), false);
652 /// assert_eq!(set.is_superset(&sub), true);
655 #[stable(feature = "rust1", since = "1.0.0")]
656 pub fn is_superset(&self, other: &BTreeSet<T>) -> bool
660 other.is_subset(self)
663 /// Returns a reference to the first value in the set, if any.
664 /// This value is always the minimum of all values in the set.
671 /// #![feature(map_first_last)]
672 /// use std::collections::BTreeSet;
674 /// let mut set = BTreeSet::new();
675 /// assert_eq!(set.first(), None);
677 /// assert_eq!(set.first(), Some(&1));
679 /// assert_eq!(set.first(), Some(&1));
682 #[unstable(feature = "map_first_last", issue = "62924")]
683 pub fn first(&self) -> Option<&T>
687 self.map.first_key_value().map(|(k, _)| k)
690 /// Returns a reference to the last value in the set, if any.
691 /// This value is always the maximum of all values in the set.
698 /// #![feature(map_first_last)]
699 /// use std::collections::BTreeSet;
701 /// let mut set = BTreeSet::new();
702 /// assert_eq!(set.last(), None);
704 /// assert_eq!(set.last(), Some(&1));
706 /// assert_eq!(set.last(), Some(&2));
709 #[unstable(feature = "map_first_last", issue = "62924")]
710 pub fn last(&self) -> Option<&T>
714 self.map.last_key_value().map(|(k, _)| k)
717 /// Removes the first value from the set and returns it, if any.
718 /// The first value is always the minimum value in the set.
723 /// #![feature(map_first_last)]
724 /// use std::collections::BTreeSet;
726 /// let mut set = BTreeSet::new();
729 /// while let Some(n) = set.pop_first() {
730 /// assert_eq!(n, 1);
732 /// assert!(set.is_empty());
734 #[unstable(feature = "map_first_last", issue = "62924")]
735 pub fn pop_first(&mut self) -> Option<T>
739 self.map.pop_first().map(|kv| kv.0)
742 /// Removes the last value from the set and returns it, if any.
743 /// The last value is always the maximum value in the set.
748 /// #![feature(map_first_last)]
749 /// use std::collections::BTreeSet;
751 /// let mut set = BTreeSet::new();
754 /// while let Some(n) = set.pop_last() {
755 /// assert_eq!(n, 1);
757 /// assert!(set.is_empty());
759 #[unstable(feature = "map_first_last", issue = "62924")]
760 pub fn pop_last(&mut self) -> Option<T>
764 self.map.pop_last().map(|kv| kv.0)
767 /// Adds a value to the set.
769 /// If the set did not have this value present, `true` is returned.
771 /// If the set did have this value present, `false` is returned, and the
772 /// entry is not updated. See the [module-level documentation] for more.
774 /// [module-level documentation]: index.html#insert-and-complex-keys
779 /// use std::collections::BTreeSet;
781 /// let mut set = BTreeSet::new();
783 /// assert_eq!(set.insert(2), true);
784 /// assert_eq!(set.insert(2), false);
785 /// assert_eq!(set.len(), 1);
787 #[stable(feature = "rust1", since = "1.0.0")]
788 pub fn insert(&mut self, value: T) -> bool
792 self.map.insert(value, ()).is_none()
795 /// Adds a value to the set, replacing the existing value, if any, that is equal to the given
796 /// one. Returns the replaced value.
801 /// use std::collections::BTreeSet;
803 /// let mut set = BTreeSet::new();
804 /// set.insert(Vec::<i32>::new());
806 /// assert_eq!(set.get(&[][..]).unwrap().capacity(), 0);
807 /// set.replace(Vec::with_capacity(10));
808 /// assert_eq!(set.get(&[][..]).unwrap().capacity(), 10);
810 #[stable(feature = "set_recovery", since = "1.9.0")]
811 pub fn replace(&mut self, value: T) -> Option<T>
815 Recover::replace(&mut self.map, value)
818 /// Removes a value from the set. Returns whether the value was
819 /// present in the set.
821 /// The value may be any borrowed form of the set's value type,
822 /// but the ordering on the borrowed form *must* match the
823 /// ordering on the value type.
828 /// use std::collections::BTreeSet;
830 /// let mut set = BTreeSet::new();
833 /// assert_eq!(set.remove(&2), true);
834 /// assert_eq!(set.remove(&2), false);
836 #[stable(feature = "rust1", since = "1.0.0")]
837 pub fn remove<Q: ?Sized>(&mut self, value: &Q) -> bool
842 self.map.remove(value).is_some()
845 /// Removes and returns the value in the set, if any, that is equal to the given one.
847 /// The value may be any borrowed form of the set's value type,
848 /// but the ordering on the borrowed form *must* match the
849 /// ordering on the value type.
854 /// use std::collections::BTreeSet;
856 /// let mut set: BTreeSet<_> = [1, 2, 3].iter().cloned().collect();
857 /// assert_eq!(set.take(&2), Some(2));
858 /// assert_eq!(set.take(&2), None);
860 #[stable(feature = "set_recovery", since = "1.9.0")]
861 pub fn take<Q: ?Sized>(&mut self, value: &Q) -> Option<T>
866 Recover::take(&mut self.map, value)
869 /// Retains only the elements specified by the predicate.
871 /// In other words, remove all elements `e` such that `f(&e)` returns `false`.
872 /// The elements are visited in ascending order.
877 /// use std::collections::BTreeSet;
879 /// let xs = [1, 2, 3, 4, 5, 6];
880 /// let mut set: BTreeSet<i32> = xs.iter().cloned().collect();
881 /// // Keep only the even numbers.
882 /// set.retain(|&k| k % 2 == 0);
883 /// assert!(set.iter().eq([2, 4, 6].iter()));
885 #[stable(feature = "btree_retain", since = "1.53.0")]
886 pub fn retain<F>(&mut self, mut f: F)
889 F: FnMut(&T) -> bool,
891 self.drain_filter(|v| !f(v));
894 /// Moves all elements from `other` into `Self`, leaving `other` empty.
899 /// use std::collections::BTreeSet;
901 /// let mut a = BTreeSet::new();
906 /// let mut b = BTreeSet::new();
911 /// a.append(&mut b);
913 /// assert_eq!(a.len(), 5);
914 /// assert_eq!(b.len(), 0);
916 /// assert!(a.contains(&1));
917 /// assert!(a.contains(&2));
918 /// assert!(a.contains(&3));
919 /// assert!(a.contains(&4));
920 /// assert!(a.contains(&5));
922 #[stable(feature = "btree_append", since = "1.11.0")]
923 pub fn append(&mut self, other: &mut Self)
927 self.map.append(&mut other.map);
930 /// Splits the collection into two at the given value. Returns everything after the given value,
931 /// including the value.
938 /// use std::collections::BTreeSet;
940 /// let mut a = BTreeSet::new();
947 /// let b = a.split_off(&3);
949 /// assert_eq!(a.len(), 2);
950 /// assert_eq!(b.len(), 3);
952 /// assert!(a.contains(&1));
953 /// assert!(a.contains(&2));
955 /// assert!(b.contains(&3));
956 /// assert!(b.contains(&17));
957 /// assert!(b.contains(&41));
959 #[stable(feature = "btree_split_off", since = "1.11.0")]
960 pub fn split_off<Q: ?Sized + Ord>(&mut self, value: &Q) -> Self
964 BTreeSet { map: self.map.split_off(value) }
967 /// Creates an iterator that visits all values in ascending order and uses a closure
968 /// to determine if a value should be removed.
970 /// If the closure returns `true`, the value is removed from the set and yielded. If
971 /// the closure returns `false`, or panics, the value remains in the set and will
974 /// If the iterator is only partially consumed or not consumed at all, each of the
975 /// remaining values is still subjected to the closure and removed and dropped if it
978 /// It is unspecified how many more values will be subjected to the closure if a
979 /// panic occurs in the closure, or if a panic occurs while dropping a value, or if
980 /// the `DrainFilter` itself is leaked.
984 /// Splitting a set into even and odd values, reusing the original set:
987 /// #![feature(btree_drain_filter)]
988 /// use std::collections::BTreeSet;
990 /// let mut set: BTreeSet<i32> = (0..8).collect();
991 /// let evens: BTreeSet<_> = set.drain_filter(|v| v % 2 == 0).collect();
993 /// assert_eq!(evens.into_iter().collect::<Vec<_>>(), vec![0, 2, 4, 6]);
994 /// assert_eq!(odds.into_iter().collect::<Vec<_>>(), vec![1, 3, 5, 7]);
996 #[unstable(feature = "btree_drain_filter", issue = "70530")]
997 pub fn drain_filter<'a, F>(&'a mut self, pred: F) -> DrainFilter<'a, T, F>
1000 F: 'a + FnMut(&T) -> bool,
1002 DrainFilter { pred, inner: self.map.drain_filter_inner() }
1005 /// Gets an iterator that visits the values in the `BTreeSet` in ascending order.
1010 /// use std::collections::BTreeSet;
1012 /// let set: BTreeSet<usize> = [1, 2, 3].iter().cloned().collect();
1013 /// let mut set_iter = set.iter();
1014 /// assert_eq!(set_iter.next(), Some(&1));
1015 /// assert_eq!(set_iter.next(), Some(&2));
1016 /// assert_eq!(set_iter.next(), Some(&3));
1017 /// assert_eq!(set_iter.next(), None);
1020 /// Values returned by the iterator are returned in ascending order:
1023 /// use std::collections::BTreeSet;
1025 /// let set: BTreeSet<usize> = [3, 1, 2].iter().cloned().collect();
1026 /// let mut set_iter = set.iter();
1027 /// assert_eq!(set_iter.next(), Some(&1));
1028 /// assert_eq!(set_iter.next(), Some(&2));
1029 /// assert_eq!(set_iter.next(), Some(&3));
1030 /// assert_eq!(set_iter.next(), None);
1032 #[stable(feature = "rust1", since = "1.0.0")]
1033 pub fn iter(&self) -> Iter<'_, T> {
1034 Iter { iter: self.map.keys() }
1037 /// Returns the number of elements in the set.
1042 /// use std::collections::BTreeSet;
1044 /// let mut v = BTreeSet::new();
1045 /// assert_eq!(v.len(), 0);
1047 /// assert_eq!(v.len(), 1);
1050 #[stable(feature = "rust1", since = "1.0.0")]
1051 #[rustc_const_unstable(feature = "const_btree_new", issue = "71835")]
1052 pub const fn len(&self) -> usize {
1056 /// Returns `true` if the set contains no elements.
1061 /// use std::collections::BTreeSet;
1063 /// let mut v = BTreeSet::new();
1064 /// assert!(v.is_empty());
1066 /// assert!(!v.is_empty());
1069 #[stable(feature = "rust1", since = "1.0.0")]
1070 #[rustc_const_unstable(feature = "const_btree_new", issue = "71835")]
1071 pub const fn is_empty(&self) -> bool {
1076 #[stable(feature = "rust1", since = "1.0.0")]
1077 impl<T: Ord> FromIterator<T> for BTreeSet<T> {
1078 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> BTreeSet<T> {
1079 let mut inputs: Vec<_> = iter.into_iter().collect();
1081 if inputs.is_empty() {
1082 return BTreeSet::new();
1085 // use stable sort to preserve the insertion order.
1087 let iter = inputs.into_iter().map(|k| (k, ()));
1088 let map = BTreeMap::bulk_build_from_sorted_iter(iter);
1093 #[stable(feature = "std_collections_from_array", since = "1.56.0")]
1094 impl<T: Ord, const N: usize> From<[T; N]> for BTreeSet<T> {
1096 /// use std::collections::BTreeSet;
1098 /// let set1 = BTreeSet::from([1, 2, 3, 4]);
1099 /// let set2: BTreeSet<_> = [1, 2, 3, 4].into();
1100 /// assert_eq!(set1, set2);
1102 fn from(mut arr: [T; N]) -> Self {
1104 return BTreeSet::new();
1107 // use stable sort to preserve the insertion order.
1109 let iter = core::array::IntoIter::new(arr).map(|k| (k, ()));
1110 let map = BTreeMap::bulk_build_from_sorted_iter(iter);
1115 #[stable(feature = "rust1", since = "1.0.0")]
1116 impl<T> IntoIterator for BTreeSet<T> {
1118 type IntoIter = IntoIter<T>;
1120 /// Gets an iterator for moving out the `BTreeSet`'s contents.
1125 /// use std::collections::BTreeSet;
1127 /// let set: BTreeSet<usize> = [1, 2, 3, 4].iter().cloned().collect();
1129 /// let v: Vec<_> = set.into_iter().collect();
1130 /// assert_eq!(v, [1, 2, 3, 4]);
1132 fn into_iter(self) -> IntoIter<T> {
1133 IntoIter { iter: self.map.into_iter() }
1137 #[stable(feature = "rust1", since = "1.0.0")]
1138 impl<'a, T> IntoIterator for &'a BTreeSet<T> {
1140 type IntoIter = Iter<'a, T>;
1142 fn into_iter(self) -> Iter<'a, T> {
1147 /// An iterator produced by calling `drain_filter` on BTreeSet.
1148 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1149 pub struct DrainFilter<'a, T, F>
1152 F: 'a + FnMut(&T) -> bool,
1155 inner: super::map::DrainFilterInner<'a, T, ()>,
1158 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1159 impl<T, F> Drop for DrainFilter<'_, T, F>
1161 F: FnMut(&T) -> bool,
1163 fn drop(&mut self) {
1164 self.for_each(drop);
1168 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1169 impl<T, F> fmt::Debug for DrainFilter<'_, T, F>
1172 F: FnMut(&T) -> bool,
1174 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1175 f.debug_tuple("DrainFilter").field(&self.inner.peek().map(|(k, _)| k)).finish()
1179 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1180 impl<'a, T, F> Iterator for DrainFilter<'_, T, F>
1182 F: 'a + FnMut(&T) -> bool,
1186 fn next(&mut self) -> Option<T> {
1187 let pred = &mut self.pred;
1188 let mut mapped_pred = |k: &T, _v: &mut ()| pred(k);
1189 self.inner.next(&mut mapped_pred).map(|(k, _)| k)
1192 fn size_hint(&self) -> (usize, Option<usize>) {
1193 self.inner.size_hint()
1197 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1198 impl<T, F> FusedIterator for DrainFilter<'_, T, F> where F: FnMut(&T) -> bool {}
1200 #[stable(feature = "rust1", since = "1.0.0")]
1201 impl<T: Ord> Extend<T> for BTreeSet<T> {
1203 fn extend<Iter: IntoIterator<Item = T>>(&mut self, iter: Iter) {
1204 iter.into_iter().for_each(move |elem| {
1210 fn extend_one(&mut self, elem: T) {
1215 #[stable(feature = "extend_ref", since = "1.2.0")]
1216 impl<'a, T: 'a + Ord + Copy> Extend<&'a T> for BTreeSet<T> {
1217 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
1218 self.extend(iter.into_iter().cloned());
1222 fn extend_one(&mut self, &elem: &'a T) {
1227 #[stable(feature = "rust1", since = "1.0.0")]
1228 impl<T> Default for BTreeSet<T> {
1229 /// Creates an empty `BTreeSet`.
1230 fn default() -> BTreeSet<T> {
1235 #[stable(feature = "rust1", since = "1.0.0")]
1236 impl<T: Ord + Clone> Sub<&BTreeSet<T>> for &BTreeSet<T> {
1237 type Output = BTreeSet<T>;
1239 /// Returns the difference of `self` and `rhs` as a new `BTreeSet<T>`.
1244 /// use std::collections::BTreeSet;
1246 /// let a: BTreeSet<_> = vec![1, 2, 3].into_iter().collect();
1247 /// let b: BTreeSet<_> = vec![3, 4, 5].into_iter().collect();
1249 /// let result = &a - &b;
1250 /// let result_vec: Vec<_> = result.into_iter().collect();
1251 /// assert_eq!(result_vec, [1, 2]);
1253 fn sub(self, rhs: &BTreeSet<T>) -> BTreeSet<T> {
1254 self.difference(rhs).cloned().collect()
1258 #[stable(feature = "rust1", since = "1.0.0")]
1259 impl<T: Ord + Clone> BitXor<&BTreeSet<T>> for &BTreeSet<T> {
1260 type Output = BTreeSet<T>;
1262 /// Returns the symmetric difference of `self` and `rhs` as a new `BTreeSet<T>`.
1267 /// use std::collections::BTreeSet;
1269 /// let a: BTreeSet<_> = vec![1, 2, 3].into_iter().collect();
1270 /// let b: BTreeSet<_> = vec![2, 3, 4].into_iter().collect();
1272 /// let result = &a ^ &b;
1273 /// let result_vec: Vec<_> = result.into_iter().collect();
1274 /// assert_eq!(result_vec, [1, 4]);
1276 fn bitxor(self, rhs: &BTreeSet<T>) -> BTreeSet<T> {
1277 self.symmetric_difference(rhs).cloned().collect()
1281 #[stable(feature = "rust1", since = "1.0.0")]
1282 impl<T: Ord + Clone> BitAnd<&BTreeSet<T>> for &BTreeSet<T> {
1283 type Output = BTreeSet<T>;
1285 /// Returns the intersection of `self` and `rhs` as a new `BTreeSet<T>`.
1290 /// use std::collections::BTreeSet;
1292 /// let a: BTreeSet<_> = vec![1, 2, 3].into_iter().collect();
1293 /// let b: BTreeSet<_> = vec![2, 3, 4].into_iter().collect();
1295 /// let result = &a & &b;
1296 /// let result_vec: Vec<_> = result.into_iter().collect();
1297 /// assert_eq!(result_vec, [2, 3]);
1299 fn bitand(self, rhs: &BTreeSet<T>) -> BTreeSet<T> {
1300 self.intersection(rhs).cloned().collect()
1304 #[stable(feature = "rust1", since = "1.0.0")]
1305 impl<T: Ord + Clone> BitOr<&BTreeSet<T>> for &BTreeSet<T> {
1306 type Output = BTreeSet<T>;
1308 /// Returns the union of `self` and `rhs` as a new `BTreeSet<T>`.
1313 /// use std::collections::BTreeSet;
1315 /// let a: BTreeSet<_> = vec![1, 2, 3].into_iter().collect();
1316 /// let b: BTreeSet<_> = vec![3, 4, 5].into_iter().collect();
1318 /// let result = &a | &b;
1319 /// let result_vec: Vec<_> = result.into_iter().collect();
1320 /// assert_eq!(result_vec, [1, 2, 3, 4, 5]);
1322 fn bitor(self, rhs: &BTreeSet<T>) -> BTreeSet<T> {
1323 self.union(rhs).cloned().collect()
1327 #[stable(feature = "rust1", since = "1.0.0")]
1328 impl<T: Debug> Debug for BTreeSet<T> {
1329 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1330 f.debug_set().entries(self.iter()).finish()
1334 #[stable(feature = "rust1", since = "1.0.0")]
1335 impl<T> Clone for Iter<'_, T> {
1336 fn clone(&self) -> Self {
1337 Iter { iter: self.iter.clone() }
1340 #[stable(feature = "rust1", since = "1.0.0")]
1341 impl<'a, T> Iterator for Iter<'a, T> {
1344 fn next(&mut self) -> Option<&'a T> {
1348 fn size_hint(&self) -> (usize, Option<usize>) {
1349 self.iter.size_hint()
1352 fn last(mut self) -> Option<&'a T> {
1356 fn min(mut self) -> Option<&'a T> {
1360 fn max(mut self) -> Option<&'a T> {
1364 #[stable(feature = "rust1", since = "1.0.0")]
1365 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
1366 fn next_back(&mut self) -> Option<&'a T> {
1367 self.iter.next_back()
1370 #[stable(feature = "rust1", since = "1.0.0")]
1371 impl<T> ExactSizeIterator for Iter<'_, T> {
1372 fn len(&self) -> usize {
1377 #[stable(feature = "fused", since = "1.26.0")]
1378 impl<T> FusedIterator for Iter<'_, T> {}
1380 #[stable(feature = "rust1", since = "1.0.0")]
1381 impl<T> Iterator for IntoIter<T> {
1384 fn next(&mut self) -> Option<T> {
1385 self.iter.next().map(|(k, _)| k)
1388 fn size_hint(&self) -> (usize, Option<usize>) {
1389 self.iter.size_hint()
1392 #[stable(feature = "rust1", since = "1.0.0")]
1393 impl<T> DoubleEndedIterator for IntoIter<T> {
1394 fn next_back(&mut self) -> Option<T> {
1395 self.iter.next_back().map(|(k, _)| k)
1398 #[stable(feature = "rust1", since = "1.0.0")]
1399 impl<T> ExactSizeIterator for IntoIter<T> {
1400 fn len(&self) -> usize {
1405 #[stable(feature = "fused", since = "1.26.0")]
1406 impl<T> FusedIterator for IntoIter<T> {}
1408 #[stable(feature = "btree_range", since = "1.17.0")]
1409 impl<T> Clone for Range<'_, T> {
1410 fn clone(&self) -> Self {
1411 Range { iter: self.iter.clone() }
1415 #[stable(feature = "btree_range", since = "1.17.0")]
1416 impl<'a, T> Iterator for Range<'a, T> {
1419 fn next(&mut self) -> Option<&'a T> {
1420 self.iter.next().map(|(k, _)| k)
1423 fn last(mut self) -> Option<&'a T> {
1427 fn min(mut self) -> Option<&'a T> {
1431 fn max(mut self) -> Option<&'a T> {
1436 #[stable(feature = "btree_range", since = "1.17.0")]
1437 impl<'a, T> DoubleEndedIterator for Range<'a, T> {
1438 fn next_back(&mut self) -> Option<&'a T> {
1439 self.iter.next_back().map(|(k, _)| k)
1443 #[stable(feature = "fused", since = "1.26.0")]
1444 impl<T> FusedIterator for Range<'_, T> {}
1446 #[stable(feature = "rust1", since = "1.0.0")]
1447 impl<T> Clone for Difference<'_, T> {
1448 fn clone(&self) -> Self {
1450 inner: match &self.inner {
1451 DifferenceInner::Stitch { self_iter, other_iter } => DifferenceInner::Stitch {
1452 self_iter: self_iter.clone(),
1453 other_iter: other_iter.clone(),
1455 DifferenceInner::Search { self_iter, other_set } => {
1456 DifferenceInner::Search { self_iter: self_iter.clone(), other_set }
1458 DifferenceInner::Iterate(iter) => DifferenceInner::Iterate(iter.clone()),
1463 #[stable(feature = "rust1", since = "1.0.0")]
1464 impl<'a, T: Ord> Iterator for Difference<'a, T> {
1467 fn next(&mut self) -> Option<&'a T> {
1468 match &mut self.inner {
1469 DifferenceInner::Stitch { self_iter, other_iter } => {
1470 let mut self_next = self_iter.next()?;
1472 match other_iter.peek().map_or(Less, |other_next| self_next.cmp(other_next)) {
1473 Less => return Some(self_next),
1475 self_next = self_iter.next()?;
1484 DifferenceInner::Search { self_iter, other_set } => loop {
1485 let self_next = self_iter.next()?;
1486 if !other_set.contains(&self_next) {
1487 return Some(self_next);
1490 DifferenceInner::Iterate(iter) => iter.next(),
1494 fn size_hint(&self) -> (usize, Option<usize>) {
1495 let (self_len, other_len) = match &self.inner {
1496 DifferenceInner::Stitch { self_iter, other_iter } => {
1497 (self_iter.len(), other_iter.len())
1499 DifferenceInner::Search { self_iter, other_set } => (self_iter.len(), other_set.len()),
1500 DifferenceInner::Iterate(iter) => (iter.len(), 0),
1502 (self_len.saturating_sub(other_len), Some(self_len))
1505 fn min(mut self) -> Option<&'a T> {
1510 #[stable(feature = "fused", since = "1.26.0")]
1511 impl<T: Ord> FusedIterator for Difference<'_, T> {}
1513 #[stable(feature = "rust1", since = "1.0.0")]
1514 impl<T> Clone for SymmetricDifference<'_, T> {
1515 fn clone(&self) -> Self {
1516 SymmetricDifference(self.0.clone())
1519 #[stable(feature = "rust1", since = "1.0.0")]
1520 impl<'a, T: Ord> Iterator for SymmetricDifference<'a, T> {
1523 fn next(&mut self) -> Option<&'a T> {
1525 let (a_next, b_next) = self.0.nexts(Self::Item::cmp);
1526 if a_next.and(b_next).is_none() {
1527 return a_next.or(b_next);
1532 fn size_hint(&self) -> (usize, Option<usize>) {
1533 let (a_len, b_len) = self.0.lens();
1534 // No checked_add, because even if a and b refer to the same set,
1535 // and T is an empty type, the storage overhead of sets limits
1536 // the number of elements to less than half the range of usize.
1537 (0, Some(a_len + b_len))
1540 fn min(mut self) -> Option<&'a T> {
1545 #[stable(feature = "fused", since = "1.26.0")]
1546 impl<T: Ord> FusedIterator for SymmetricDifference<'_, T> {}
1548 #[stable(feature = "rust1", since = "1.0.0")]
1549 impl<T> Clone for Intersection<'_, T> {
1550 fn clone(&self) -> Self {
1552 inner: match &self.inner {
1553 IntersectionInner::Stitch { a, b } => {
1554 IntersectionInner::Stitch { a: a.clone(), b: b.clone() }
1556 IntersectionInner::Search { small_iter, large_set } => {
1557 IntersectionInner::Search { small_iter: small_iter.clone(), large_set }
1559 IntersectionInner::Answer(answer) => IntersectionInner::Answer(*answer),
1564 #[stable(feature = "rust1", since = "1.0.0")]
1565 impl<'a, T: Ord> Iterator for Intersection<'a, T> {
1568 fn next(&mut self) -> Option<&'a T> {
1569 match &mut self.inner {
1570 IntersectionInner::Stitch { a, b } => {
1571 let mut a_next = a.next()?;
1572 let mut b_next = b.next()?;
1574 match a_next.cmp(b_next) {
1575 Less => a_next = a.next()?,
1576 Greater => b_next = b.next()?,
1577 Equal => return Some(a_next),
1581 IntersectionInner::Search { small_iter, large_set } => loop {
1582 let small_next = small_iter.next()?;
1583 if large_set.contains(&small_next) {
1584 return Some(small_next);
1587 IntersectionInner::Answer(answer) => answer.take(),
1591 fn size_hint(&self) -> (usize, Option<usize>) {
1593 IntersectionInner::Stitch { a, b } => (0, Some(min(a.len(), b.len()))),
1594 IntersectionInner::Search { small_iter, .. } => (0, Some(small_iter.len())),
1595 IntersectionInner::Answer(None) => (0, Some(0)),
1596 IntersectionInner::Answer(Some(_)) => (1, Some(1)),
1600 fn min(mut self) -> Option<&'a T> {
1605 #[stable(feature = "fused", since = "1.26.0")]
1606 impl<T: Ord> FusedIterator for Intersection<'_, T> {}
1608 #[stable(feature = "rust1", since = "1.0.0")]
1609 impl<T> Clone for Union<'_, T> {
1610 fn clone(&self) -> Self {
1611 Union(self.0.clone())
1614 #[stable(feature = "rust1", since = "1.0.0")]
1615 impl<'a, T: Ord> Iterator for Union<'a, T> {
1618 fn next(&mut self) -> Option<&'a T> {
1619 let (a_next, b_next) = self.0.nexts(Self::Item::cmp);
1623 fn size_hint(&self) -> (usize, Option<usize>) {
1624 let (a_len, b_len) = self.0.lens();
1625 // No checked_add - see SymmetricDifference::size_hint.
1626 (max(a_len, b_len), Some(a_len + b_len))
1629 fn min(mut self) -> Option<&'a T> {
1634 #[stable(feature = "fused", since = "1.26.0")]
1635 impl<T: Ord> FusedIterator for Union<'_, T> {}