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 /// An ordered 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 /// Iterators returned by [`BTreeSet::iter`] produce their items in order, and take worst-case
31 /// logarithmic and amortized constant time per item returned.
33 /// [`Ord`]: core::cmp::Ord
34 /// [`Cell`]: core::cell::Cell
35 /// [`RefCell`]: core::cell::RefCell
40 /// use std::collections::BTreeSet;
42 /// // Type inference lets us omit an explicit type signature (which
43 /// // would be `BTreeSet<&str>` in this example).
44 /// let mut books = BTreeSet::new();
46 /// // Add some books.
47 /// books.insert("A Dance With Dragons");
48 /// books.insert("To Kill a Mockingbird");
49 /// books.insert("The Odyssey");
50 /// books.insert("The Great Gatsby");
52 /// // Check for a specific one.
53 /// if !books.contains("The Winds of Winter") {
54 /// println!("We have {} books, but The Winds of Winter ain't one.",
59 /// books.remove("The Odyssey");
61 /// // Iterate over everything.
62 /// for book in &books {
63 /// println!("{book}");
67 /// A `BTreeSet` with a known list of items can be initialized from an array:
70 /// use std::collections::BTreeSet;
72 /// let set = BTreeSet::from([1, 2, 3]);
74 #[derive(Hash, PartialEq, Eq, Ord, PartialOrd)]
75 #[stable(feature = "rust1", since = "1.0.0")]
76 #[cfg_attr(not(test), rustc_diagnostic_item = "BTreeSet")]
77 pub struct BTreeSet<T> {
81 #[stable(feature = "rust1", since = "1.0.0")]
82 impl<T: Clone> Clone for BTreeSet<T> {
83 fn clone(&self) -> Self {
84 BTreeSet { map: self.map.clone() }
87 fn clone_from(&mut self, other: &Self) {
88 self.map.clone_from(&other.map);
92 /// An iterator over the items of a `BTreeSet`.
94 /// This `struct` is created by the [`iter`] method on [`BTreeSet`].
95 /// See its documentation for more.
97 /// [`iter`]: BTreeSet::iter
98 #[must_use = "iterators are lazy and do nothing unless consumed"]
99 #[stable(feature = "rust1", since = "1.0.0")]
100 pub struct Iter<'a, T: 'a> {
101 iter: Keys<'a, T, ()>,
104 #[stable(feature = "collection_debug", since = "1.17.0")]
105 impl<T: fmt::Debug> fmt::Debug for Iter<'_, T> {
106 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
107 f.debug_tuple("Iter").field(&self.iter.clone()).finish()
111 /// An owning iterator over the items of a `BTreeSet`.
113 /// This `struct` is created by the [`into_iter`] method on [`BTreeSet`]
114 /// (provided by the [`IntoIterator`] trait). See its documentation for more.
116 /// [`into_iter`]: BTreeSet#method.into_iter
117 /// [`IntoIterator`]: core::iter::IntoIterator
118 #[stable(feature = "rust1", since = "1.0.0")]
120 pub struct IntoIter<T> {
121 iter: super::map::IntoIter<T, ()>,
124 /// An iterator over a sub-range of items in a `BTreeSet`.
126 /// This `struct` is created by the [`range`] method on [`BTreeSet`].
127 /// See its documentation for more.
129 /// [`range`]: BTreeSet::range
130 #[must_use = "iterators are lazy and do nothing unless consumed"]
132 #[stable(feature = "btree_range", since = "1.17.0")]
133 pub struct Range<'a, T: 'a> {
134 iter: super::map::Range<'a, T, ()>,
137 /// A lazy iterator producing elements in the difference of `BTreeSet`s.
139 /// This `struct` is created by the [`difference`] method on [`BTreeSet`].
140 /// See its documentation for more.
142 /// [`difference`]: BTreeSet::difference
143 #[must_use = "this returns the difference as an iterator, \
144 without modifying either input set"]
145 #[stable(feature = "rust1", since = "1.0.0")]
146 pub struct Difference<'a, T: 'a> {
147 inner: DifferenceInner<'a, T>,
150 enum DifferenceInner<'a, T: 'a> {
152 // iterate all of `self` and some of `other`, spotting matches along the way
153 self_iter: Iter<'a, T>,
154 other_iter: Peekable<Iter<'a, T>>,
157 // iterate `self`, look up in `other`
158 self_iter: Iter<'a, T>,
159 other_set: &'a BTreeSet<T>,
161 Iterate(Iter<'a, T>), // simply produce all elements in `self`
164 #[stable(feature = "collection_debug", since = "1.17.0")]
165 impl<T: fmt::Debug> fmt::Debug for Difference<'_, T> {
166 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
167 f.debug_tuple("Difference").field(&self.inner).finish()
171 /// A lazy iterator producing elements in the symmetric difference of `BTreeSet`s.
173 /// This `struct` is created by the [`symmetric_difference`] method on
174 /// [`BTreeSet`]. See its documentation for more.
176 /// [`symmetric_difference`]: BTreeSet::symmetric_difference
177 #[must_use = "this returns the difference as an iterator, \
178 without modifying either input set"]
179 #[stable(feature = "rust1", since = "1.0.0")]
180 pub struct SymmetricDifference<'a, T: 'a>(MergeIterInner<Iter<'a, T>>);
182 #[stable(feature = "collection_debug", since = "1.17.0")]
183 impl<T: fmt::Debug> fmt::Debug for SymmetricDifference<'_, T> {
184 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
185 f.debug_tuple("SymmetricDifference").field(&self.0).finish()
189 /// A lazy iterator producing elements in the intersection of `BTreeSet`s.
191 /// This `struct` is created by the [`intersection`] method on [`BTreeSet`].
192 /// See its documentation for more.
194 /// [`intersection`]: BTreeSet::intersection
195 #[must_use = "this returns the intersection as an iterator, \
196 without modifying either input set"]
197 #[stable(feature = "rust1", since = "1.0.0")]
198 pub struct Intersection<'a, T: 'a> {
199 inner: IntersectionInner<'a, T>,
202 enum IntersectionInner<'a, T: 'a> {
204 // iterate similarly sized sets jointly, spotting matches along the way
209 // iterate a small set, look up in the large set
210 small_iter: Iter<'a, T>,
211 large_set: &'a BTreeSet<T>,
213 Answer(Option<&'a T>), // return a specific element or emptiness
216 #[stable(feature = "collection_debug", since = "1.17.0")]
217 impl<T: fmt::Debug> fmt::Debug for Intersection<'_, T> {
218 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
219 f.debug_tuple("Intersection").field(&self.inner).finish()
223 /// A lazy iterator producing elements in the union of `BTreeSet`s.
225 /// This `struct` is created by the [`union`] method on [`BTreeSet`].
226 /// See its documentation for more.
228 /// [`union`]: BTreeSet::union
229 #[must_use = "this returns the union as an iterator, \
230 without modifying either input set"]
231 #[stable(feature = "rust1", since = "1.0.0")]
232 pub struct Union<'a, T: 'a>(MergeIterInner<Iter<'a, T>>);
234 #[stable(feature = "collection_debug", since = "1.17.0")]
235 impl<T: fmt::Debug> fmt::Debug for Union<'_, T> {
236 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
237 f.debug_tuple("Union").field(&self.0).finish()
241 // This constant is used by functions that compare two sets.
242 // It estimates the relative size at which searching performs better
243 // than iterating, based on the benchmarks in
244 // https://github.com/ssomers/rust_bench_btreeset_intersection.
245 // It's used to divide rather than multiply sizes, to rule out overflow,
246 // and it's a power of two to make that division cheap.
247 const ITER_PERFORMANCE_TIPPING_SIZE_DIFF: usize = 16;
249 impl<T> BTreeSet<T> {
250 /// Makes a new, empty `BTreeSet`.
252 /// Does not allocate anything on its own.
257 /// # #![allow(unused_mut)]
258 /// use std::collections::BTreeSet;
260 /// let mut set: BTreeSet<i32> = BTreeSet::new();
262 #[stable(feature = "rust1", since = "1.0.0")]
263 #[rustc_const_unstable(feature = "const_btree_new", issue = "71835")]
265 pub const fn new() -> BTreeSet<T> {
266 BTreeSet { map: BTreeMap::new() }
269 /// Constructs a double-ended iterator over a sub-range of elements in the set.
270 /// The simplest way is to use the range syntax `min..max`, thus `range(min..max)` will
271 /// yield elements from min (inclusive) to max (exclusive).
272 /// The range may also be entered as `(Bound<T>, Bound<T>)`, so for example
273 /// `range((Excluded(4), Included(10)))` will yield a left-exclusive, right-inclusive
274 /// range from 4 to 10.
279 /// use std::collections::BTreeSet;
280 /// use std::ops::Bound::Included;
282 /// let mut set = BTreeSet::new();
286 /// for &elem in set.range((Included(&4), Included(&8))) {
287 /// println!("{elem}");
289 /// assert_eq!(Some(&5), set.range(4..).next());
291 #[stable(feature = "btree_range", since = "1.17.0")]
292 pub fn range<K: ?Sized, R>(&self, range: R) -> Range<'_, T>
298 Range { iter: self.map.range(range) }
301 /// Visits the elements representing the difference,
302 /// i.e., the elements that are in `self` but not in `other`,
303 /// in ascending order.
308 /// use std::collections::BTreeSet;
310 /// let mut a = BTreeSet::new();
314 /// let mut b = BTreeSet::new();
318 /// let diff: Vec<_> = a.difference(&b).cloned().collect();
319 /// assert_eq!(diff, [1]);
321 #[stable(feature = "rust1", since = "1.0.0")]
322 pub fn difference<'a>(&'a self, other: &'a BTreeSet<T>) -> Difference<'a, T>
326 let (self_min, self_max) =
327 if let (Some(self_min), Some(self_max)) = (self.first(), self.last()) {
330 return Difference { inner: DifferenceInner::Iterate(self.iter()) };
332 let (other_min, other_max) =
333 if let (Some(other_min), Some(other_max)) = (other.first(), other.last()) {
334 (other_min, other_max)
336 return Difference { inner: DifferenceInner::Iterate(self.iter()) };
339 inner: match (self_min.cmp(other_max), self_max.cmp(other_min)) {
340 (Greater, _) | (_, Less) => DifferenceInner::Iterate(self.iter()),
342 let mut self_iter = self.iter();
344 DifferenceInner::Iterate(self_iter)
347 let mut self_iter = self.iter();
348 self_iter.next_back();
349 DifferenceInner::Iterate(self_iter)
351 _ if self.len() <= other.len() / ITER_PERFORMANCE_TIPPING_SIZE_DIFF => {
352 DifferenceInner::Search { self_iter: self.iter(), other_set: other }
354 _ => DifferenceInner::Stitch {
355 self_iter: self.iter(),
356 other_iter: other.iter().peekable(),
362 /// Visits the elements representing the symmetric difference,
363 /// i.e., the elements that are in `self` or in `other` but not in both,
364 /// in ascending order.
369 /// use std::collections::BTreeSet;
371 /// let mut a = BTreeSet::new();
375 /// let mut b = BTreeSet::new();
379 /// let sym_diff: Vec<_> = a.symmetric_difference(&b).cloned().collect();
380 /// assert_eq!(sym_diff, [1, 3]);
382 #[stable(feature = "rust1", since = "1.0.0")]
383 pub fn symmetric_difference<'a>(&'a self, other: &'a BTreeSet<T>) -> SymmetricDifference<'a, T>
387 SymmetricDifference(MergeIterInner::new(self.iter(), other.iter()))
390 /// Visits the elements representing the intersection,
391 /// i.e., the elements that are both in `self` and `other`,
392 /// in ascending order.
397 /// use std::collections::BTreeSet;
399 /// let mut a = BTreeSet::new();
403 /// let mut b = BTreeSet::new();
407 /// let intersection: Vec<_> = a.intersection(&b).cloned().collect();
408 /// assert_eq!(intersection, [2]);
410 #[stable(feature = "rust1", since = "1.0.0")]
411 pub fn intersection<'a>(&'a self, other: &'a BTreeSet<T>) -> Intersection<'a, T>
415 let (self_min, self_max) =
416 if let (Some(self_min), Some(self_max)) = (self.first(), self.last()) {
419 return Intersection { inner: IntersectionInner::Answer(None) };
421 let (other_min, other_max) =
422 if let (Some(other_min), Some(other_max)) = (other.first(), other.last()) {
423 (other_min, other_max)
425 return Intersection { inner: IntersectionInner::Answer(None) };
428 inner: match (self_min.cmp(other_max), self_max.cmp(other_min)) {
429 (Greater, _) | (_, Less) => IntersectionInner::Answer(None),
430 (Equal, _) => IntersectionInner::Answer(Some(self_min)),
431 (_, Equal) => IntersectionInner::Answer(Some(self_max)),
432 _ if self.len() <= other.len() / ITER_PERFORMANCE_TIPPING_SIZE_DIFF => {
433 IntersectionInner::Search { small_iter: self.iter(), large_set: other }
435 _ if other.len() <= self.len() / ITER_PERFORMANCE_TIPPING_SIZE_DIFF => {
436 IntersectionInner::Search { small_iter: other.iter(), large_set: self }
438 _ => IntersectionInner::Stitch { a: self.iter(), b: other.iter() },
443 /// Visits the elements representing the union,
444 /// i.e., all the elements in `self` or `other`, without duplicates,
445 /// in ascending order.
450 /// use std::collections::BTreeSet;
452 /// let mut a = BTreeSet::new();
455 /// let mut b = BTreeSet::new();
458 /// let union: Vec<_> = a.union(&b).cloned().collect();
459 /// assert_eq!(union, [1, 2]);
461 #[stable(feature = "rust1", since = "1.0.0")]
462 pub fn union<'a>(&'a self, other: &'a BTreeSet<T>) -> Union<'a, T>
466 Union(MergeIterInner::new(self.iter(), other.iter()))
469 /// Clears the set, removing all elements.
474 /// use std::collections::BTreeSet;
476 /// let mut v = BTreeSet::new();
479 /// assert!(v.is_empty());
481 #[stable(feature = "rust1", since = "1.0.0")]
482 pub fn clear(&mut self) {
486 /// Returns `true` if the set contains an element equal to the value.
488 /// The value may be any borrowed form of the set's element type,
489 /// but the ordering on the borrowed form *must* match the
490 /// ordering on the element type.
495 /// use std::collections::BTreeSet;
497 /// let set = BTreeSet::from([1, 2, 3]);
498 /// assert_eq!(set.contains(&1), true);
499 /// assert_eq!(set.contains(&4), false);
501 #[stable(feature = "rust1", since = "1.0.0")]
502 pub fn contains<Q: ?Sized>(&self, value: &Q) -> bool
507 self.map.contains_key(value)
510 /// Returns a reference to the element in the set, if any, that is equal to
513 /// The value may be any borrowed form of the set's element type,
514 /// but the ordering on the borrowed form *must* match the
515 /// ordering on the element type.
520 /// use std::collections::BTreeSet;
522 /// let set = BTreeSet::from([1, 2, 3]);
523 /// assert_eq!(set.get(&2), Some(&2));
524 /// assert_eq!(set.get(&4), None);
526 #[stable(feature = "set_recovery", since = "1.9.0")]
527 pub fn get<Q: ?Sized>(&self, value: &Q) -> Option<&T>
532 Recover::get(&self.map, value)
535 /// Returns `true` if `self` has no elements in common with `other`.
536 /// This is equivalent to checking for an empty intersection.
541 /// use std::collections::BTreeSet;
543 /// let a = BTreeSet::from([1, 2, 3]);
544 /// let mut b = BTreeSet::new();
546 /// assert_eq!(a.is_disjoint(&b), true);
548 /// assert_eq!(a.is_disjoint(&b), true);
550 /// assert_eq!(a.is_disjoint(&b), false);
553 #[stable(feature = "rust1", since = "1.0.0")]
554 pub fn is_disjoint(&self, other: &BTreeSet<T>) -> bool
558 self.intersection(other).next().is_none()
561 /// Returns `true` if the set is a subset of another,
562 /// i.e., `other` contains at least all the elements in `self`.
567 /// use std::collections::BTreeSet;
569 /// let sup = BTreeSet::from([1, 2, 3]);
570 /// let mut set = BTreeSet::new();
572 /// assert_eq!(set.is_subset(&sup), true);
574 /// assert_eq!(set.is_subset(&sup), true);
576 /// assert_eq!(set.is_subset(&sup), false);
579 #[stable(feature = "rust1", since = "1.0.0")]
580 pub fn is_subset(&self, other: &BTreeSet<T>) -> bool
584 // Same result as self.difference(other).next().is_none()
585 // but the code below is faster (hugely in some cases).
586 if self.len() > other.len() {
589 let (self_min, self_max) =
590 if let (Some(self_min), Some(self_max)) = (self.first(), self.last()) {
593 return true; // self is empty
595 let (other_min, other_max) =
596 if let (Some(other_min), Some(other_max)) = (other.first(), other.last()) {
597 (other_min, other_max)
599 return false; // other is empty
601 let mut self_iter = self.iter();
602 match self_min.cmp(other_min) {
603 Less => return false,
609 match self_max.cmp(other_max) {
610 Greater => return false,
612 self_iter.next_back();
616 if self_iter.len() <= other.len() / ITER_PERFORMANCE_TIPPING_SIZE_DIFF {
617 for next in self_iter {
618 if !other.contains(next) {
623 let mut other_iter = other.iter();
625 other_iter.next_back();
626 let mut self_next = self_iter.next();
627 while let Some(self1) = self_next {
628 match other_iter.next().map_or(Less, |other1| self1.cmp(other1)) {
629 Less => return false,
630 Equal => self_next = self_iter.next(),
638 /// Returns `true` if the set is a superset of another,
639 /// i.e., `self` contains at least all the elements in `other`.
644 /// use std::collections::BTreeSet;
646 /// let sub = BTreeSet::from([1, 2]);
647 /// let mut set = BTreeSet::new();
649 /// assert_eq!(set.is_superset(&sub), false);
653 /// assert_eq!(set.is_superset(&sub), false);
656 /// assert_eq!(set.is_superset(&sub), true);
659 #[stable(feature = "rust1", since = "1.0.0")]
660 pub fn is_superset(&self, other: &BTreeSet<T>) -> bool
664 other.is_subset(self)
667 /// Returns a reference to the first element in the set, if any.
668 /// This element is always the minimum of all elements in the set.
675 /// #![feature(map_first_last)]
676 /// use std::collections::BTreeSet;
678 /// let mut set = BTreeSet::new();
679 /// assert_eq!(set.first(), None);
681 /// assert_eq!(set.first(), Some(&1));
683 /// assert_eq!(set.first(), Some(&1));
686 #[unstable(feature = "map_first_last", issue = "62924")]
687 pub fn first(&self) -> Option<&T>
691 self.map.first_key_value().map(|(k, _)| k)
694 /// Returns a reference to the last element in the set, if any.
695 /// This element is always the maximum of all elements in the set.
702 /// #![feature(map_first_last)]
703 /// use std::collections::BTreeSet;
705 /// let mut set = BTreeSet::new();
706 /// assert_eq!(set.last(), None);
708 /// assert_eq!(set.last(), Some(&1));
710 /// assert_eq!(set.last(), Some(&2));
713 #[unstable(feature = "map_first_last", issue = "62924")]
714 pub fn last(&self) -> Option<&T>
718 self.map.last_key_value().map(|(k, _)| k)
721 /// Removes the first element from the set and returns it, if any.
722 /// The first element is always the minimum element in the set.
727 /// #![feature(map_first_last)]
728 /// use std::collections::BTreeSet;
730 /// let mut set = BTreeSet::new();
733 /// while let Some(n) = set.pop_first() {
734 /// assert_eq!(n, 1);
736 /// assert!(set.is_empty());
738 #[unstable(feature = "map_first_last", issue = "62924")]
739 pub fn pop_first(&mut self) -> Option<T>
743 self.map.pop_first().map(|kv| kv.0)
746 /// Removes the last element from the set and returns it, if any.
747 /// The last element is always the maximum element in the set.
752 /// #![feature(map_first_last)]
753 /// use std::collections::BTreeSet;
755 /// let mut set = BTreeSet::new();
758 /// while let Some(n) = set.pop_last() {
759 /// assert_eq!(n, 1);
761 /// assert!(set.is_empty());
763 #[unstable(feature = "map_first_last", issue = "62924")]
764 pub fn pop_last(&mut self) -> Option<T>
768 self.map.pop_last().map(|kv| kv.0)
771 /// Adds a value to the set.
773 /// If the set did not have an equal element present, `true` is returned.
775 /// If the set did have an equal element present, `false` is returned, and
776 /// the entry is not updated. See the [module-level documentation] for more.
778 /// [module-level documentation]: index.html#insert-and-complex-keys
783 /// use std::collections::BTreeSet;
785 /// let mut set = BTreeSet::new();
787 /// assert_eq!(set.insert(2), true);
788 /// assert_eq!(set.insert(2), false);
789 /// assert_eq!(set.len(), 1);
791 #[stable(feature = "rust1", since = "1.0.0")]
792 pub fn insert(&mut self, value: T) -> bool
796 self.map.insert(value, ()).is_none()
799 /// Adds a value to the set, replacing the existing element, if any, that is
800 /// equal to the value. Returns the replaced element.
805 /// use std::collections::BTreeSet;
807 /// let mut set = BTreeSet::new();
808 /// set.insert(Vec::<i32>::new());
810 /// assert_eq!(set.get(&[][..]).unwrap().capacity(), 0);
811 /// set.replace(Vec::with_capacity(10));
812 /// assert_eq!(set.get(&[][..]).unwrap().capacity(), 10);
814 #[stable(feature = "set_recovery", since = "1.9.0")]
815 pub fn replace(&mut self, value: T) -> Option<T>
819 Recover::replace(&mut self.map, value)
822 /// If the set contains an element equal to the value, removes it from the
823 /// set and drops it. Returns whether such an element was present.
825 /// The value may be any borrowed form of the set's element type,
826 /// but the ordering on the borrowed form *must* match the
827 /// ordering on the element type.
832 /// use std::collections::BTreeSet;
834 /// let mut set = BTreeSet::new();
837 /// assert_eq!(set.remove(&2), true);
838 /// assert_eq!(set.remove(&2), false);
840 #[stable(feature = "rust1", since = "1.0.0")]
841 pub fn remove<Q: ?Sized>(&mut self, value: &Q) -> bool
846 self.map.remove(value).is_some()
849 /// Removes and returns the element in the set, if any, that is equal to
852 /// The value may be any borrowed form of the set's element type,
853 /// but the ordering on the borrowed form *must* match the
854 /// ordering on the element type.
859 /// use std::collections::BTreeSet;
861 /// let mut set = BTreeSet::from([1, 2, 3]);
862 /// assert_eq!(set.take(&2), Some(2));
863 /// assert_eq!(set.take(&2), None);
865 #[stable(feature = "set_recovery", since = "1.9.0")]
866 pub fn take<Q: ?Sized>(&mut self, value: &Q) -> Option<T>
871 Recover::take(&mut self.map, value)
874 /// Retains only the elements specified by the predicate.
876 /// In other words, remove all elements `e` for which `f(&e)` returns `false`.
877 /// The elements are visited in ascending order.
882 /// use std::collections::BTreeSet;
884 /// let mut set = BTreeSet::from([1, 2, 3, 4, 5, 6]);
885 /// // Keep only the even numbers.
886 /// set.retain(|&k| k % 2 == 0);
887 /// assert!(set.iter().eq([2, 4, 6].iter()));
889 #[stable(feature = "btree_retain", since = "1.53.0")]
890 pub fn retain<F>(&mut self, mut f: F)
893 F: FnMut(&T) -> bool,
895 self.drain_filter(|v| !f(v));
898 /// Moves all elements from `other` into `self`, leaving `other` empty.
903 /// use std::collections::BTreeSet;
905 /// let mut a = BTreeSet::new();
910 /// let mut b = BTreeSet::new();
915 /// a.append(&mut b);
917 /// assert_eq!(a.len(), 5);
918 /// assert_eq!(b.len(), 0);
920 /// assert!(a.contains(&1));
921 /// assert!(a.contains(&2));
922 /// assert!(a.contains(&3));
923 /// assert!(a.contains(&4));
924 /// assert!(a.contains(&5));
926 #[stable(feature = "btree_append", since = "1.11.0")]
927 pub fn append(&mut self, other: &mut Self)
931 self.map.append(&mut other.map);
934 /// Splits the collection into two at the value. Returns a new collection
935 /// with all elements greater than or equal to the value.
942 /// use std::collections::BTreeSet;
944 /// let mut a = BTreeSet::new();
951 /// let b = a.split_off(&3);
953 /// assert_eq!(a.len(), 2);
954 /// assert_eq!(b.len(), 3);
956 /// assert!(a.contains(&1));
957 /// assert!(a.contains(&2));
959 /// assert!(b.contains(&3));
960 /// assert!(b.contains(&17));
961 /// assert!(b.contains(&41));
963 #[stable(feature = "btree_split_off", since = "1.11.0")]
964 pub fn split_off<Q: ?Sized + Ord>(&mut self, value: &Q) -> Self
968 BTreeSet { map: self.map.split_off(value) }
971 /// Creates an iterator that visits all elements in ascending order and
972 /// uses a closure to determine if an element should be removed.
974 /// If the closure returns `true`, the element is removed from the set and
975 /// yielded. If the closure returns `false`, or panics, the element remains
976 /// in the set and will not be yielded.
978 /// If the iterator is only partially consumed or not consumed at all, each
979 /// of the remaining elements is still subjected to the closure and removed
980 /// and dropped if it returns `true`.
982 /// It is unspecified how many more elements will be subjected to the
983 /// closure if a panic occurs in the closure, or if a panic occurs while
984 /// dropping an element, or if the `DrainFilter` itself is leaked.
988 /// Splitting a set into even and odd values, reusing the original set:
991 /// #![feature(btree_drain_filter)]
992 /// use std::collections::BTreeSet;
994 /// let mut set: BTreeSet<i32> = (0..8).collect();
995 /// let evens: BTreeSet<_> = set.drain_filter(|v| v % 2 == 0).collect();
997 /// assert_eq!(evens.into_iter().collect::<Vec<_>>(), vec![0, 2, 4, 6]);
998 /// assert_eq!(odds.into_iter().collect::<Vec<_>>(), vec![1, 3, 5, 7]);
1000 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1001 pub fn drain_filter<'a, F>(&'a mut self, pred: F) -> DrainFilter<'a, T, F>
1004 F: 'a + FnMut(&T) -> bool,
1006 DrainFilter { pred, inner: self.map.drain_filter_inner() }
1009 /// Gets an iterator that visits the elements in the `BTreeSet` in ascending
1015 /// use std::collections::BTreeSet;
1017 /// let set = BTreeSet::from([1, 2, 3]);
1018 /// let mut set_iter = set.iter();
1019 /// assert_eq!(set_iter.next(), Some(&1));
1020 /// assert_eq!(set_iter.next(), Some(&2));
1021 /// assert_eq!(set_iter.next(), Some(&3));
1022 /// assert_eq!(set_iter.next(), None);
1025 /// Values returned by the iterator are returned in ascending order:
1028 /// use std::collections::BTreeSet;
1030 /// let set = BTreeSet::from([3, 1, 2]);
1031 /// let mut set_iter = set.iter();
1032 /// assert_eq!(set_iter.next(), Some(&1));
1033 /// assert_eq!(set_iter.next(), Some(&2));
1034 /// assert_eq!(set_iter.next(), Some(&3));
1035 /// assert_eq!(set_iter.next(), None);
1037 #[stable(feature = "rust1", since = "1.0.0")]
1038 pub fn iter(&self) -> Iter<'_, T> {
1039 Iter { iter: self.map.keys() }
1042 /// Returns the number of elements in the set.
1047 /// use std::collections::BTreeSet;
1049 /// let mut v = BTreeSet::new();
1050 /// assert_eq!(v.len(), 0);
1052 /// assert_eq!(v.len(), 1);
1055 #[stable(feature = "rust1", since = "1.0.0")]
1056 #[rustc_const_unstable(feature = "const_btree_new", issue = "71835")]
1057 pub const fn len(&self) -> usize {
1061 /// Returns `true` if the set contains no elements.
1066 /// use std::collections::BTreeSet;
1068 /// let mut v = BTreeSet::new();
1069 /// assert!(v.is_empty());
1071 /// assert!(!v.is_empty());
1074 #[stable(feature = "rust1", since = "1.0.0")]
1075 #[rustc_const_unstable(feature = "const_btree_new", issue = "71835")]
1076 pub const fn is_empty(&self) -> bool {
1081 #[stable(feature = "rust1", since = "1.0.0")]
1082 impl<T: Ord> FromIterator<T> for BTreeSet<T> {
1083 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> BTreeSet<T> {
1084 let mut inputs: Vec<_> = iter.into_iter().collect();
1086 if inputs.is_empty() {
1087 return BTreeSet::new();
1090 // use stable sort to preserve the insertion order.
1092 let iter = inputs.into_iter().map(|k| (k, ()));
1093 let map = BTreeMap::bulk_build_from_sorted_iter(iter);
1098 #[stable(feature = "std_collections_from_array", since = "1.56.0")]
1099 impl<T: Ord, const N: usize> From<[T; N]> for BTreeSet<T> {
1100 /// Converts a `[T; N]` into a `BTreeSet<T>`.
1103 /// use std::collections::BTreeSet;
1105 /// let set1 = BTreeSet::from([1, 2, 3, 4]);
1106 /// let set2: BTreeSet<_> = [1, 2, 3, 4].into();
1107 /// assert_eq!(set1, set2);
1109 fn from(mut arr: [T; N]) -> Self {
1111 return BTreeSet::new();
1114 // use stable sort to preserve the insertion order.
1116 let iter = IntoIterator::into_iter(arr).map(|k| (k, ()));
1117 let map = BTreeMap::bulk_build_from_sorted_iter(iter);
1122 #[stable(feature = "rust1", since = "1.0.0")]
1123 impl<T> IntoIterator for BTreeSet<T> {
1125 type IntoIter = IntoIter<T>;
1127 /// Gets an iterator for moving out the `BTreeSet`'s contents.
1132 /// use std::collections::BTreeSet;
1134 /// let set = BTreeSet::from([1, 2, 3, 4]);
1136 /// let v: Vec<_> = set.into_iter().collect();
1137 /// assert_eq!(v, [1, 2, 3, 4]);
1139 fn into_iter(self) -> IntoIter<T> {
1140 IntoIter { iter: self.map.into_iter() }
1144 #[stable(feature = "rust1", since = "1.0.0")]
1145 impl<'a, T> IntoIterator for &'a BTreeSet<T> {
1147 type IntoIter = Iter<'a, T>;
1149 fn into_iter(self) -> Iter<'a, T> {
1154 /// An iterator produced by calling `drain_filter` on BTreeSet.
1155 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1156 pub struct DrainFilter<'a, T, F>
1159 F: 'a + FnMut(&T) -> bool,
1162 inner: super::map::DrainFilterInner<'a, T, ()>,
1165 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1166 impl<T, F> Drop for DrainFilter<'_, T, F>
1168 F: FnMut(&T) -> bool,
1170 fn drop(&mut self) {
1171 self.for_each(drop);
1175 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1176 impl<T, F> fmt::Debug for DrainFilter<'_, T, F>
1179 F: FnMut(&T) -> bool,
1181 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1182 f.debug_tuple("DrainFilter").field(&self.inner.peek().map(|(k, _)| k)).finish()
1186 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1187 impl<'a, T, F> Iterator for DrainFilter<'_, T, F>
1189 F: 'a + FnMut(&T) -> bool,
1193 fn next(&mut self) -> Option<T> {
1194 let pred = &mut self.pred;
1195 let mut mapped_pred = |k: &T, _v: &mut ()| pred(k);
1196 self.inner.next(&mut mapped_pred).map(|(k, _)| k)
1199 fn size_hint(&self) -> (usize, Option<usize>) {
1200 self.inner.size_hint()
1204 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1205 impl<T, F> FusedIterator for DrainFilter<'_, T, F> where F: FnMut(&T) -> bool {}
1207 #[stable(feature = "rust1", since = "1.0.0")]
1208 impl<T: Ord> Extend<T> for BTreeSet<T> {
1210 fn extend<Iter: IntoIterator<Item = T>>(&mut self, iter: Iter) {
1211 iter.into_iter().for_each(move |elem| {
1217 fn extend_one(&mut self, elem: T) {
1222 #[stable(feature = "extend_ref", since = "1.2.0")]
1223 impl<'a, T: 'a + Ord + Copy> Extend<&'a T> for BTreeSet<T> {
1224 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
1225 self.extend(iter.into_iter().cloned());
1229 fn extend_one(&mut self, &elem: &'a T) {
1234 #[stable(feature = "rust1", since = "1.0.0")]
1235 impl<T> Default for BTreeSet<T> {
1236 /// Creates an empty `BTreeSet`.
1237 fn default() -> BTreeSet<T> {
1242 #[stable(feature = "rust1", since = "1.0.0")]
1243 impl<T: Ord + Clone> Sub<&BTreeSet<T>> for &BTreeSet<T> {
1244 type Output = BTreeSet<T>;
1246 /// Returns the difference of `self` and `rhs` as a new `BTreeSet<T>`.
1251 /// use std::collections::BTreeSet;
1253 /// let a = BTreeSet::from([1, 2, 3]);
1254 /// let b = BTreeSet::from([3, 4, 5]);
1256 /// let result = &a - &b;
1257 /// let result_vec: Vec<_> = result.into_iter().collect();
1258 /// assert_eq!(result_vec, [1, 2]);
1260 fn sub(self, rhs: &BTreeSet<T>) -> BTreeSet<T> {
1261 self.difference(rhs).cloned().collect()
1265 #[stable(feature = "rust1", since = "1.0.0")]
1266 impl<T: Ord + Clone> BitXor<&BTreeSet<T>> for &BTreeSet<T> {
1267 type Output = BTreeSet<T>;
1269 /// Returns the symmetric difference of `self` and `rhs` as a new `BTreeSet<T>`.
1274 /// use std::collections::BTreeSet;
1276 /// let a = BTreeSet::from([1, 2, 3]);
1277 /// let b = BTreeSet::from([2, 3, 4]);
1279 /// let result = &a ^ &b;
1280 /// let result_vec: Vec<_> = result.into_iter().collect();
1281 /// assert_eq!(result_vec, [1, 4]);
1283 fn bitxor(self, rhs: &BTreeSet<T>) -> BTreeSet<T> {
1284 self.symmetric_difference(rhs).cloned().collect()
1288 #[stable(feature = "rust1", since = "1.0.0")]
1289 impl<T: Ord + Clone> BitAnd<&BTreeSet<T>> for &BTreeSet<T> {
1290 type Output = BTreeSet<T>;
1292 /// Returns the intersection of `self` and `rhs` as a new `BTreeSet<T>`.
1297 /// use std::collections::BTreeSet;
1299 /// let a = BTreeSet::from([1, 2, 3]);
1300 /// let b = BTreeSet::from([2, 3, 4]);
1302 /// let result = &a & &b;
1303 /// let result_vec: Vec<_> = result.into_iter().collect();
1304 /// assert_eq!(result_vec, [2, 3]);
1306 fn bitand(self, rhs: &BTreeSet<T>) -> BTreeSet<T> {
1307 self.intersection(rhs).cloned().collect()
1311 #[stable(feature = "rust1", since = "1.0.0")]
1312 impl<T: Ord + Clone> BitOr<&BTreeSet<T>> for &BTreeSet<T> {
1313 type Output = BTreeSet<T>;
1315 /// Returns the union of `self` and `rhs` as a new `BTreeSet<T>`.
1320 /// use std::collections::BTreeSet;
1322 /// let a = BTreeSet::from([1, 2, 3]);
1323 /// let b = BTreeSet::from([3, 4, 5]);
1325 /// let result = &a | &b;
1326 /// let result_vec: Vec<_> = result.into_iter().collect();
1327 /// assert_eq!(result_vec, [1, 2, 3, 4, 5]);
1329 fn bitor(self, rhs: &BTreeSet<T>) -> BTreeSet<T> {
1330 self.union(rhs).cloned().collect()
1334 #[stable(feature = "rust1", since = "1.0.0")]
1335 impl<T: Debug> Debug for BTreeSet<T> {
1336 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1337 f.debug_set().entries(self.iter()).finish()
1341 #[stable(feature = "rust1", since = "1.0.0")]
1342 impl<T> Clone for Iter<'_, T> {
1343 fn clone(&self) -> Self {
1344 Iter { iter: self.iter.clone() }
1347 #[stable(feature = "rust1", since = "1.0.0")]
1348 impl<'a, T> Iterator for Iter<'a, T> {
1351 fn next(&mut self) -> Option<&'a T> {
1355 fn size_hint(&self) -> (usize, Option<usize>) {
1356 self.iter.size_hint()
1359 fn last(mut self) -> Option<&'a T> {
1363 fn min(mut self) -> Option<&'a T> {
1367 fn max(mut self) -> Option<&'a T> {
1371 #[stable(feature = "rust1", since = "1.0.0")]
1372 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
1373 fn next_back(&mut self) -> Option<&'a T> {
1374 self.iter.next_back()
1377 #[stable(feature = "rust1", since = "1.0.0")]
1378 impl<T> ExactSizeIterator for Iter<'_, T> {
1379 fn len(&self) -> usize {
1384 #[stable(feature = "fused", since = "1.26.0")]
1385 impl<T> FusedIterator for Iter<'_, T> {}
1387 #[stable(feature = "rust1", since = "1.0.0")]
1388 impl<T> Iterator for IntoIter<T> {
1391 fn next(&mut self) -> Option<T> {
1392 self.iter.next().map(|(k, _)| k)
1395 fn size_hint(&self) -> (usize, Option<usize>) {
1396 self.iter.size_hint()
1399 #[stable(feature = "rust1", since = "1.0.0")]
1400 impl<T> DoubleEndedIterator for IntoIter<T> {
1401 fn next_back(&mut self) -> Option<T> {
1402 self.iter.next_back().map(|(k, _)| k)
1405 #[stable(feature = "rust1", since = "1.0.0")]
1406 impl<T> ExactSizeIterator for IntoIter<T> {
1407 fn len(&self) -> usize {
1412 #[stable(feature = "fused", since = "1.26.0")]
1413 impl<T> FusedIterator for IntoIter<T> {}
1415 #[stable(feature = "btree_range", since = "1.17.0")]
1416 impl<T> Clone for Range<'_, T> {
1417 fn clone(&self) -> Self {
1418 Range { iter: self.iter.clone() }
1422 #[stable(feature = "btree_range", since = "1.17.0")]
1423 impl<'a, T> Iterator for Range<'a, T> {
1426 fn next(&mut self) -> Option<&'a T> {
1427 self.iter.next().map(|(k, _)| k)
1430 fn last(mut self) -> Option<&'a T> {
1434 fn min(mut self) -> Option<&'a T> {
1438 fn max(mut self) -> Option<&'a T> {
1443 #[stable(feature = "btree_range", since = "1.17.0")]
1444 impl<'a, T> DoubleEndedIterator for Range<'a, T> {
1445 fn next_back(&mut self) -> Option<&'a T> {
1446 self.iter.next_back().map(|(k, _)| k)
1450 #[stable(feature = "fused", since = "1.26.0")]
1451 impl<T> FusedIterator for Range<'_, T> {}
1453 #[stable(feature = "rust1", since = "1.0.0")]
1454 impl<T> Clone for Difference<'_, T> {
1455 fn clone(&self) -> Self {
1457 inner: match &self.inner {
1458 DifferenceInner::Stitch { self_iter, other_iter } => DifferenceInner::Stitch {
1459 self_iter: self_iter.clone(),
1460 other_iter: other_iter.clone(),
1462 DifferenceInner::Search { self_iter, other_set } => {
1463 DifferenceInner::Search { self_iter: self_iter.clone(), other_set }
1465 DifferenceInner::Iterate(iter) => DifferenceInner::Iterate(iter.clone()),
1470 #[stable(feature = "rust1", since = "1.0.0")]
1471 impl<'a, T: Ord> Iterator for Difference<'a, T> {
1474 fn next(&mut self) -> Option<&'a T> {
1475 match &mut self.inner {
1476 DifferenceInner::Stitch { self_iter, other_iter } => {
1477 let mut self_next = self_iter.next()?;
1479 match other_iter.peek().map_or(Less, |other_next| self_next.cmp(other_next)) {
1480 Less => return Some(self_next),
1482 self_next = self_iter.next()?;
1491 DifferenceInner::Search { self_iter, other_set } => loop {
1492 let self_next = self_iter.next()?;
1493 if !other_set.contains(&self_next) {
1494 return Some(self_next);
1497 DifferenceInner::Iterate(iter) => iter.next(),
1501 fn size_hint(&self) -> (usize, Option<usize>) {
1502 let (self_len, other_len) = match &self.inner {
1503 DifferenceInner::Stitch { self_iter, other_iter } => {
1504 (self_iter.len(), other_iter.len())
1506 DifferenceInner::Search { self_iter, other_set } => (self_iter.len(), other_set.len()),
1507 DifferenceInner::Iterate(iter) => (iter.len(), 0),
1509 (self_len.saturating_sub(other_len), Some(self_len))
1512 fn min(mut self) -> Option<&'a T> {
1517 #[stable(feature = "fused", since = "1.26.0")]
1518 impl<T: Ord> FusedIterator for Difference<'_, T> {}
1520 #[stable(feature = "rust1", since = "1.0.0")]
1521 impl<T> Clone for SymmetricDifference<'_, T> {
1522 fn clone(&self) -> Self {
1523 SymmetricDifference(self.0.clone())
1526 #[stable(feature = "rust1", since = "1.0.0")]
1527 impl<'a, T: Ord> Iterator for SymmetricDifference<'a, T> {
1530 fn next(&mut self) -> Option<&'a T> {
1532 let (a_next, b_next) = self.0.nexts(Self::Item::cmp);
1533 if a_next.and(b_next).is_none() {
1534 return a_next.or(b_next);
1539 fn size_hint(&self) -> (usize, Option<usize>) {
1540 let (a_len, b_len) = self.0.lens();
1541 // No checked_add, because even if a and b refer to the same set,
1542 // and T is a zero-sized type, the storage overhead of sets limits
1543 // the number of elements to less than half the range of usize.
1544 (0, Some(a_len + b_len))
1547 fn min(mut self) -> Option<&'a T> {
1552 #[stable(feature = "fused", since = "1.26.0")]
1553 impl<T: Ord> FusedIterator for SymmetricDifference<'_, T> {}
1555 #[stable(feature = "rust1", since = "1.0.0")]
1556 impl<T> Clone for Intersection<'_, T> {
1557 fn clone(&self) -> Self {
1559 inner: match &self.inner {
1560 IntersectionInner::Stitch { a, b } => {
1561 IntersectionInner::Stitch { a: a.clone(), b: b.clone() }
1563 IntersectionInner::Search { small_iter, large_set } => {
1564 IntersectionInner::Search { small_iter: small_iter.clone(), large_set }
1566 IntersectionInner::Answer(answer) => IntersectionInner::Answer(*answer),
1571 #[stable(feature = "rust1", since = "1.0.0")]
1572 impl<'a, T: Ord> Iterator for Intersection<'a, T> {
1575 fn next(&mut self) -> Option<&'a T> {
1576 match &mut self.inner {
1577 IntersectionInner::Stitch { a, b } => {
1578 let mut a_next = a.next()?;
1579 let mut b_next = b.next()?;
1581 match a_next.cmp(b_next) {
1582 Less => a_next = a.next()?,
1583 Greater => b_next = b.next()?,
1584 Equal => return Some(a_next),
1588 IntersectionInner::Search { small_iter, large_set } => loop {
1589 let small_next = small_iter.next()?;
1590 if large_set.contains(&small_next) {
1591 return Some(small_next);
1594 IntersectionInner::Answer(answer) => answer.take(),
1598 fn size_hint(&self) -> (usize, Option<usize>) {
1600 IntersectionInner::Stitch { a, b } => (0, Some(min(a.len(), b.len()))),
1601 IntersectionInner::Search { small_iter, .. } => (0, Some(small_iter.len())),
1602 IntersectionInner::Answer(None) => (0, Some(0)),
1603 IntersectionInner::Answer(Some(_)) => (1, Some(1)),
1607 fn min(mut self) -> Option<&'a T> {
1612 #[stable(feature = "fused", since = "1.26.0")]
1613 impl<T: Ord> FusedIterator for Intersection<'_, T> {}
1615 #[stable(feature = "rust1", since = "1.0.0")]
1616 impl<T> Clone for Union<'_, T> {
1617 fn clone(&self) -> Self {
1618 Union(self.0.clone())
1621 #[stable(feature = "rust1", since = "1.0.0")]
1622 impl<'a, T: Ord> Iterator for Union<'a, T> {
1625 fn next(&mut self) -> Option<&'a T> {
1626 let (a_next, b_next) = self.0.nexts(Self::Item::cmp);
1630 fn size_hint(&self) -> (usize, Option<usize>) {
1631 let (a_len, b_len) = self.0.lens();
1632 // No checked_add - see SymmetricDifference::size_hint.
1633 (max(a_len, b_len), Some(a_len + b_len))
1636 fn min(mut self) -> Option<&'a T> {
1641 #[stable(feature = "fused", since = "1.26.0")]
1642 impl<T: Ord> FusedIterator for Union<'_, T> {}