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 /// [`Ord`]: ../../std/cmp/trait.Ord.html
26 /// [`Cell`]: ../../std/cell/struct.Cell.html
27 /// [`RefCell`]: ../../std/cell/struct.RefCell.html
32 /// use std::collections::BTreeSet;
34 /// // Type inference lets us omit an explicit type signature (which
35 /// // would be `BTreeSet<&str>` in this example).
36 /// let mut books = BTreeSet::new();
38 /// // Add some books.
39 /// books.insert("A Dance With Dragons");
40 /// books.insert("To Kill a Mockingbird");
41 /// books.insert("The Odyssey");
42 /// books.insert("The Great Gatsby");
44 /// // Check for a specific one.
45 /// if !books.contains("The Winds of Winter") {
46 /// println!("We have {} books, but The Winds of Winter ain't one.",
51 /// books.remove("The Odyssey");
53 /// // Iterate over everything.
54 /// for book in &books {
55 /// println!("{}", book);
58 #[derive(Hash, PartialEq, Eq, Ord, PartialOrd)]
59 #[stable(feature = "rust1", since = "1.0.0")]
60 pub struct BTreeSet<T> {
64 #[stable(feature = "rust1", since = "1.0.0")]
65 impl<T: Clone> Clone for BTreeSet<T> {
66 fn clone(&self) -> Self {
67 BTreeSet { map: self.map.clone() }
70 fn clone_from(&mut self, other: &Self) {
71 self.map.clone_from(&other.map);
75 /// An iterator over the items of a `BTreeSet`.
77 /// This `struct` is created by the [`iter`] method on [`BTreeSet`].
78 /// See its documentation for more.
80 /// [`iter`]: BTreeSet::iter
81 #[stable(feature = "rust1", since = "1.0.0")]
82 pub struct Iter<'a, T: 'a> {
83 iter: Keys<'a, T, ()>,
86 #[stable(feature = "collection_debug", since = "1.17.0")]
87 impl<T: fmt::Debug> fmt::Debug for Iter<'_, T> {
88 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
89 f.debug_tuple("Iter").field(&self.iter.clone()).finish()
93 /// An owning iterator over the items of a `BTreeSet`.
95 /// This `struct` is created by the [`into_iter`] method on [`BTreeSet`]
96 /// (provided by the `IntoIterator` trait). See its documentation for more.
98 /// [`into_iter`]: BTreeSet#method.into_iter
99 #[stable(feature = "rust1", since = "1.0.0")]
101 pub struct IntoIter<T> {
102 iter: super::map::IntoIter<T, ()>,
105 /// An iterator over a sub-range of items in a `BTreeSet`.
107 /// This `struct` is created by the [`range`] method on [`BTreeSet`].
108 /// See its documentation for more.
110 /// [`range`]: BTreeSet::range
112 #[stable(feature = "btree_range", since = "1.17.0")]
113 pub struct Range<'a, T: 'a> {
114 iter: super::map::Range<'a, T, ()>,
117 /// Core of SymmetricDifference and Union.
118 /// More efficient than btree.map.MergeIter,
119 /// and crucially for SymmetricDifference, nexts() reports on both sides.
121 struct MergeIterInner<I>
128 peeked: Option<MergeIterPeeked<I>>,
131 #[derive(Copy, Clone, Debug)]
132 enum MergeIterPeeked<I: Iterator> {
137 impl<I> MergeIterInner<I>
139 I: ExactSizeIterator + FusedIterator,
142 fn new(a: I, b: I) -> Self {
143 MergeIterInner { a, b, peeked: None }
146 fn nexts(&mut self) -> (Option<I::Item>, Option<I::Item>) {
147 let mut a_next = match self.peeked {
148 Some(MergeIterPeeked::A(next)) => Some(next),
151 let mut b_next = match self.peeked {
152 Some(MergeIterPeeked::B(next)) => Some(next),
155 let ord = match (a_next, b_next) {
156 (None, None) => Equal,
158 (None, _) => Greater,
159 (Some(a1), Some(b1)) => a1.cmp(&b1),
161 self.peeked = match ord {
162 Less => b_next.take().map(MergeIterPeeked::B),
164 Greater => a_next.take().map(MergeIterPeeked::A),
169 fn lens(&self) -> (usize, usize) {
171 Some(MergeIterPeeked::A(_)) => (1 + self.a.len(), self.b.len()),
172 Some(MergeIterPeeked::B(_)) => (self.a.len(), 1 + self.b.len()),
173 _ => (self.a.len(), self.b.len()),
178 impl<I> Debug for MergeIterInner<I>
181 I::Item: Copy + Debug,
183 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
184 f.debug_tuple("MergeIterInner").field(&self.a).field(&self.b).finish()
188 /// A lazy iterator producing elements in the difference of `BTreeSet`s.
190 /// This `struct` is created by the [`difference`] method on [`BTreeSet`].
191 /// See its documentation for more.
193 /// [`difference`]: BTreeSet::difference
194 #[stable(feature = "rust1", since = "1.0.0")]
195 pub struct Difference<'a, T: 'a> {
196 inner: DifferenceInner<'a, T>,
199 enum DifferenceInner<'a, T: 'a> {
201 // iterate all of `self` and some of `other`, spotting matches along the way
202 self_iter: Iter<'a, T>,
203 other_iter: Peekable<Iter<'a, T>>,
206 // iterate `self`, look up in `other`
207 self_iter: Iter<'a, T>,
208 other_set: &'a BTreeSet<T>,
210 Iterate(Iter<'a, T>), // simply produce all values in `self`
213 #[stable(feature = "collection_debug", since = "1.17.0")]
214 impl<T: fmt::Debug> fmt::Debug for Difference<'_, T> {
215 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
216 f.debug_tuple("Difference").field(&self.inner).finish()
220 /// A lazy iterator producing elements in the symmetric difference of `BTreeSet`s.
222 /// This `struct` is created by the [`symmetric_difference`] method on
223 /// [`BTreeSet`]. See its documentation for more.
225 /// [`symmetric_difference`]: BTreeSet::symmetric_difference
226 #[stable(feature = "rust1", since = "1.0.0")]
227 pub struct SymmetricDifference<'a, T: 'a>(MergeIterInner<Iter<'a, T>>);
229 #[stable(feature = "collection_debug", since = "1.17.0")]
230 impl<T: fmt::Debug> fmt::Debug for SymmetricDifference<'_, T> {
231 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
232 f.debug_tuple("SymmetricDifference").field(&self.0).finish()
236 /// A lazy iterator producing elements in the intersection of `BTreeSet`s.
238 /// This `struct` is created by the [`intersection`] method on [`BTreeSet`].
239 /// See its documentation for more.
241 /// [`intersection`]: BTreeSet::intersection
242 #[stable(feature = "rust1", since = "1.0.0")]
243 pub struct Intersection<'a, T: 'a> {
244 inner: IntersectionInner<'a, T>,
247 enum IntersectionInner<'a, T: 'a> {
249 // iterate similarly sized sets jointly, spotting matches along the way
254 // iterate a small set, look up in the large set
255 small_iter: Iter<'a, T>,
256 large_set: &'a BTreeSet<T>,
258 Answer(Option<&'a T>), // return a specific value or emptiness
261 #[stable(feature = "collection_debug", since = "1.17.0")]
262 impl<T: fmt::Debug> fmt::Debug for Intersection<'_, T> {
263 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
264 f.debug_tuple("Intersection").field(&self.inner).finish()
268 /// A lazy iterator producing elements in the union of `BTreeSet`s.
270 /// This `struct` is created by the [`union`] method on [`BTreeSet`].
271 /// See its documentation for more.
273 /// [`union`]: BTreeSet::union
274 #[stable(feature = "rust1", since = "1.0.0")]
275 pub struct Union<'a, T: 'a>(MergeIterInner<Iter<'a, T>>);
277 #[stable(feature = "collection_debug", since = "1.17.0")]
278 impl<T: fmt::Debug> fmt::Debug for Union<'_, T> {
279 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
280 f.debug_tuple("Union").field(&self.0).finish()
284 // This constant is used by functions that compare two sets.
285 // It estimates the relative size at which searching performs better
286 // than iterating, based on the benchmarks in
287 // https://github.com/ssomers/rust_bench_btreeset_intersection;
288 // It's used to divide rather than multiply sizes, to rule out overflow,
289 // and it's a power of two to make that division cheap.
290 const ITER_PERFORMANCE_TIPPING_SIZE_DIFF: usize = 16;
292 impl<T: Ord> BTreeSet<T> {
293 /// Makes a new `BTreeSet` with a reasonable choice of B.
298 /// # #![allow(unused_mut)]
299 /// use std::collections::BTreeSet;
301 /// let mut set: BTreeSet<i32> = BTreeSet::new();
303 #[stable(feature = "rust1", since = "1.0.0")]
304 #[rustc_const_unstable(feature = "const_btree_new", issue = "71835")]
305 pub const fn new() -> BTreeSet<T> {
306 BTreeSet { map: BTreeMap::new() }
309 /// Constructs a double-ended iterator over a sub-range of elements in the set.
310 /// The simplest way is to use the range syntax `min..max`, thus `range(min..max)` will
311 /// yield elements from min (inclusive) to max (exclusive).
312 /// The range may also be entered as `(Bound<T>, Bound<T>)`, so for example
313 /// `range((Excluded(4), Included(10)))` will yield a left-exclusive, right-inclusive
314 /// range from 4 to 10.
319 /// use std::collections::BTreeSet;
320 /// use std::ops::Bound::Included;
322 /// let mut set = BTreeSet::new();
326 /// for &elem in set.range((Included(&4), Included(&8))) {
327 /// println!("{}", elem);
329 /// assert_eq!(Some(&5), set.range(4..).next());
331 #[stable(feature = "btree_range", since = "1.17.0")]
332 pub fn range<K: ?Sized, R>(&self, range: R) -> Range<'_, T>
338 Range { iter: self.map.range(range) }
341 /// Visits the values representing the difference,
342 /// i.e., the values that are in `self` but not in `other`,
343 /// in ascending order.
348 /// use std::collections::BTreeSet;
350 /// let mut a = BTreeSet::new();
354 /// let mut b = BTreeSet::new();
358 /// let diff: Vec<_> = a.difference(&b).cloned().collect();
359 /// assert_eq!(diff, [1]);
361 #[stable(feature = "rust1", since = "1.0.0")]
362 pub fn difference<'a>(&'a self, other: &'a BTreeSet<T>) -> Difference<'a, T> {
363 let (self_min, self_max) =
364 if let (Some(self_min), Some(self_max)) = (self.first(), self.last()) {
367 return Difference { inner: DifferenceInner::Iterate(self.iter()) };
369 let (other_min, other_max) =
370 if let (Some(other_min), Some(other_max)) = (other.first(), other.last()) {
371 (other_min, other_max)
373 return Difference { inner: DifferenceInner::Iterate(self.iter()) };
376 inner: match (self_min.cmp(other_max), self_max.cmp(other_min)) {
377 (Greater, _) | (_, Less) => DifferenceInner::Iterate(self.iter()),
379 let mut self_iter = self.iter();
381 DifferenceInner::Iterate(self_iter)
384 let mut self_iter = self.iter();
385 self_iter.next_back();
386 DifferenceInner::Iterate(self_iter)
388 _ if self.len() <= other.len() / ITER_PERFORMANCE_TIPPING_SIZE_DIFF => {
389 DifferenceInner::Search { self_iter: self.iter(), other_set: other }
391 _ => DifferenceInner::Stitch {
392 self_iter: self.iter(),
393 other_iter: other.iter().peekable(),
399 /// Visits the values representing the symmetric difference,
400 /// i.e., the values that are in `self` or in `other` but not in both,
401 /// in ascending order.
406 /// use std::collections::BTreeSet;
408 /// let mut a = BTreeSet::new();
412 /// let mut b = BTreeSet::new();
416 /// let sym_diff: Vec<_> = a.symmetric_difference(&b).cloned().collect();
417 /// assert_eq!(sym_diff, [1, 3]);
419 #[stable(feature = "rust1", since = "1.0.0")]
420 pub fn symmetric_difference<'a>(
422 other: &'a BTreeSet<T>,
423 ) -> SymmetricDifference<'a, T> {
424 SymmetricDifference(MergeIterInner::new(self.iter(), other.iter()))
427 /// Visits the values representing the intersection,
428 /// i.e., the values that are both in `self` and `other`,
429 /// in ascending order.
434 /// use std::collections::BTreeSet;
436 /// let mut a = BTreeSet::new();
440 /// let mut b = BTreeSet::new();
444 /// let intersection: Vec<_> = a.intersection(&b).cloned().collect();
445 /// assert_eq!(intersection, [2]);
447 #[stable(feature = "rust1", since = "1.0.0")]
448 pub fn intersection<'a>(&'a self, other: &'a BTreeSet<T>) -> Intersection<'a, T> {
449 let (self_min, self_max) =
450 if let (Some(self_min), Some(self_max)) = (self.first(), self.last()) {
453 return Intersection { inner: IntersectionInner::Answer(None) };
455 let (other_min, other_max) =
456 if let (Some(other_min), Some(other_max)) = (other.first(), other.last()) {
457 (other_min, other_max)
459 return Intersection { inner: IntersectionInner::Answer(None) };
462 inner: match (self_min.cmp(other_max), self_max.cmp(other_min)) {
463 (Greater, _) | (_, Less) => IntersectionInner::Answer(None),
464 (Equal, _) => IntersectionInner::Answer(Some(self_min)),
465 (_, Equal) => IntersectionInner::Answer(Some(self_max)),
466 _ if self.len() <= other.len() / ITER_PERFORMANCE_TIPPING_SIZE_DIFF => {
467 IntersectionInner::Search { small_iter: self.iter(), large_set: other }
469 _ if other.len() <= self.len() / ITER_PERFORMANCE_TIPPING_SIZE_DIFF => {
470 IntersectionInner::Search { small_iter: other.iter(), large_set: self }
472 _ => IntersectionInner::Stitch { a: self.iter(), b: other.iter() },
477 /// Visits the values representing the union,
478 /// i.e., all the values in `self` or `other`, without duplicates,
479 /// in ascending order.
484 /// use std::collections::BTreeSet;
486 /// let mut a = BTreeSet::new();
489 /// let mut b = BTreeSet::new();
492 /// let union: Vec<_> = a.union(&b).cloned().collect();
493 /// assert_eq!(union, [1, 2]);
495 #[stable(feature = "rust1", since = "1.0.0")]
496 pub fn union<'a>(&'a self, other: &'a BTreeSet<T>) -> Union<'a, T> {
497 Union(MergeIterInner::new(self.iter(), other.iter()))
500 /// Clears the set, removing all values.
505 /// use std::collections::BTreeSet;
507 /// let mut v = BTreeSet::new();
510 /// assert!(v.is_empty());
512 #[stable(feature = "rust1", since = "1.0.0")]
513 pub fn clear(&mut self) {
517 /// Returns `true` if the set contains a value.
519 /// The value may be any borrowed form of the set's value type,
520 /// but the ordering on the borrowed form *must* match the
521 /// ordering on the value type.
526 /// use std::collections::BTreeSet;
528 /// let set: BTreeSet<_> = [1, 2, 3].iter().cloned().collect();
529 /// assert_eq!(set.contains(&1), true);
530 /// assert_eq!(set.contains(&4), false);
532 #[stable(feature = "rust1", since = "1.0.0")]
533 pub fn contains<Q: ?Sized>(&self, value: &Q) -> bool
538 self.map.contains_key(value)
541 /// Returns a reference to the value in the set, if any, that is equal to the given value.
543 /// The value may be any borrowed form of the set's value type,
544 /// but the ordering on the borrowed form *must* match the
545 /// ordering on the value type.
550 /// use std::collections::BTreeSet;
552 /// let set: BTreeSet<_> = [1, 2, 3].iter().cloned().collect();
553 /// assert_eq!(set.get(&2), Some(&2));
554 /// assert_eq!(set.get(&4), None);
556 #[stable(feature = "set_recovery", since = "1.9.0")]
557 pub fn get<Q: ?Sized>(&self, value: &Q) -> Option<&T>
562 Recover::get(&self.map, value)
565 /// Returns `true` if `self` has no elements in common with `other`.
566 /// This is equivalent to checking for an empty intersection.
571 /// use std::collections::BTreeSet;
573 /// let a: BTreeSet<_> = [1, 2, 3].iter().cloned().collect();
574 /// let mut b = BTreeSet::new();
576 /// assert_eq!(a.is_disjoint(&b), true);
578 /// assert_eq!(a.is_disjoint(&b), true);
580 /// assert_eq!(a.is_disjoint(&b), false);
582 #[stable(feature = "rust1", since = "1.0.0")]
583 pub fn is_disjoint(&self, other: &BTreeSet<T>) -> bool {
584 self.intersection(other).next().is_none()
587 /// Returns `true` if the set is a subset of another,
588 /// i.e., `other` contains at least all the values in `self`.
593 /// use std::collections::BTreeSet;
595 /// let sup: BTreeSet<_> = [1, 2, 3].iter().cloned().collect();
596 /// let mut set = BTreeSet::new();
598 /// assert_eq!(set.is_subset(&sup), true);
600 /// assert_eq!(set.is_subset(&sup), true);
602 /// assert_eq!(set.is_subset(&sup), false);
604 #[stable(feature = "rust1", since = "1.0.0")]
605 pub fn is_subset(&self, other: &BTreeSet<T>) -> bool {
606 // Same result as self.difference(other).next().is_none()
607 // but the code below is faster (hugely in some cases).
608 if self.len() > other.len() {
611 let (self_min, self_max) =
612 if let (Some(self_min), Some(self_max)) = (self.first(), self.last()) {
615 return true; // self is empty
617 let (other_min, other_max) =
618 if let (Some(other_min), Some(other_max)) = (other.first(), other.last()) {
619 (other_min, other_max)
621 return false; // other is empty
623 let mut self_iter = self.iter();
624 match self_min.cmp(other_min) {
625 Less => return false,
631 match self_max.cmp(other_max) {
632 Greater => return false,
634 self_iter.next_back();
638 if self_iter.len() <= other.len() / ITER_PERFORMANCE_TIPPING_SIZE_DIFF {
639 for next in self_iter {
640 if !other.contains(next) {
645 let mut other_iter = other.iter();
647 other_iter.next_back();
648 let mut self_next = self_iter.next();
649 while let Some(self1) = self_next {
650 match other_iter.next().map_or(Less, |other1| self1.cmp(other1)) {
651 Less => return false,
652 Equal => self_next = self_iter.next(),
660 /// Returns `true` if the set is a superset of another,
661 /// i.e., `self` contains at least all the values in `other`.
666 /// use std::collections::BTreeSet;
668 /// let sub: BTreeSet<_> = [1, 2].iter().cloned().collect();
669 /// let mut set = BTreeSet::new();
671 /// assert_eq!(set.is_superset(&sub), false);
675 /// assert_eq!(set.is_superset(&sub), false);
678 /// assert_eq!(set.is_superset(&sub), true);
680 #[stable(feature = "rust1", since = "1.0.0")]
681 pub fn is_superset(&self, other: &BTreeSet<T>) -> bool {
682 other.is_subset(self)
685 /// Returns a reference to the first value in the set, if any.
686 /// This value is always the minimum of all values in the set.
693 /// #![feature(map_first_last)]
694 /// use std::collections::BTreeSet;
696 /// let mut map = BTreeSet::new();
697 /// assert_eq!(map.first(), None);
699 /// assert_eq!(map.first(), Some(&1));
701 /// assert_eq!(map.first(), Some(&1));
703 #[unstable(feature = "map_first_last", issue = "62924")]
704 pub fn first(&self) -> Option<&T> {
705 self.map.first_key_value().map(|(k, _)| k)
708 /// Returns a reference to the last value in the set, if any.
709 /// This value is always the maximum of all values in the set.
716 /// #![feature(map_first_last)]
717 /// use std::collections::BTreeSet;
719 /// let mut map = BTreeSet::new();
720 /// assert_eq!(map.first(), None);
722 /// assert_eq!(map.last(), Some(&1));
724 /// assert_eq!(map.last(), Some(&2));
726 #[unstable(feature = "map_first_last", issue = "62924")]
727 pub fn last(&self) -> Option<&T> {
728 self.map.last_key_value().map(|(k, _)| k)
731 /// Removes the first value from the set and returns it, if any.
732 /// The first value is always the minimum value in the set.
737 /// #![feature(map_first_last)]
738 /// use std::collections::BTreeSet;
740 /// let mut set = BTreeSet::new();
743 /// while let Some(n) = set.pop_first() {
744 /// assert_eq!(n, 1);
746 /// assert!(set.is_empty());
748 #[unstable(feature = "map_first_last", issue = "62924")]
749 pub fn pop_first(&mut self) -> Option<T> {
750 self.map.first_entry().map(|entry| entry.remove_entry().0)
753 /// Removes the last value from the set and returns it, if any.
754 /// The last value is always the maximum value in the set.
759 /// #![feature(map_first_last)]
760 /// use std::collections::BTreeSet;
762 /// let mut set = BTreeSet::new();
765 /// while let Some(n) = set.pop_last() {
766 /// assert_eq!(n, 1);
768 /// assert!(set.is_empty());
770 #[unstable(feature = "map_first_last", issue = "62924")]
771 pub fn pop_last(&mut self) -> Option<T> {
772 self.map.last_entry().map(|entry| entry.remove_entry().0)
775 /// Adds a value to the set.
777 /// If the set did not have this value present, `true` is returned.
779 /// If the set did have this value present, `false` is returned, and the
780 /// entry is not updated. See the [module-level documentation] for more.
782 /// [module-level documentation]: index.html#insert-and-complex-keys
787 /// use std::collections::BTreeSet;
789 /// let mut set = BTreeSet::new();
791 /// assert_eq!(set.insert(2), true);
792 /// assert_eq!(set.insert(2), false);
793 /// assert_eq!(set.len(), 1);
795 #[stable(feature = "rust1", since = "1.0.0")]
796 pub fn insert(&mut self, value: T) -> bool {
797 self.map.insert(value, ()).is_none()
800 /// Adds a value to the set, replacing the existing value, if any, that is equal to the given
801 /// one. Returns the replaced value.
806 /// use std::collections::BTreeSet;
808 /// let mut set = BTreeSet::new();
809 /// set.insert(Vec::<i32>::new());
811 /// assert_eq!(set.get(&[][..]).unwrap().capacity(), 0);
812 /// set.replace(Vec::with_capacity(10));
813 /// assert_eq!(set.get(&[][..]).unwrap().capacity(), 10);
815 #[stable(feature = "set_recovery", since = "1.9.0")]
816 pub fn replace(&mut self, value: T) -> Option<T> {
817 Recover::replace(&mut self.map, value)
820 /// Removes a value from the set. Returns whether the value was
821 /// present in the set.
823 /// The value may be any borrowed form of the set's value type,
824 /// but the ordering on the borrowed form *must* match the
825 /// ordering on the value type.
830 /// use std::collections::BTreeSet;
832 /// let mut set = BTreeSet::new();
835 /// assert_eq!(set.remove(&2), true);
836 /// assert_eq!(set.remove(&2), false);
838 #[stable(feature = "rust1", since = "1.0.0")]
839 pub fn remove<Q: ?Sized>(&mut self, value: &Q) -> bool
844 self.map.remove(value).is_some()
847 /// Removes and returns the value in the set, if any, that is equal to the given one.
849 /// The value may be any borrowed form of the set's value type,
850 /// but the ordering on the borrowed form *must* match the
851 /// ordering on the value type.
856 /// use std::collections::BTreeSet;
858 /// let mut set: BTreeSet<_> = [1, 2, 3].iter().cloned().collect();
859 /// assert_eq!(set.take(&2), Some(2));
860 /// assert_eq!(set.take(&2), None);
862 #[stable(feature = "set_recovery", since = "1.9.0")]
863 pub fn take<Q: ?Sized>(&mut self, value: &Q) -> Option<T>
868 Recover::take(&mut self.map, value)
871 /// Moves all elements from `other` into `Self`, leaving `other` empty.
876 /// use std::collections::BTreeSet;
878 /// let mut a = BTreeSet::new();
883 /// let mut b = BTreeSet::new();
888 /// a.append(&mut b);
890 /// assert_eq!(a.len(), 5);
891 /// assert_eq!(b.len(), 0);
893 /// assert!(a.contains(&1));
894 /// assert!(a.contains(&2));
895 /// assert!(a.contains(&3));
896 /// assert!(a.contains(&4));
897 /// assert!(a.contains(&5));
899 #[stable(feature = "btree_append", since = "1.11.0")]
900 pub fn append(&mut self, other: &mut Self) {
901 self.map.append(&mut other.map);
904 /// Splits the collection into two at the given key. Returns everything after the given key,
905 /// including the key.
912 /// use std::collections::BTreeSet;
914 /// let mut a = BTreeSet::new();
921 /// let b = a.split_off(&3);
923 /// assert_eq!(a.len(), 2);
924 /// assert_eq!(b.len(), 3);
926 /// assert!(a.contains(&1));
927 /// assert!(a.contains(&2));
929 /// assert!(b.contains(&3));
930 /// assert!(b.contains(&17));
931 /// assert!(b.contains(&41));
933 #[stable(feature = "btree_split_off", since = "1.11.0")]
934 pub fn split_off<Q: ?Sized + Ord>(&mut self, key: &Q) -> Self
938 BTreeSet { map: self.map.split_off(key) }
941 /// Creates an iterator which uses a closure to determine if a value should be removed.
943 /// If the closure returns true, then the value is removed and yielded.
944 /// If the closure returns false, the value will remain in the list and will not be yielded
947 /// If the iterator is only partially consumed or not consumed at all, each of the remaining
948 /// values will still be subjected to the closure and removed and dropped if it returns true.
950 /// It is unspecified how many more values will be subjected to the closure
951 /// if a panic occurs in the closure, or if a panic occurs while dropping a value, or if the
952 /// `DrainFilter` itself is leaked.
956 /// Splitting a set into even and odd values, reusing the original set:
959 /// #![feature(btree_drain_filter)]
960 /// use std::collections::BTreeSet;
962 /// let mut set: BTreeSet<i32> = (0..8).collect();
963 /// let evens: BTreeSet<_> = set.drain_filter(|v| v % 2 == 0).collect();
965 /// assert_eq!(evens.into_iter().collect::<Vec<_>>(), vec![0, 2, 4, 6]);
966 /// assert_eq!(odds.into_iter().collect::<Vec<_>>(), vec![1, 3, 5, 7]);
968 #[unstable(feature = "btree_drain_filter", issue = "70530")]
969 pub fn drain_filter<'a, F>(&'a mut self, pred: F) -> DrainFilter<'a, T, F>
971 F: 'a + FnMut(&T) -> bool,
973 DrainFilter { pred, inner: self.map.drain_filter_inner() }
977 impl<T> BTreeSet<T> {
978 /// Gets an iterator that visits the values in the `BTreeSet` in ascending order.
983 /// use std::collections::BTreeSet;
985 /// let set: BTreeSet<usize> = [1, 2, 3].iter().cloned().collect();
986 /// let mut set_iter = set.iter();
987 /// assert_eq!(set_iter.next(), Some(&1));
988 /// assert_eq!(set_iter.next(), Some(&2));
989 /// assert_eq!(set_iter.next(), Some(&3));
990 /// assert_eq!(set_iter.next(), None);
993 /// Values returned by the iterator are returned in ascending order:
996 /// use std::collections::BTreeSet;
998 /// let set: BTreeSet<usize> = [3, 1, 2].iter().cloned().collect();
999 /// let mut set_iter = set.iter();
1000 /// assert_eq!(set_iter.next(), Some(&1));
1001 /// assert_eq!(set_iter.next(), Some(&2));
1002 /// assert_eq!(set_iter.next(), Some(&3));
1003 /// assert_eq!(set_iter.next(), None);
1005 #[stable(feature = "rust1", since = "1.0.0")]
1006 pub fn iter(&self) -> Iter<'_, T> {
1007 Iter { iter: self.map.keys() }
1010 /// Returns the number of elements in the set.
1015 /// use std::collections::BTreeSet;
1017 /// let mut v = BTreeSet::new();
1018 /// assert_eq!(v.len(), 0);
1020 /// assert_eq!(v.len(), 1);
1022 #[stable(feature = "rust1", since = "1.0.0")]
1023 pub fn len(&self) -> usize {
1027 /// Returns `true` if the set contains no elements.
1032 /// use std::collections::BTreeSet;
1034 /// let mut v = BTreeSet::new();
1035 /// assert!(v.is_empty());
1037 /// assert!(!v.is_empty());
1039 #[stable(feature = "rust1", since = "1.0.0")]
1040 pub fn is_empty(&self) -> bool {
1045 #[stable(feature = "rust1", since = "1.0.0")]
1046 impl<T: Ord> FromIterator<T> for BTreeSet<T> {
1047 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> BTreeSet<T> {
1048 let mut set = BTreeSet::new();
1054 #[stable(feature = "rust1", since = "1.0.0")]
1055 impl<T> IntoIterator for BTreeSet<T> {
1057 type IntoIter = IntoIter<T>;
1059 /// Gets an iterator for moving out the `BTreeSet`'s contents.
1064 /// use std::collections::BTreeSet;
1066 /// let set: BTreeSet<usize> = [1, 2, 3, 4].iter().cloned().collect();
1068 /// let v: Vec<_> = set.into_iter().collect();
1069 /// assert_eq!(v, [1, 2, 3, 4]);
1071 fn into_iter(self) -> IntoIter<T> {
1072 IntoIter { iter: self.map.into_iter() }
1076 #[stable(feature = "rust1", since = "1.0.0")]
1077 impl<'a, T> IntoIterator for &'a BTreeSet<T> {
1079 type IntoIter = Iter<'a, T>;
1081 fn into_iter(self) -> Iter<'a, T> {
1086 /// An iterator produced by calling `drain_filter` on BTreeSet.
1087 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1088 pub struct DrainFilter<'a, T, F>
1091 F: 'a + FnMut(&T) -> bool,
1094 inner: super::map::DrainFilterInner<'a, T, ()>,
1097 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1098 impl<T, F> Drop for DrainFilter<'_, T, F>
1100 F: FnMut(&T) -> bool,
1102 fn drop(&mut self) {
1103 self.for_each(drop);
1107 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1108 impl<T, F> fmt::Debug for DrainFilter<'_, T, F>
1111 F: FnMut(&T) -> bool,
1113 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1114 f.debug_tuple("DrainFilter").field(&self.inner.peek().map(|(k, _)| k)).finish()
1118 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1119 impl<'a, T, F> Iterator for DrainFilter<'_, T, F>
1121 F: 'a + FnMut(&T) -> bool,
1125 fn next(&mut self) -> Option<T> {
1126 let pred = &mut self.pred;
1127 let mut mapped_pred = |k: &T, _v: &mut ()| pred(k);
1128 self.inner.next(&mut mapped_pred).map(|(k, _)| k)
1131 fn size_hint(&self) -> (usize, Option<usize>) {
1132 self.inner.size_hint()
1136 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1137 impl<T, F> FusedIterator for DrainFilter<'_, T, F> where F: FnMut(&T) -> bool {}
1139 #[stable(feature = "rust1", since = "1.0.0")]
1140 impl<T: Ord> Extend<T> for BTreeSet<T> {
1142 fn extend<Iter: IntoIterator<Item = T>>(&mut self, iter: Iter) {
1143 iter.into_iter().for_each(move |elem| {
1149 fn extend_one(&mut self, elem: T) {
1154 #[stable(feature = "extend_ref", since = "1.2.0")]
1155 impl<'a, T: 'a + Ord + Copy> Extend<&'a T> for BTreeSet<T> {
1156 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
1157 self.extend(iter.into_iter().cloned());
1161 fn extend_one(&mut self, &elem: &'a T) {
1166 #[stable(feature = "rust1", since = "1.0.0")]
1167 impl<T: Ord> Default for BTreeSet<T> {
1168 /// Makes an empty `BTreeSet<T>` with a reasonable choice of B.
1169 fn default() -> BTreeSet<T> {
1174 #[stable(feature = "rust1", since = "1.0.0")]
1175 impl<T: Ord + Clone> Sub<&BTreeSet<T>> for &BTreeSet<T> {
1176 type Output = BTreeSet<T>;
1178 /// Returns the difference of `self` and `rhs` as a new `BTreeSet<T>`.
1183 /// use std::collections::BTreeSet;
1185 /// let a: BTreeSet<_> = vec![1, 2, 3].into_iter().collect();
1186 /// let b: BTreeSet<_> = vec![3, 4, 5].into_iter().collect();
1188 /// let result = &a - &b;
1189 /// let result_vec: Vec<_> = result.into_iter().collect();
1190 /// assert_eq!(result_vec, [1, 2]);
1192 fn sub(self, rhs: &BTreeSet<T>) -> BTreeSet<T> {
1193 self.difference(rhs).cloned().collect()
1197 #[stable(feature = "rust1", since = "1.0.0")]
1198 impl<T: Ord + Clone> BitXor<&BTreeSet<T>> for &BTreeSet<T> {
1199 type Output = BTreeSet<T>;
1201 /// Returns the symmetric difference of `self` and `rhs` as a new `BTreeSet<T>`.
1206 /// use std::collections::BTreeSet;
1208 /// let a: BTreeSet<_> = vec![1, 2, 3].into_iter().collect();
1209 /// let b: BTreeSet<_> = vec![2, 3, 4].into_iter().collect();
1211 /// let result = &a ^ &b;
1212 /// let result_vec: Vec<_> = result.into_iter().collect();
1213 /// assert_eq!(result_vec, [1, 4]);
1215 fn bitxor(self, rhs: &BTreeSet<T>) -> BTreeSet<T> {
1216 self.symmetric_difference(rhs).cloned().collect()
1220 #[stable(feature = "rust1", since = "1.0.0")]
1221 impl<T: Ord + Clone> BitAnd<&BTreeSet<T>> for &BTreeSet<T> {
1222 type Output = BTreeSet<T>;
1224 /// Returns the intersection of `self` and `rhs` as a new `BTreeSet<T>`.
1229 /// use std::collections::BTreeSet;
1231 /// let a: BTreeSet<_> = vec![1, 2, 3].into_iter().collect();
1232 /// let b: BTreeSet<_> = vec![2, 3, 4].into_iter().collect();
1234 /// let result = &a & &b;
1235 /// let result_vec: Vec<_> = result.into_iter().collect();
1236 /// assert_eq!(result_vec, [2, 3]);
1238 fn bitand(self, rhs: &BTreeSet<T>) -> BTreeSet<T> {
1239 self.intersection(rhs).cloned().collect()
1243 #[stable(feature = "rust1", since = "1.0.0")]
1244 impl<T: Ord + Clone> BitOr<&BTreeSet<T>> for &BTreeSet<T> {
1245 type Output = BTreeSet<T>;
1247 /// Returns the union of `self` and `rhs` as a new `BTreeSet<T>`.
1252 /// use std::collections::BTreeSet;
1254 /// let a: BTreeSet<_> = vec![1, 2, 3].into_iter().collect();
1255 /// let b: BTreeSet<_> = vec![3, 4, 5].into_iter().collect();
1257 /// let result = &a | &b;
1258 /// let result_vec: Vec<_> = result.into_iter().collect();
1259 /// assert_eq!(result_vec, [1, 2, 3, 4, 5]);
1261 fn bitor(self, rhs: &BTreeSet<T>) -> BTreeSet<T> {
1262 self.union(rhs).cloned().collect()
1266 #[stable(feature = "rust1", since = "1.0.0")]
1267 impl<T: Debug> Debug for BTreeSet<T> {
1268 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1269 f.debug_set().entries(self.iter()).finish()
1273 #[stable(feature = "rust1", since = "1.0.0")]
1274 impl<T> Clone for Iter<'_, T> {
1275 fn clone(&self) -> Self {
1276 Iter { iter: self.iter.clone() }
1279 #[stable(feature = "rust1", since = "1.0.0")]
1280 impl<'a, T> Iterator for Iter<'a, T> {
1283 fn next(&mut self) -> Option<&'a T> {
1287 fn size_hint(&self) -> (usize, Option<usize>) {
1288 self.iter.size_hint()
1291 fn last(mut self) -> Option<&'a T> {
1295 fn min(mut self) -> Option<&'a T> {
1299 fn max(mut self) -> Option<&'a T> {
1303 #[stable(feature = "rust1", since = "1.0.0")]
1304 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
1305 fn next_back(&mut self) -> Option<&'a T> {
1306 self.iter.next_back()
1309 #[stable(feature = "rust1", since = "1.0.0")]
1310 impl<T> ExactSizeIterator for Iter<'_, T> {
1311 fn len(&self) -> usize {
1316 #[stable(feature = "fused", since = "1.26.0")]
1317 impl<T> FusedIterator for Iter<'_, T> {}
1319 #[stable(feature = "rust1", since = "1.0.0")]
1320 impl<T> Iterator for IntoIter<T> {
1323 fn next(&mut self) -> Option<T> {
1324 self.iter.next().map(|(k, _)| k)
1327 fn size_hint(&self) -> (usize, Option<usize>) {
1328 self.iter.size_hint()
1331 #[stable(feature = "rust1", since = "1.0.0")]
1332 impl<T> DoubleEndedIterator for IntoIter<T> {
1333 fn next_back(&mut self) -> Option<T> {
1334 self.iter.next_back().map(|(k, _)| k)
1337 #[stable(feature = "rust1", since = "1.0.0")]
1338 impl<T> ExactSizeIterator for IntoIter<T> {
1339 fn len(&self) -> usize {
1344 #[stable(feature = "fused", since = "1.26.0")]
1345 impl<T> FusedIterator for IntoIter<T> {}
1347 #[stable(feature = "btree_range", since = "1.17.0")]
1348 impl<T> Clone for Range<'_, T> {
1349 fn clone(&self) -> Self {
1350 Range { iter: self.iter.clone() }
1354 #[stable(feature = "btree_range", since = "1.17.0")]
1355 impl<'a, T> Iterator for Range<'a, T> {
1358 fn next(&mut self) -> Option<&'a T> {
1359 self.iter.next().map(|(k, _)| k)
1362 fn last(mut self) -> Option<&'a T> {
1366 fn min(mut self) -> Option<&'a T> {
1370 fn max(mut self) -> Option<&'a T> {
1375 #[stable(feature = "btree_range", since = "1.17.0")]
1376 impl<'a, T> DoubleEndedIterator for Range<'a, T> {
1377 fn next_back(&mut self) -> Option<&'a T> {
1378 self.iter.next_back().map(|(k, _)| k)
1382 #[stable(feature = "fused", since = "1.26.0")]
1383 impl<T> FusedIterator for Range<'_, T> {}
1385 #[stable(feature = "rust1", since = "1.0.0")]
1386 impl<T> Clone for Difference<'_, T> {
1387 fn clone(&self) -> Self {
1389 inner: match &self.inner {
1390 DifferenceInner::Stitch { self_iter, other_iter } => DifferenceInner::Stitch {
1391 self_iter: self_iter.clone(),
1392 other_iter: other_iter.clone(),
1394 DifferenceInner::Search { self_iter, other_set } => {
1395 DifferenceInner::Search { self_iter: self_iter.clone(), other_set }
1397 DifferenceInner::Iterate(iter) => DifferenceInner::Iterate(iter.clone()),
1402 #[stable(feature = "rust1", since = "1.0.0")]
1403 impl<'a, T: Ord> Iterator for Difference<'a, T> {
1406 fn next(&mut self) -> Option<&'a T> {
1407 match &mut self.inner {
1408 DifferenceInner::Stitch { self_iter, other_iter } => {
1409 let mut self_next = self_iter.next()?;
1411 match other_iter.peek().map_or(Less, |other_next| self_next.cmp(other_next)) {
1412 Less => return Some(self_next),
1414 self_next = self_iter.next()?;
1423 DifferenceInner::Search { self_iter, other_set } => loop {
1424 let self_next = self_iter.next()?;
1425 if !other_set.contains(&self_next) {
1426 return Some(self_next);
1429 DifferenceInner::Iterate(iter) => iter.next(),
1433 fn size_hint(&self) -> (usize, Option<usize>) {
1434 let (self_len, other_len) = match &self.inner {
1435 DifferenceInner::Stitch { self_iter, other_iter } => {
1436 (self_iter.len(), other_iter.len())
1438 DifferenceInner::Search { self_iter, other_set } => (self_iter.len(), other_set.len()),
1439 DifferenceInner::Iterate(iter) => (iter.len(), 0),
1441 (self_len.saturating_sub(other_len), Some(self_len))
1444 fn min(mut self) -> Option<&'a T> {
1449 #[stable(feature = "fused", since = "1.26.0")]
1450 impl<T: Ord> FusedIterator for Difference<'_, T> {}
1452 #[stable(feature = "rust1", since = "1.0.0")]
1453 impl<T> Clone for SymmetricDifference<'_, T> {
1454 fn clone(&self) -> Self {
1455 SymmetricDifference(self.0.clone())
1458 #[stable(feature = "rust1", since = "1.0.0")]
1459 impl<'a, T: Ord> Iterator for SymmetricDifference<'a, T> {
1462 fn next(&mut self) -> Option<&'a T> {
1464 let (a_next, b_next) = self.0.nexts();
1465 if a_next.and(b_next).is_none() {
1466 return a_next.or(b_next);
1471 fn size_hint(&self) -> (usize, Option<usize>) {
1472 let (a_len, b_len) = self.0.lens();
1473 // No checked_add, because even if a and b refer to the same set,
1474 // and T is an empty type, the storage overhead of sets limits
1475 // the number of elements to less than half the range of usize.
1476 (0, Some(a_len + b_len))
1479 fn min(mut self) -> Option<&'a T> {
1484 #[stable(feature = "fused", since = "1.26.0")]
1485 impl<T: Ord> FusedIterator for SymmetricDifference<'_, T> {}
1487 #[stable(feature = "rust1", since = "1.0.0")]
1488 impl<T> Clone for Intersection<'_, T> {
1489 fn clone(&self) -> Self {
1491 inner: match &self.inner {
1492 IntersectionInner::Stitch { a, b } => {
1493 IntersectionInner::Stitch { a: a.clone(), b: b.clone() }
1495 IntersectionInner::Search { small_iter, large_set } => {
1496 IntersectionInner::Search { small_iter: small_iter.clone(), large_set }
1498 IntersectionInner::Answer(answer) => IntersectionInner::Answer(*answer),
1503 #[stable(feature = "rust1", since = "1.0.0")]
1504 impl<'a, T: Ord> Iterator for Intersection<'a, T> {
1507 fn next(&mut self) -> Option<&'a T> {
1508 match &mut self.inner {
1509 IntersectionInner::Stitch { a, b } => {
1510 let mut a_next = a.next()?;
1511 let mut b_next = b.next()?;
1513 match a_next.cmp(b_next) {
1514 Less => a_next = a.next()?,
1515 Greater => b_next = b.next()?,
1516 Equal => return Some(a_next),
1520 IntersectionInner::Search { small_iter, large_set } => loop {
1521 let small_next = small_iter.next()?;
1522 if large_set.contains(&small_next) {
1523 return Some(small_next);
1526 IntersectionInner::Answer(answer) => answer.take(),
1530 fn size_hint(&self) -> (usize, Option<usize>) {
1532 IntersectionInner::Stitch { a, b } => (0, Some(min(a.len(), b.len()))),
1533 IntersectionInner::Search { small_iter, .. } => (0, Some(small_iter.len())),
1534 IntersectionInner::Answer(None) => (0, Some(0)),
1535 IntersectionInner::Answer(Some(_)) => (1, Some(1)),
1539 fn min(mut self) -> Option<&'a T> {
1544 #[stable(feature = "fused", since = "1.26.0")]
1545 impl<T: Ord> FusedIterator for Intersection<'_, T> {}
1547 #[stable(feature = "rust1", since = "1.0.0")]
1548 impl<T> Clone for Union<'_, T> {
1549 fn clone(&self) -> Self {
1550 Union(self.0.clone())
1553 #[stable(feature = "rust1", since = "1.0.0")]
1554 impl<'a, T: Ord> Iterator for Union<'a, T> {
1557 fn next(&mut self) -> Option<&'a T> {
1558 let (a_next, b_next) = self.0.nexts();
1562 fn size_hint(&self) -> (usize, Option<usize>) {
1563 let (a_len, b_len) = self.0.lens();
1564 // No checked_add - see SymmetricDifference::size_hint.
1565 (max(a_len, b_len), Some(a_len + b_len))
1568 fn min(mut self) -> Option<&'a T> {
1573 #[stable(feature = "fused", since = "1.26.0")]
1574 impl<T: Ord> FusedIterator for Union<'_, T> {}