1 // This is pretty much entirely stolen from TreeSet, since BTreeMap has an identical interface
4 use core::borrow::Borrow;
5 use core::cmp::Ordering::{Equal, Greater, Less};
6 use core::cmp::{max, min};
7 use core::fmt::{self, Debug};
8 use core::iter::{FromIterator, FusedIterator, Peekable};
9 use core::ops::{BitAnd, BitOr, BitXor, RangeBounds, Sub};
11 use super::map::{BTreeMap, Keys};
14 // FIXME(conventions): implement bounded iterators
16 /// A set based on a B-Tree.
18 /// See [`BTreeMap`]'s documentation for a detailed discussion of this collection's performance
19 /// benefits and drawbacks.
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.
25 /// [`BTreeMap`]: struct.BTreeMap.html
26 /// [`Ord`]: ../../std/cmp/trait.Ord.html
27 /// [`Cell`]: ../../std/cell/struct.Cell.html
28 /// [`RefCell`]: ../../std/cell/struct.RefCell.html
33 /// use std::collections::BTreeSet;
35 /// // Type inference lets us omit an explicit type signature (which
36 /// // would be `BTreeSet<&str>` in this example).
37 /// let mut books = BTreeSet::new();
39 /// // Add some books.
40 /// books.insert("A Dance With Dragons");
41 /// books.insert("To Kill a Mockingbird");
42 /// books.insert("The Odyssey");
43 /// books.insert("The Great Gatsby");
45 /// // Check for a specific one.
46 /// if !books.contains("The Winds of Winter") {
47 /// println!("We have {} books, but The Winds of Winter ain't one.",
52 /// books.remove("The Odyssey");
54 /// // Iterate over everything.
55 /// for book in &books {
56 /// println!("{}", book);
59 #[derive(Hash, PartialEq, Eq, Ord, PartialOrd)]
60 #[stable(feature = "rust1", since = "1.0.0")]
61 pub struct BTreeSet<T> {
65 #[stable(feature = "rust1", since = "1.0.0")]
66 impl<T: Clone> Clone for BTreeSet<T> {
67 fn clone(&self) -> Self {
68 BTreeSet { map: self.map.clone() }
71 fn clone_from(&mut self, other: &Self) {
72 self.map.clone_from(&other.map);
76 /// An iterator over the items of a `BTreeSet`.
78 /// This `struct` is created by the [`iter`] method on [`BTreeSet`].
79 /// See its documentation for more.
81 /// [`BTreeSet`]: struct.BTreeSet.html
82 /// [`iter`]: struct.BTreeSet.html#method.iter
83 #[stable(feature = "rust1", since = "1.0.0")]
84 pub struct Iter<'a, T: 'a> {
85 iter: Keys<'a, T, ()>,
88 #[stable(feature = "collection_debug", since = "1.17.0")]
89 impl<T: fmt::Debug> fmt::Debug for Iter<'_, T> {
90 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
91 f.debug_tuple("Iter").field(&self.iter.clone()).finish()
95 /// An owning iterator over the items of a `BTreeSet`.
97 /// This `struct` is created by the [`into_iter`] method on [`BTreeSet`]
98 /// (provided by the `IntoIterator` trait). See its documentation for more.
100 /// [`BTreeSet`]: struct.BTreeSet.html
101 /// [`into_iter`]: struct.BTreeSet.html#method.into_iter
102 #[stable(feature = "rust1", since = "1.0.0")]
104 pub struct IntoIter<T> {
105 iter: super::map::IntoIter<T, ()>,
108 /// An iterator over a sub-range of items in a `BTreeSet`.
110 /// This `struct` is created by the [`range`] method on [`BTreeSet`].
111 /// See its documentation for more.
113 /// [`BTreeSet`]: struct.BTreeSet.html
114 /// [`range`]: struct.BTreeSet.html#method.range
116 #[stable(feature = "btree_range", since = "1.17.0")]
117 pub struct Range<'a, T: 'a> {
118 iter: super::map::Range<'a, T, ()>,
121 /// Core of SymmetricDifference and Union.
122 /// More efficient than btree.map.MergeIter,
123 /// and crucially for SymmetricDifference, nexts() reports on both sides.
125 struct MergeIterInner<I>
132 peeked: Option<MergeIterPeeked<I>>,
135 #[derive(Copy, Clone, Debug)]
136 enum MergeIterPeeked<I: Iterator> {
141 impl<I> MergeIterInner<I>
143 I: ExactSizeIterator + FusedIterator,
146 fn new(a: I, b: I) -> Self {
147 MergeIterInner { a, b, peeked: None }
150 fn nexts(&mut self) -> (Option<I::Item>, Option<I::Item>) {
151 let mut a_next = match self.peeked {
152 Some(MergeIterPeeked::A(next)) => Some(next),
155 let mut b_next = match self.peeked {
156 Some(MergeIterPeeked::B(next)) => Some(next),
159 let ord = match (a_next, b_next) {
160 (None, None) => Equal,
162 (None, _) => Greater,
163 (Some(a1), Some(b1)) => a1.cmp(&b1),
165 self.peeked = match ord {
166 Less => b_next.take().map(MergeIterPeeked::B),
168 Greater => a_next.take().map(MergeIterPeeked::A),
173 fn lens(&self) -> (usize, usize) {
175 Some(MergeIterPeeked::A(_)) => (1 + self.a.len(), self.b.len()),
176 Some(MergeIterPeeked::B(_)) => (self.a.len(), 1 + self.b.len()),
177 _ => (self.a.len(), self.b.len()),
182 impl<I> Debug for MergeIterInner<I>
185 I::Item: Copy + Debug,
187 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
188 f.debug_tuple("MergeIterInner").field(&self.a).field(&self.b).finish()
192 /// A lazy iterator producing elements in the difference of `BTreeSet`s.
194 /// This `struct` is created by the [`difference`] method on [`BTreeSet`].
195 /// See its documentation for more.
197 /// [`BTreeSet`]: struct.BTreeSet.html
198 /// [`difference`]: struct.BTreeSet.html#method.difference
199 #[stable(feature = "rust1", since = "1.0.0")]
200 pub struct Difference<'a, T: 'a> {
201 inner: DifferenceInner<'a, T>,
204 enum DifferenceInner<'a, T: 'a> {
206 // iterate all of `self` and some of `other`, spotting matches along the way
207 self_iter: Iter<'a, T>,
208 other_iter: Peekable<Iter<'a, T>>,
211 // iterate `self`, look up in `other`
212 self_iter: Iter<'a, T>,
213 other_set: &'a BTreeSet<T>,
215 Iterate(Iter<'a, T>), // simply produce all values in `self`
218 #[stable(feature = "collection_debug", since = "1.17.0")]
219 impl<T: fmt::Debug> fmt::Debug for Difference<'_, T> {
220 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
221 f.debug_tuple("Difference").field(&self.inner).finish()
225 /// A lazy iterator producing elements in the symmetric difference of `BTreeSet`s.
227 /// This `struct` is created by the [`symmetric_difference`] method on
228 /// [`BTreeSet`]. See its documentation for more.
230 /// [`BTreeSet`]: struct.BTreeSet.html
231 /// [`symmetric_difference`]: struct.BTreeSet.html#method.symmetric_difference
232 #[stable(feature = "rust1", since = "1.0.0")]
233 pub struct SymmetricDifference<'a, T: 'a>(MergeIterInner<Iter<'a, T>>);
235 #[stable(feature = "collection_debug", since = "1.17.0")]
236 impl<T: fmt::Debug> fmt::Debug for SymmetricDifference<'_, T> {
237 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
238 f.debug_tuple("SymmetricDifference").field(&self.0).finish()
242 /// A lazy iterator producing elements in the intersection of `BTreeSet`s.
244 /// This `struct` is created by the [`intersection`] method on [`BTreeSet`].
245 /// See its documentation for more.
247 /// [`BTreeSet`]: struct.BTreeSet.html
248 /// [`intersection`]: struct.BTreeSet.html#method.intersection
249 #[stable(feature = "rust1", since = "1.0.0")]
250 pub struct Intersection<'a, T: 'a> {
251 inner: IntersectionInner<'a, T>,
254 enum IntersectionInner<'a, T: 'a> {
256 // iterate similarly sized sets jointly, spotting matches along the way
261 // iterate a small set, look up in the large set
262 small_iter: Iter<'a, T>,
263 large_set: &'a BTreeSet<T>,
265 Answer(Option<&'a T>), // return a specific value or emptiness
268 #[stable(feature = "collection_debug", since = "1.17.0")]
269 impl<T: fmt::Debug> fmt::Debug for Intersection<'_, T> {
270 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
271 f.debug_tuple("Intersection").field(&self.inner).finish()
275 /// A lazy iterator producing elements in the union of `BTreeSet`s.
277 /// This `struct` is created by the [`union`] method on [`BTreeSet`].
278 /// See its documentation for more.
280 /// [`BTreeSet`]: struct.BTreeSet.html
281 /// [`union`]: struct.BTreeSet.html#method.union
282 #[stable(feature = "rust1", since = "1.0.0")]
283 pub struct Union<'a, T: 'a>(MergeIterInner<Iter<'a, T>>);
285 #[stable(feature = "collection_debug", since = "1.17.0")]
286 impl<T: fmt::Debug> fmt::Debug for Union<'_, T> {
287 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
288 f.debug_tuple("Union").field(&self.0).finish()
292 // This constant is used by functions that compare two sets.
293 // It estimates the relative size at which searching performs better
294 // than iterating, based on the benchmarks in
295 // https://github.com/ssomers/rust_bench_btreeset_intersection;
296 // It's used to divide rather than multiply sizes, to rule out overflow,
297 // and it's a power of two to make that division cheap.
298 const ITER_PERFORMANCE_TIPPING_SIZE_DIFF: usize = 16;
300 impl<T: Ord> BTreeSet<T> {
301 /// Makes a new `BTreeSet` with a reasonable choice of B.
306 /// # #![allow(unused_mut)]
307 /// use std::collections::BTreeSet;
309 /// let mut set: BTreeSet<i32> = BTreeSet::new();
311 #[stable(feature = "rust1", since = "1.0.0")]
312 #[rustc_const_unstable(feature = "const_btree_new", issue = "71835")]
313 pub const fn new() -> BTreeSet<T> {
314 BTreeSet { map: BTreeMap::new() }
317 /// Constructs a double-ended iterator over a sub-range of elements in the set.
318 /// The simplest way is to use the range syntax `min..max`, thus `range(min..max)` will
319 /// yield elements from min (inclusive) to max (exclusive).
320 /// The range may also be entered as `(Bound<T>, Bound<T>)`, so for example
321 /// `range((Excluded(4), Included(10)))` will yield a left-exclusive, right-inclusive
322 /// range from 4 to 10.
327 /// use std::collections::BTreeSet;
328 /// use std::ops::Bound::Included;
330 /// let mut set = BTreeSet::new();
334 /// for &elem in set.range((Included(&4), Included(&8))) {
335 /// println!("{}", elem);
337 /// assert_eq!(Some(&5), set.range(4..).next());
339 #[stable(feature = "btree_range", since = "1.17.0")]
340 pub fn range<K: ?Sized, R>(&self, range: R) -> Range<'_, T>
346 Range { iter: self.map.range(range) }
349 /// Visits the values representing the difference,
350 /// i.e., the values that are in `self` but not in `other`,
351 /// in ascending order.
356 /// use std::collections::BTreeSet;
358 /// let mut a = BTreeSet::new();
362 /// let mut b = BTreeSet::new();
366 /// let diff: Vec<_> = a.difference(&b).cloned().collect();
367 /// assert_eq!(diff, [1]);
369 #[stable(feature = "rust1", since = "1.0.0")]
370 pub fn difference<'a>(&'a self, other: &'a BTreeSet<T>) -> Difference<'a, T> {
371 let (self_min, self_max) =
372 if let (Some(self_min), Some(self_max)) = (self.first(), self.last()) {
375 return Difference { inner: DifferenceInner::Iterate(self.iter()) };
377 let (other_min, other_max) =
378 if let (Some(other_min), Some(other_max)) = (other.first(), other.last()) {
379 (other_min, other_max)
381 return Difference { inner: DifferenceInner::Iterate(self.iter()) };
384 inner: match (self_min.cmp(other_max), self_max.cmp(other_min)) {
385 (Greater, _) | (_, Less) => DifferenceInner::Iterate(self.iter()),
387 let mut self_iter = self.iter();
389 DifferenceInner::Iterate(self_iter)
392 let mut self_iter = self.iter();
393 self_iter.next_back();
394 DifferenceInner::Iterate(self_iter)
396 _ if self.len() <= other.len() / ITER_PERFORMANCE_TIPPING_SIZE_DIFF => {
397 DifferenceInner::Search { self_iter: self.iter(), other_set: other }
399 _ => DifferenceInner::Stitch {
400 self_iter: self.iter(),
401 other_iter: other.iter().peekable(),
407 /// Visits the values representing the symmetric difference,
408 /// i.e., the values that are in `self` or in `other` but not in both,
409 /// in ascending order.
414 /// use std::collections::BTreeSet;
416 /// let mut a = BTreeSet::new();
420 /// let mut b = BTreeSet::new();
424 /// let sym_diff: Vec<_> = a.symmetric_difference(&b).cloned().collect();
425 /// assert_eq!(sym_diff, [1, 3]);
427 #[stable(feature = "rust1", since = "1.0.0")]
428 pub fn symmetric_difference<'a>(
430 other: &'a BTreeSet<T>,
431 ) -> SymmetricDifference<'a, T> {
432 SymmetricDifference(MergeIterInner::new(self.iter(), other.iter()))
435 /// Visits the values representing the intersection,
436 /// i.e., the values that are both in `self` and `other`,
437 /// in ascending order.
442 /// use std::collections::BTreeSet;
444 /// let mut a = BTreeSet::new();
448 /// let mut b = BTreeSet::new();
452 /// let intersection: Vec<_> = a.intersection(&b).cloned().collect();
453 /// assert_eq!(intersection, [2]);
455 #[stable(feature = "rust1", since = "1.0.0")]
456 pub fn intersection<'a>(&'a self, other: &'a BTreeSet<T>) -> Intersection<'a, T> {
457 let (self_min, self_max) =
458 if let (Some(self_min), Some(self_max)) = (self.first(), self.last()) {
461 return Intersection { inner: IntersectionInner::Answer(None) };
463 let (other_min, other_max) =
464 if let (Some(other_min), Some(other_max)) = (other.first(), other.last()) {
465 (other_min, other_max)
467 return Intersection { inner: IntersectionInner::Answer(None) };
470 inner: match (self_min.cmp(other_max), self_max.cmp(other_min)) {
471 (Greater, _) | (_, Less) => IntersectionInner::Answer(None),
472 (Equal, _) => IntersectionInner::Answer(Some(self_min)),
473 (_, Equal) => IntersectionInner::Answer(Some(self_max)),
474 _ if self.len() <= other.len() / ITER_PERFORMANCE_TIPPING_SIZE_DIFF => {
475 IntersectionInner::Search { small_iter: self.iter(), large_set: other }
477 _ if other.len() <= self.len() / ITER_PERFORMANCE_TIPPING_SIZE_DIFF => {
478 IntersectionInner::Search { small_iter: other.iter(), large_set: self }
480 _ => IntersectionInner::Stitch { a: self.iter(), b: other.iter() },
485 /// Visits the values representing the union,
486 /// i.e., all the values in `self` or `other`, without duplicates,
487 /// in ascending order.
492 /// use std::collections::BTreeSet;
494 /// let mut a = BTreeSet::new();
497 /// let mut b = BTreeSet::new();
500 /// let union: Vec<_> = a.union(&b).cloned().collect();
501 /// assert_eq!(union, [1, 2]);
503 #[stable(feature = "rust1", since = "1.0.0")]
504 pub fn union<'a>(&'a self, other: &'a BTreeSet<T>) -> Union<'a, T> {
505 Union(MergeIterInner::new(self.iter(), other.iter()))
508 /// Clears the set, removing all values.
513 /// use std::collections::BTreeSet;
515 /// let mut v = BTreeSet::new();
518 /// assert!(v.is_empty());
520 #[stable(feature = "rust1", since = "1.0.0")]
521 pub fn clear(&mut self) {
525 /// Returns `true` if the set contains a value.
527 /// The value may be any borrowed form of the set's value type,
528 /// but the ordering on the borrowed form *must* match the
529 /// ordering on the value type.
534 /// use std::collections::BTreeSet;
536 /// let set: BTreeSet<_> = [1, 2, 3].iter().cloned().collect();
537 /// assert_eq!(set.contains(&1), true);
538 /// assert_eq!(set.contains(&4), false);
540 #[stable(feature = "rust1", since = "1.0.0")]
541 pub fn contains<Q: ?Sized>(&self, value: &Q) -> bool
546 self.map.contains_key(value)
549 /// Returns a reference to the value in the set, if any, that is equal to the given value.
551 /// The value may be any borrowed form of the set's value type,
552 /// but the ordering on the borrowed form *must* match the
553 /// ordering on the value type.
558 /// use std::collections::BTreeSet;
560 /// let set: BTreeSet<_> = [1, 2, 3].iter().cloned().collect();
561 /// assert_eq!(set.get(&2), Some(&2));
562 /// assert_eq!(set.get(&4), None);
564 #[stable(feature = "set_recovery", since = "1.9.0")]
565 pub fn get<Q: ?Sized>(&self, value: &Q) -> Option<&T>
570 Recover::get(&self.map, value)
573 /// Returns `true` if `self` has no elements in common with `other`.
574 /// This is equivalent to checking for an empty intersection.
579 /// use std::collections::BTreeSet;
581 /// let a: BTreeSet<_> = [1, 2, 3].iter().cloned().collect();
582 /// let mut b = BTreeSet::new();
584 /// assert_eq!(a.is_disjoint(&b), true);
586 /// assert_eq!(a.is_disjoint(&b), true);
588 /// assert_eq!(a.is_disjoint(&b), false);
590 #[stable(feature = "rust1", since = "1.0.0")]
591 pub fn is_disjoint(&self, other: &BTreeSet<T>) -> bool {
592 self.intersection(other).next().is_none()
595 /// Returns `true` if the set is a subset of another,
596 /// i.e., `other` contains at least all the values in `self`.
601 /// use std::collections::BTreeSet;
603 /// let sup: BTreeSet<_> = [1, 2, 3].iter().cloned().collect();
604 /// let mut set = BTreeSet::new();
606 /// assert_eq!(set.is_subset(&sup), true);
608 /// assert_eq!(set.is_subset(&sup), true);
610 /// assert_eq!(set.is_subset(&sup), false);
612 #[stable(feature = "rust1", since = "1.0.0")]
613 pub fn is_subset(&self, other: &BTreeSet<T>) -> bool {
614 // Same result as self.difference(other).next().is_none()
615 // but the code below is faster (hugely in some cases).
616 if self.len() > other.len() {
619 let (self_min, self_max) =
620 if let (Some(self_min), Some(self_max)) = (self.first(), self.last()) {
623 return true; // self is empty
625 let (other_min, other_max) =
626 if let (Some(other_min), Some(other_max)) = (other.first(), other.last()) {
627 (other_min, other_max)
629 return false; // other is empty
631 let mut self_iter = self.iter();
632 match self_min.cmp(other_min) {
633 Less => return false,
639 match self_max.cmp(other_max) {
640 Greater => return false,
642 self_iter.next_back();
646 if self_iter.len() <= other.len() / ITER_PERFORMANCE_TIPPING_SIZE_DIFF {
647 for next in self_iter {
648 if !other.contains(next) {
653 let mut other_iter = other.iter();
655 other_iter.next_back();
656 let mut self_next = self_iter.next();
657 while let Some(self1) = self_next {
658 match other_iter.next().map_or(Less, |other1| self1.cmp(other1)) {
659 Less => return false,
660 Equal => self_next = self_iter.next(),
668 /// Returns `true` if the set is a superset of another,
669 /// i.e., `self` contains at least all the values in `other`.
674 /// use std::collections::BTreeSet;
676 /// let sub: BTreeSet<_> = [1, 2].iter().cloned().collect();
677 /// let mut set = BTreeSet::new();
679 /// assert_eq!(set.is_superset(&sub), false);
683 /// assert_eq!(set.is_superset(&sub), false);
686 /// assert_eq!(set.is_superset(&sub), true);
688 #[stable(feature = "rust1", since = "1.0.0")]
689 pub fn is_superset(&self, other: &BTreeSet<T>) -> bool {
690 other.is_subset(self)
693 /// Returns a reference to the first value in the set, if any.
694 /// This value is always the minimum of all values in the set.
701 /// #![feature(map_first_last)]
702 /// use std::collections::BTreeSet;
704 /// let mut map = BTreeSet::new();
705 /// assert_eq!(map.first(), None);
707 /// assert_eq!(map.first(), Some(&1));
709 /// assert_eq!(map.first(), Some(&1));
711 #[unstable(feature = "map_first_last", issue = "62924")]
712 pub fn first(&self) -> Option<&T> {
713 self.map.first_key_value().map(|(k, _)| k)
716 /// Returns a reference to the last value in the set, if any.
717 /// This value is always the maximum of all values in the set.
724 /// #![feature(map_first_last)]
725 /// use std::collections::BTreeSet;
727 /// let mut map = BTreeSet::new();
728 /// assert_eq!(map.first(), None);
730 /// assert_eq!(map.last(), Some(&1));
732 /// assert_eq!(map.last(), Some(&2));
734 #[unstable(feature = "map_first_last", issue = "62924")]
735 pub fn last(&self) -> Option<&T> {
736 self.map.last_key_value().map(|(k, _)| k)
739 /// Removes the first value from the set and returns it, if any.
740 /// The first value is always the minimum value in the set.
745 /// #![feature(map_first_last)]
746 /// use std::collections::BTreeSet;
748 /// let mut set = BTreeSet::new();
751 /// while let Some(n) = set.pop_first() {
752 /// assert_eq!(n, 1);
754 /// assert!(set.is_empty());
756 #[unstable(feature = "map_first_last", issue = "62924")]
757 pub fn pop_first(&mut self) -> Option<T> {
758 self.map.first_entry().map(|entry| entry.remove_entry().0)
761 /// Removes the last value from the set and returns it, if any.
762 /// The last value is always the maximum value in the set.
767 /// #![feature(map_first_last)]
768 /// use std::collections::BTreeSet;
770 /// let mut set = BTreeSet::new();
773 /// while let Some(n) = set.pop_last() {
774 /// assert_eq!(n, 1);
776 /// assert!(set.is_empty());
778 #[unstable(feature = "map_first_last", issue = "62924")]
779 pub fn pop_last(&mut self) -> Option<T> {
780 self.map.last_entry().map(|entry| entry.remove_entry().0)
783 /// Adds a value to the set.
785 /// If the set did not have this value present, `true` is returned.
787 /// If the set did have this value present, `false` is returned, and the
788 /// entry is not updated. See the [module-level documentation] for more.
790 /// [module-level documentation]: index.html#insert-and-complex-keys
795 /// use std::collections::BTreeSet;
797 /// let mut set = BTreeSet::new();
799 /// assert_eq!(set.insert(2), true);
800 /// assert_eq!(set.insert(2), false);
801 /// assert_eq!(set.len(), 1);
803 #[stable(feature = "rust1", since = "1.0.0")]
804 pub fn insert(&mut self, value: T) -> bool {
805 self.map.insert(value, ()).is_none()
808 /// Adds a value to the set, replacing the existing value, if any, that is equal to the given
809 /// one. Returns the replaced value.
814 /// use std::collections::BTreeSet;
816 /// let mut set = BTreeSet::new();
817 /// set.insert(Vec::<i32>::new());
819 /// assert_eq!(set.get(&[][..]).unwrap().capacity(), 0);
820 /// set.replace(Vec::with_capacity(10));
821 /// assert_eq!(set.get(&[][..]).unwrap().capacity(), 10);
823 #[stable(feature = "set_recovery", since = "1.9.0")]
824 pub fn replace(&mut self, value: T) -> Option<T> {
825 Recover::replace(&mut self.map, value)
828 /// Removes a value from the set. Returns whether the value was
829 /// present in the set.
831 /// The value may be any borrowed form of the set's value type,
832 /// but the ordering on the borrowed form *must* match the
833 /// ordering on the value type.
838 /// use std::collections::BTreeSet;
840 /// let mut set = BTreeSet::new();
843 /// assert_eq!(set.remove(&2), true);
844 /// assert_eq!(set.remove(&2), false);
846 #[stable(feature = "rust1", since = "1.0.0")]
847 pub fn remove<Q: ?Sized>(&mut self, value: &Q) -> bool
852 self.map.remove(value).is_some()
855 /// Removes and returns the value in the set, if any, that is equal to the given one.
857 /// The value may be any borrowed form of the set's value type,
858 /// but the ordering on the borrowed form *must* match the
859 /// ordering on the value type.
864 /// use std::collections::BTreeSet;
866 /// let mut set: BTreeSet<_> = [1, 2, 3].iter().cloned().collect();
867 /// assert_eq!(set.take(&2), Some(2));
868 /// assert_eq!(set.take(&2), None);
870 #[stable(feature = "set_recovery", since = "1.9.0")]
871 pub fn take<Q: ?Sized>(&mut self, value: &Q) -> Option<T>
876 Recover::take(&mut self.map, value)
879 /// Moves all elements from `other` into `Self`, leaving `other` empty.
884 /// use std::collections::BTreeSet;
886 /// let mut a = BTreeSet::new();
891 /// let mut b = BTreeSet::new();
896 /// a.append(&mut b);
898 /// assert_eq!(a.len(), 5);
899 /// assert_eq!(b.len(), 0);
901 /// assert!(a.contains(&1));
902 /// assert!(a.contains(&2));
903 /// assert!(a.contains(&3));
904 /// assert!(a.contains(&4));
905 /// assert!(a.contains(&5));
907 #[stable(feature = "btree_append", since = "1.11.0")]
908 pub fn append(&mut self, other: &mut Self) {
909 self.map.append(&mut other.map);
912 /// Splits the collection into two at the given key. Returns everything after the given key,
913 /// including the key.
920 /// use std::collections::BTreeSet;
922 /// let mut a = BTreeSet::new();
929 /// let b = a.split_off(&3);
931 /// assert_eq!(a.len(), 2);
932 /// assert_eq!(b.len(), 3);
934 /// assert!(a.contains(&1));
935 /// assert!(a.contains(&2));
937 /// assert!(b.contains(&3));
938 /// assert!(b.contains(&17));
939 /// assert!(b.contains(&41));
941 #[stable(feature = "btree_split_off", since = "1.11.0")]
942 pub fn split_off<Q: ?Sized + Ord>(&mut self, key: &Q) -> Self
946 BTreeSet { map: self.map.split_off(key) }
949 /// Creates an iterator which uses a closure to determine if a value should be removed.
951 /// If the closure returns true, then the value is removed and yielded.
952 /// If the closure returns false, the value will remain in the list and will not be yielded
955 /// If the iterator is only partially consumed or not consumed at all, each of the remaining
956 /// values will still be subjected to the closure and removed and dropped if it returns true.
958 /// It is unspecified how many more values will be subjected to the closure
959 /// if a panic occurs in the closure, or if a panic occurs while dropping a value, or if the
960 /// `DrainFilter` itself is leaked.
964 /// Splitting a set into even and odd values, reusing the original set:
967 /// #![feature(btree_drain_filter)]
968 /// use std::collections::BTreeSet;
970 /// let mut set: BTreeSet<i32> = (0..8).collect();
971 /// let evens: BTreeSet<_> = set.drain_filter(|v| v % 2 == 0).collect();
973 /// assert_eq!(evens.into_iter().collect::<Vec<_>>(), vec![0, 2, 4, 6]);
974 /// assert_eq!(odds.into_iter().collect::<Vec<_>>(), vec![1, 3, 5, 7]);
976 #[unstable(feature = "btree_drain_filter", issue = "70530")]
977 pub fn drain_filter<'a, F>(&'a mut self, pred: F) -> DrainFilter<'a, T, F>
979 F: 'a + FnMut(&T) -> bool,
981 DrainFilter { pred, inner: self.map.drain_filter_inner() }
985 impl<T> BTreeSet<T> {
986 /// Gets an iterator that visits the values in the `BTreeSet` in ascending order.
991 /// use std::collections::BTreeSet;
993 /// let set: BTreeSet<usize> = [1, 2, 3].iter().cloned().collect();
994 /// let mut set_iter = set.iter();
995 /// assert_eq!(set_iter.next(), Some(&1));
996 /// assert_eq!(set_iter.next(), Some(&2));
997 /// assert_eq!(set_iter.next(), Some(&3));
998 /// assert_eq!(set_iter.next(), None);
1001 /// Values returned by the iterator are returned in ascending order:
1004 /// use std::collections::BTreeSet;
1006 /// let set: BTreeSet<usize> = [3, 1, 2].iter().cloned().collect();
1007 /// let mut set_iter = set.iter();
1008 /// assert_eq!(set_iter.next(), Some(&1));
1009 /// assert_eq!(set_iter.next(), Some(&2));
1010 /// assert_eq!(set_iter.next(), Some(&3));
1011 /// assert_eq!(set_iter.next(), None);
1013 #[stable(feature = "rust1", since = "1.0.0")]
1014 pub fn iter(&self) -> Iter<'_, T> {
1015 Iter { iter: self.map.keys() }
1018 /// Returns the number of elements in the set.
1023 /// use std::collections::BTreeSet;
1025 /// let mut v = BTreeSet::new();
1026 /// assert_eq!(v.len(), 0);
1028 /// assert_eq!(v.len(), 1);
1030 #[stable(feature = "rust1", since = "1.0.0")]
1031 pub fn len(&self) -> usize {
1035 /// Returns `true` if the set contains no elements.
1040 /// use std::collections::BTreeSet;
1042 /// let mut v = BTreeSet::new();
1043 /// assert!(v.is_empty());
1045 /// assert!(!v.is_empty());
1047 #[stable(feature = "rust1", since = "1.0.0")]
1048 pub fn is_empty(&self) -> bool {
1053 #[stable(feature = "rust1", since = "1.0.0")]
1054 impl<T: Ord> FromIterator<T> for BTreeSet<T> {
1055 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> BTreeSet<T> {
1056 let mut set = BTreeSet::new();
1062 #[stable(feature = "rust1", since = "1.0.0")]
1063 impl<T> IntoIterator for BTreeSet<T> {
1065 type IntoIter = IntoIter<T>;
1067 /// Gets an iterator for moving out the `BTreeSet`'s contents.
1072 /// use std::collections::BTreeSet;
1074 /// let set: BTreeSet<usize> = [1, 2, 3, 4].iter().cloned().collect();
1076 /// let v: Vec<_> = set.into_iter().collect();
1077 /// assert_eq!(v, [1, 2, 3, 4]);
1079 fn into_iter(self) -> IntoIter<T> {
1080 IntoIter { iter: self.map.into_iter() }
1084 #[stable(feature = "rust1", since = "1.0.0")]
1085 impl<'a, T> IntoIterator for &'a BTreeSet<T> {
1087 type IntoIter = Iter<'a, T>;
1089 fn into_iter(self) -> Iter<'a, T> {
1094 /// An iterator produced by calling `drain_filter` on BTreeSet.
1095 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1096 pub struct DrainFilter<'a, T, F>
1099 F: 'a + FnMut(&T) -> bool,
1102 inner: super::map::DrainFilterInner<'a, T, ()>,
1105 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1106 impl<T, F> Drop for DrainFilter<'_, T, F>
1108 F: FnMut(&T) -> bool,
1110 fn drop(&mut self) {
1111 self.for_each(drop);
1115 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1116 impl<T, F> fmt::Debug for DrainFilter<'_, T, F>
1119 F: FnMut(&T) -> bool,
1121 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1122 f.debug_tuple("DrainFilter").field(&self.inner.peek().map(|(k, _)| k)).finish()
1126 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1127 impl<'a, T, F> Iterator for DrainFilter<'_, T, F>
1129 F: 'a + FnMut(&T) -> bool,
1133 fn next(&mut self) -> Option<T> {
1134 let pred = &mut self.pred;
1135 let mut mapped_pred = |k: &T, _v: &mut ()| pred(k);
1136 self.inner.next(&mut mapped_pred).map(|(k, _)| k)
1139 fn size_hint(&self) -> (usize, Option<usize>) {
1140 self.inner.size_hint()
1144 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1145 impl<T, F> FusedIterator for DrainFilter<'_, T, F> where F: FnMut(&T) -> bool {}
1147 #[stable(feature = "rust1", since = "1.0.0")]
1148 impl<T: Ord> Extend<T> for BTreeSet<T> {
1150 fn extend<Iter: IntoIterator<Item = T>>(&mut self, iter: Iter) {
1151 iter.into_iter().for_each(move |elem| {
1157 fn extend_one(&mut self, elem: T) {
1162 #[stable(feature = "extend_ref", since = "1.2.0")]
1163 impl<'a, T: 'a + Ord + Copy> Extend<&'a T> for BTreeSet<T> {
1164 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
1165 self.extend(iter.into_iter().cloned());
1169 fn extend_one(&mut self, &elem: &'a T) {
1174 #[stable(feature = "rust1", since = "1.0.0")]
1175 impl<T: Ord> Default for BTreeSet<T> {
1176 /// Makes an empty `BTreeSet<T>` with a reasonable choice of B.
1177 fn default() -> BTreeSet<T> {
1182 #[stable(feature = "rust1", since = "1.0.0")]
1183 impl<T: Ord + Clone> Sub<&BTreeSet<T>> for &BTreeSet<T> {
1184 type Output = BTreeSet<T>;
1186 /// Returns the difference of `self` and `rhs` as a new `BTreeSet<T>`.
1191 /// use std::collections::BTreeSet;
1193 /// let a: BTreeSet<_> = vec![1, 2, 3].into_iter().collect();
1194 /// let b: BTreeSet<_> = vec![3, 4, 5].into_iter().collect();
1196 /// let result = &a - &b;
1197 /// let result_vec: Vec<_> = result.into_iter().collect();
1198 /// assert_eq!(result_vec, [1, 2]);
1200 fn sub(self, rhs: &BTreeSet<T>) -> BTreeSet<T> {
1201 self.difference(rhs).cloned().collect()
1205 #[stable(feature = "rust1", since = "1.0.0")]
1206 impl<T: Ord + Clone> BitXor<&BTreeSet<T>> for &BTreeSet<T> {
1207 type Output = BTreeSet<T>;
1209 /// Returns the symmetric difference of `self` and `rhs` as a new `BTreeSet<T>`.
1214 /// use std::collections::BTreeSet;
1216 /// let a: BTreeSet<_> = vec![1, 2, 3].into_iter().collect();
1217 /// let b: BTreeSet<_> = vec![2, 3, 4].into_iter().collect();
1219 /// let result = &a ^ &b;
1220 /// let result_vec: Vec<_> = result.into_iter().collect();
1221 /// assert_eq!(result_vec, [1, 4]);
1223 fn bitxor(self, rhs: &BTreeSet<T>) -> BTreeSet<T> {
1224 self.symmetric_difference(rhs).cloned().collect()
1228 #[stable(feature = "rust1", since = "1.0.0")]
1229 impl<T: Ord + Clone> BitAnd<&BTreeSet<T>> for &BTreeSet<T> {
1230 type Output = BTreeSet<T>;
1232 /// Returns the intersection of `self` and `rhs` as a new `BTreeSet<T>`.
1237 /// use std::collections::BTreeSet;
1239 /// let a: BTreeSet<_> = vec![1, 2, 3].into_iter().collect();
1240 /// let b: BTreeSet<_> = vec![2, 3, 4].into_iter().collect();
1242 /// let result = &a & &b;
1243 /// let result_vec: Vec<_> = result.into_iter().collect();
1244 /// assert_eq!(result_vec, [2, 3]);
1246 fn bitand(self, rhs: &BTreeSet<T>) -> BTreeSet<T> {
1247 self.intersection(rhs).cloned().collect()
1251 #[stable(feature = "rust1", since = "1.0.0")]
1252 impl<T: Ord + Clone> BitOr<&BTreeSet<T>> for &BTreeSet<T> {
1253 type Output = BTreeSet<T>;
1255 /// Returns the union of `self` and `rhs` as a new `BTreeSet<T>`.
1260 /// use std::collections::BTreeSet;
1262 /// let a: BTreeSet<_> = vec![1, 2, 3].into_iter().collect();
1263 /// let b: BTreeSet<_> = vec![3, 4, 5].into_iter().collect();
1265 /// let result = &a | &b;
1266 /// let result_vec: Vec<_> = result.into_iter().collect();
1267 /// assert_eq!(result_vec, [1, 2, 3, 4, 5]);
1269 fn bitor(self, rhs: &BTreeSet<T>) -> BTreeSet<T> {
1270 self.union(rhs).cloned().collect()
1274 #[stable(feature = "rust1", since = "1.0.0")]
1275 impl<T: Debug> Debug for BTreeSet<T> {
1276 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1277 f.debug_set().entries(self.iter()).finish()
1281 #[stable(feature = "rust1", since = "1.0.0")]
1282 impl<T> Clone for Iter<'_, T> {
1283 fn clone(&self) -> Self {
1284 Iter { iter: self.iter.clone() }
1287 #[stable(feature = "rust1", since = "1.0.0")]
1288 impl<'a, T> Iterator for Iter<'a, T> {
1291 fn next(&mut self) -> Option<&'a T> {
1294 fn size_hint(&self) -> (usize, Option<usize>) {
1295 self.iter.size_hint()
1297 fn last(mut self) -> Option<&'a T> {
1301 #[stable(feature = "rust1", since = "1.0.0")]
1302 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
1303 fn next_back(&mut self) -> Option<&'a T> {
1304 self.iter.next_back()
1307 #[stable(feature = "rust1", since = "1.0.0")]
1308 impl<T> ExactSizeIterator for Iter<'_, T> {
1309 fn len(&self) -> usize {
1314 #[stable(feature = "fused", since = "1.26.0")]
1315 impl<T> FusedIterator for Iter<'_, T> {}
1317 #[stable(feature = "rust1", since = "1.0.0")]
1318 impl<T> Iterator for IntoIter<T> {
1321 fn next(&mut self) -> Option<T> {
1322 self.iter.next().map(|(k, _)| k)
1324 fn size_hint(&self) -> (usize, Option<usize>) {
1325 self.iter.size_hint()
1328 #[stable(feature = "rust1", since = "1.0.0")]
1329 impl<T> DoubleEndedIterator for IntoIter<T> {
1330 fn next_back(&mut self) -> Option<T> {
1331 self.iter.next_back().map(|(k, _)| k)
1334 #[stable(feature = "rust1", since = "1.0.0")]
1335 impl<T> ExactSizeIterator for IntoIter<T> {
1336 fn len(&self) -> usize {
1341 #[stable(feature = "fused", since = "1.26.0")]
1342 impl<T> FusedIterator for IntoIter<T> {}
1344 #[stable(feature = "btree_range", since = "1.17.0")]
1345 impl<T> Clone for Range<'_, T> {
1346 fn clone(&self) -> Self {
1347 Range { iter: self.iter.clone() }
1351 #[stable(feature = "btree_range", since = "1.17.0")]
1352 impl<'a, T> Iterator for Range<'a, T> {
1355 fn next(&mut self) -> Option<&'a T> {
1356 self.iter.next().map(|(k, _)| k)
1359 fn last(mut self) -> Option<&'a T> {
1364 #[stable(feature = "btree_range", since = "1.17.0")]
1365 impl<'a, T> DoubleEndedIterator for Range<'a, T> {
1366 fn next_back(&mut self) -> Option<&'a T> {
1367 self.iter.next_back().map(|(k, _)| k)
1371 #[stable(feature = "fused", since = "1.26.0")]
1372 impl<T> FusedIterator for Range<'_, T> {}
1374 #[stable(feature = "rust1", since = "1.0.0")]
1375 impl<T> Clone for Difference<'_, T> {
1376 fn clone(&self) -> Self {
1378 inner: match &self.inner {
1379 DifferenceInner::Stitch { self_iter, other_iter } => DifferenceInner::Stitch {
1380 self_iter: self_iter.clone(),
1381 other_iter: other_iter.clone(),
1383 DifferenceInner::Search { self_iter, other_set } => {
1384 DifferenceInner::Search { self_iter: self_iter.clone(), other_set }
1386 DifferenceInner::Iterate(iter) => DifferenceInner::Iterate(iter.clone()),
1391 #[stable(feature = "rust1", since = "1.0.0")]
1392 impl<'a, T: Ord> Iterator for Difference<'a, T> {
1395 fn next(&mut self) -> Option<&'a T> {
1396 match &mut self.inner {
1397 DifferenceInner::Stitch { self_iter, other_iter } => {
1398 let mut self_next = self_iter.next()?;
1400 match other_iter.peek().map_or(Less, |other_next| self_next.cmp(other_next)) {
1401 Less => return Some(self_next),
1403 self_next = self_iter.next()?;
1412 DifferenceInner::Search { self_iter, other_set } => loop {
1413 let self_next = self_iter.next()?;
1414 if !other_set.contains(&self_next) {
1415 return Some(self_next);
1418 DifferenceInner::Iterate(iter) => iter.next(),
1422 fn size_hint(&self) -> (usize, Option<usize>) {
1423 let (self_len, other_len) = match &self.inner {
1424 DifferenceInner::Stitch { self_iter, other_iter } => {
1425 (self_iter.len(), other_iter.len())
1427 DifferenceInner::Search { self_iter, other_set } => (self_iter.len(), other_set.len()),
1428 DifferenceInner::Iterate(iter) => (iter.len(), 0),
1430 (self_len.saturating_sub(other_len), Some(self_len))
1434 #[stable(feature = "fused", since = "1.26.0")]
1435 impl<T: Ord> FusedIterator for Difference<'_, T> {}
1437 #[stable(feature = "rust1", since = "1.0.0")]
1438 impl<T> Clone for SymmetricDifference<'_, T> {
1439 fn clone(&self) -> Self {
1440 SymmetricDifference(self.0.clone())
1443 #[stable(feature = "rust1", since = "1.0.0")]
1444 impl<'a, T: Ord> Iterator for SymmetricDifference<'a, T> {
1447 fn next(&mut self) -> Option<&'a T> {
1449 let (a_next, b_next) = self.0.nexts();
1450 if a_next.and(b_next).is_none() {
1451 return a_next.or(b_next);
1456 fn size_hint(&self) -> (usize, Option<usize>) {
1457 let (a_len, b_len) = self.0.lens();
1458 // No checked_add, because even if a and b refer to the same set,
1459 // and T is an empty type, the storage overhead of sets limits
1460 // the number of elements to less than half the range of usize.
1461 (0, Some(a_len + b_len))
1465 #[stable(feature = "fused", since = "1.26.0")]
1466 impl<T: Ord> FusedIterator for SymmetricDifference<'_, T> {}
1468 #[stable(feature = "rust1", since = "1.0.0")]
1469 impl<T> Clone for Intersection<'_, T> {
1470 fn clone(&self) -> Self {
1472 inner: match &self.inner {
1473 IntersectionInner::Stitch { a, b } => {
1474 IntersectionInner::Stitch { a: a.clone(), b: b.clone() }
1476 IntersectionInner::Search { small_iter, large_set } => {
1477 IntersectionInner::Search { small_iter: small_iter.clone(), large_set }
1479 IntersectionInner::Answer(answer) => IntersectionInner::Answer(*answer),
1484 #[stable(feature = "rust1", since = "1.0.0")]
1485 impl<'a, T: Ord> Iterator for Intersection<'a, T> {
1488 fn next(&mut self) -> Option<&'a T> {
1489 match &mut self.inner {
1490 IntersectionInner::Stitch { a, b } => {
1491 let mut a_next = a.next()?;
1492 let mut b_next = b.next()?;
1494 match a_next.cmp(b_next) {
1495 Less => a_next = a.next()?,
1496 Greater => b_next = b.next()?,
1497 Equal => return Some(a_next),
1501 IntersectionInner::Search { small_iter, large_set } => loop {
1502 let small_next = small_iter.next()?;
1503 if large_set.contains(&small_next) {
1504 return Some(small_next);
1507 IntersectionInner::Answer(answer) => answer.take(),
1511 fn size_hint(&self) -> (usize, Option<usize>) {
1513 IntersectionInner::Stitch { a, b } => (0, Some(min(a.len(), b.len()))),
1514 IntersectionInner::Search { small_iter, .. } => (0, Some(small_iter.len())),
1515 IntersectionInner::Answer(None) => (0, Some(0)),
1516 IntersectionInner::Answer(Some(_)) => (1, Some(1)),
1521 #[stable(feature = "fused", since = "1.26.0")]
1522 impl<T: Ord> FusedIterator for Intersection<'_, T> {}
1524 #[stable(feature = "rust1", since = "1.0.0")]
1525 impl<T> Clone for Union<'_, T> {
1526 fn clone(&self) -> Self {
1527 Union(self.0.clone())
1530 #[stable(feature = "rust1", since = "1.0.0")]
1531 impl<'a, T: Ord> Iterator for Union<'a, T> {
1534 fn next(&mut self) -> Option<&'a T> {
1535 let (a_next, b_next) = self.0.nexts();
1539 fn size_hint(&self) -> (usize, Option<usize>) {
1540 let (a_len, b_len) = self.0.lens();
1541 // No checked_add - see SymmetricDifference::size_hint.
1542 (max(a_len, b_len), Some(a_len + b_len))
1546 #[stable(feature = "fused", since = "1.26.0")]
1547 impl<T: Ord> FusedIterator for Union<'_, T> {}