1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 // This is pretty much entirely stolen from TreeSet, since BTreeMap has an identical interface
14 use core::cmp::Ordering::{self, Less, Greater, Equal};
17 use core::iter::{Peekable, Map, FromIterator};
18 use core::ops::{BitOr, BitAnd, BitXor, Sub};
21 use btree_map::{BTreeMap, Keys};
25 // FIXME(conventions): implement bounded iterators
27 /// A set based on a B-Tree.
29 /// See BTreeMap's documentation for a detailed discussion of this collection's performance
30 /// benefits and drawbacks.
32 /// It is a logic error for an item to be modified in such a way that the item's ordering relative
33 /// to any other item, as determined by the `Ord` trait, changes while it is in the set. This is
34 /// normally only possible through `Cell`, `RefCell`, global state, I/O, or unsafe code.
35 #[derive(Clone, Hash, PartialEq, Eq, Ord, PartialOrd)]
36 #[stable(feature = "rust1", since = "1.0.0")]
37 pub struct BTreeSet<T> {
41 /// An iterator over a BTreeSet's items.
42 #[stable(feature = "rust1", since = "1.0.0")]
43 pub struct Iter<'a, T: 'a> {
44 iter: Keys<'a, T, ()>,
47 /// An owning iterator over a BTreeSet's items.
48 #[stable(feature = "rust1", since = "1.0.0")]
49 pub struct IntoIter<T> {
50 iter: Map<::btree_map::IntoIter<T, ()>, fn((T, ())) -> T>,
53 /// An iterator over a sub-range of BTreeSet's items.
54 pub struct Range<'a, T: 'a> {
55 iter: Map<::btree_map::Range<'a, T, ()>, fn((&'a T, &'a ())) -> &'a T>,
58 /// A lazy iterator producing elements in the set difference (in-order).
59 #[stable(feature = "rust1", since = "1.0.0")]
60 pub struct Difference<'a, T: 'a> {
61 a: Peekable<Iter<'a, T>>,
62 b: Peekable<Iter<'a, T>>,
65 /// A lazy iterator producing elements in the set symmetric difference (in-order).
66 #[stable(feature = "rust1", since = "1.0.0")]
67 pub struct SymmetricDifference<'a, T: 'a> {
68 a: Peekable<Iter<'a, T>>,
69 b: Peekable<Iter<'a, T>>,
72 /// A lazy iterator producing elements in the set intersection (in-order).
73 #[stable(feature = "rust1", since = "1.0.0")]
74 pub struct Intersection<'a, T: 'a> {
75 a: Peekable<Iter<'a, T>>,
76 b: Peekable<Iter<'a, T>>,
79 /// A lazy iterator producing elements in the set union (in-order).
80 #[stable(feature = "rust1", since = "1.0.0")]
81 pub struct Union<'a, T: 'a> {
82 a: Peekable<Iter<'a, T>>,
83 b: Peekable<Iter<'a, T>>,
86 impl<T: Ord> BTreeSet<T> {
87 /// Makes a new BTreeSet with a reasonable choice of B.
92 /// # #![allow(unused_mut)]
93 /// use std::collections::BTreeSet;
95 /// let mut set: BTreeSet<i32> = BTreeSet::new();
97 #[stable(feature = "rust1", since = "1.0.0")]
98 pub fn new() -> BTreeSet<T> {
99 BTreeSet { map: BTreeMap::new() }
102 /// Makes a new BTreeSet with the given B.
104 /// B cannot be less than 2.
105 #[unstable(feature = "btree_b",
106 reason = "probably want this to be on the type, eventually",
108 #[rustc_deprecated(since = "1.4.0", reason = "niche API")]
110 pub fn with_b(b: usize) -> BTreeSet<T> {
111 BTreeSet { map: BTreeMap::with_b(b) }
115 impl<T> BTreeSet<T> {
116 /// Gets an iterator over the BTreeSet's contents.
121 /// use std::collections::BTreeSet;
123 /// let set: BTreeSet<usize> = [1, 2, 3, 4].iter().cloned().collect();
125 /// for x in set.iter() {
126 /// println!("{}", x);
129 /// let v: Vec<_> = set.iter().cloned().collect();
130 /// assert_eq!(v, [1, 2, 3, 4]);
132 #[stable(feature = "rust1", since = "1.0.0")]
133 pub fn iter(&self) -> Iter<T> {
134 Iter { iter: self.map.keys() }
138 impl<T: Ord> BTreeSet<T> {
139 /// Constructs a double-ended iterator over a sub-range of elements in the set, starting
140 /// at min, and ending at max. If min is `Unbounded`, then it will be treated as "negative
141 /// infinity", and if max is `Unbounded`, then it will be treated as "positive infinity".
142 /// Thus range(Unbounded, Unbounded) will yield the whole collection.
147 /// #![feature(btree_range, collections_bound)]
149 /// use std::collections::BTreeSet;
150 /// use std::collections::Bound::{Included, Unbounded};
152 /// let mut set = BTreeSet::new();
156 /// for &elem in set.range(Included(&4), Included(&8)) {
157 /// println!("{}", elem);
159 /// assert_eq!(Some(&5), set.range(Included(&4), Unbounded).next());
161 #[unstable(feature = "btree_range",
162 reason = "matches collection reform specification, waiting for dust to settle",
164 pub fn range<'a, Min: ?Sized + Ord = T, Max: ?Sized + Ord = T>(&'a self,
168 where T: Borrow<Min> + Borrow<Max>
170 fn first<A, B>((a, _): (A, B)) -> A {
173 let first: fn((&'a T, &'a ())) -> &'a T = first; // coerce to fn pointer
175 Range { iter: self.map.range(min, max).map(first) }
179 impl<T: Ord> BTreeSet<T> {
180 /// Visits the values representing the difference, in ascending order.
185 /// use std::collections::BTreeSet;
187 /// let mut a = BTreeSet::new();
191 /// let mut b = BTreeSet::new();
195 /// let diff: Vec<_> = a.difference(&b).cloned().collect();
196 /// assert_eq!(diff, [1]);
198 #[stable(feature = "rust1", since = "1.0.0")]
199 pub fn difference<'a>(&'a self, other: &'a BTreeSet<T>) -> Difference<'a, T> {
201 a: self.iter().peekable(),
202 b: other.iter().peekable(),
206 /// Visits the values representing the symmetric difference, in ascending order.
211 /// use std::collections::BTreeSet;
213 /// let mut a = BTreeSet::new();
217 /// let mut b = BTreeSet::new();
221 /// let sym_diff: Vec<_> = a.symmetric_difference(&b).cloned().collect();
222 /// assert_eq!(sym_diff, [1, 3]);
224 #[stable(feature = "rust1", since = "1.0.0")]
225 pub fn symmetric_difference<'a>(&'a self,
226 other: &'a BTreeSet<T>)
227 -> SymmetricDifference<'a, T> {
228 SymmetricDifference {
229 a: self.iter().peekable(),
230 b: other.iter().peekable(),
234 /// Visits the values representing the intersection, in ascending order.
239 /// use std::collections::BTreeSet;
241 /// let mut a = BTreeSet::new();
245 /// let mut b = BTreeSet::new();
249 /// let intersection: Vec<_> = a.intersection(&b).cloned().collect();
250 /// assert_eq!(intersection, [2]);
252 #[stable(feature = "rust1", since = "1.0.0")]
253 pub fn intersection<'a>(&'a self, other: &'a BTreeSet<T>) -> Intersection<'a, T> {
255 a: self.iter().peekable(),
256 b: other.iter().peekable(),
260 /// Visits the values representing the union, in ascending order.
265 /// use std::collections::BTreeSet;
267 /// let mut a = BTreeSet::new();
270 /// let mut b = BTreeSet::new();
273 /// let union: Vec<_> = a.union(&b).cloned().collect();
274 /// assert_eq!(union, [1, 2]);
276 #[stable(feature = "rust1", since = "1.0.0")]
277 pub fn union<'a>(&'a self, other: &'a BTreeSet<T>) -> Union<'a, T> {
279 a: self.iter().peekable(),
280 b: other.iter().peekable(),
284 /// Returns the number of elements in the set.
289 /// use std::collections::BTreeSet;
291 /// let mut v = BTreeSet::new();
292 /// assert_eq!(v.len(), 0);
294 /// assert_eq!(v.len(), 1);
296 #[stable(feature = "rust1", since = "1.0.0")]
297 pub fn len(&self) -> usize {
301 /// Returns true if the set contains no elements.
306 /// use std::collections::BTreeSet;
308 /// let mut v = BTreeSet::new();
309 /// assert!(v.is_empty());
311 /// assert!(!v.is_empty());
313 #[stable(feature = "rust1", since = "1.0.0")]
314 pub fn is_empty(&self) -> bool {
318 /// Clears the set, removing all values.
323 /// use std::collections::BTreeSet;
325 /// let mut v = BTreeSet::new();
328 /// assert!(v.is_empty());
330 #[stable(feature = "rust1", since = "1.0.0")]
331 pub fn clear(&mut self) {
335 /// Returns `true` if the set contains a value.
337 /// The value may be any borrowed form of the set's value type,
338 /// but the ordering on the borrowed form *must* match the
339 /// ordering on the value type.
344 /// use std::collections::BTreeSet;
346 /// let set: BTreeSet<_> = [1, 2, 3].iter().cloned().collect();
347 /// assert_eq!(set.contains(&1), true);
348 /// assert_eq!(set.contains(&4), false);
350 #[stable(feature = "rust1", since = "1.0.0")]
351 pub fn contains<Q: ?Sized>(&self, value: &Q) -> bool
355 self.map.contains_key(value)
358 /// Returns a reference to the value in the set, if any, that is equal to the given value.
360 /// The value may be any borrowed form of the set's value type,
361 /// but the ordering on the borrowed form *must* match the
362 /// ordering on the value type.
363 #[unstable(feature = "set_recovery", issue = "28050")]
364 pub fn get<Q: ?Sized>(&self, value: &Q) -> Option<&T>
368 Recover::get(&self.map, value)
371 /// Returns `true` if the set has no elements in common with `other`.
372 /// This is equivalent to checking for an empty intersection.
377 /// use std::collections::BTreeSet;
379 /// let a: BTreeSet<_> = [1, 2, 3].iter().cloned().collect();
380 /// let mut b = BTreeSet::new();
382 /// assert_eq!(a.is_disjoint(&b), true);
384 /// assert_eq!(a.is_disjoint(&b), true);
386 /// assert_eq!(a.is_disjoint(&b), false);
388 #[stable(feature = "rust1", since = "1.0.0")]
389 pub fn is_disjoint(&self, other: &BTreeSet<T>) -> bool {
390 self.intersection(other).next().is_none()
393 /// Returns `true` if the set is a subset of another.
398 /// use std::collections::BTreeSet;
400 /// let sup: BTreeSet<_> = [1, 2, 3].iter().cloned().collect();
401 /// let mut set = BTreeSet::new();
403 /// assert_eq!(set.is_subset(&sup), true);
405 /// assert_eq!(set.is_subset(&sup), true);
407 /// assert_eq!(set.is_subset(&sup), false);
409 #[stable(feature = "rust1", since = "1.0.0")]
410 pub fn is_subset(&self, other: &BTreeSet<T>) -> bool {
411 // Stolen from TreeMap
412 let mut x = self.iter();
413 let mut y = other.iter();
414 let mut a = x.next();
415 let mut b = y.next();
426 Greater => return false,
427 Equal => a = x.next(),
435 /// Returns `true` if the set is a superset of another.
440 /// use std::collections::BTreeSet;
442 /// let sub: BTreeSet<_> = [1, 2].iter().cloned().collect();
443 /// let mut set = BTreeSet::new();
445 /// assert_eq!(set.is_superset(&sub), false);
449 /// assert_eq!(set.is_superset(&sub), false);
452 /// assert_eq!(set.is_superset(&sub), true);
454 #[stable(feature = "rust1", since = "1.0.0")]
455 pub fn is_superset(&self, other: &BTreeSet<T>) -> bool {
456 other.is_subset(self)
459 /// Adds a value to the set.
461 /// If the set did not have a value present, `true` is returned.
463 /// If the set did have this key present, that value is returned, and the
464 /// entry is not updated. See the [module-level documentation] for more.
466 /// [module-level documentation]: index.html#insert-and-complex-keys
471 /// use std::collections::BTreeSet;
473 /// let mut set = BTreeSet::new();
475 /// assert_eq!(set.insert(2), true);
476 /// assert_eq!(set.insert(2), false);
477 /// assert_eq!(set.len(), 1);
479 #[stable(feature = "rust1", since = "1.0.0")]
480 pub fn insert(&mut self, value: T) -> bool {
481 self.map.insert(value, ()).is_none()
484 /// Adds a value to the set, replacing the existing value, if any, that is equal to the given
485 /// one. Returns the replaced value.
486 #[unstable(feature = "set_recovery", issue = "28050")]
487 pub fn replace(&mut self, value: T) -> Option<T> {
488 Recover::replace(&mut self.map, value)
491 /// Removes a value from the set. Returns `true` if the value was
492 /// present in the set.
494 /// The value may be any borrowed form of the set's value type,
495 /// but the ordering on the borrowed form *must* match the
496 /// ordering on the value type.
501 /// use std::collections::BTreeSet;
503 /// let mut set = BTreeSet::new();
506 /// assert_eq!(set.remove(&2), true);
507 /// assert_eq!(set.remove(&2), false);
509 #[stable(feature = "rust1", since = "1.0.0")]
510 pub fn remove<Q: ?Sized>(&mut self, value: &Q) -> bool
514 self.map.remove(value).is_some()
517 /// Removes and returns the value in the set, if any, that is equal to the given one.
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.
522 #[unstable(feature = "set_recovery", issue = "28050")]
523 pub fn take<Q: ?Sized>(&mut self, value: &Q) -> Option<T>
527 Recover::take(&mut self.map, value)
531 #[stable(feature = "rust1", since = "1.0.0")]
532 impl<T: Ord> FromIterator<T> for BTreeSet<T> {
533 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> BTreeSet<T> {
534 let mut set = BTreeSet::new();
540 #[stable(feature = "rust1", since = "1.0.0")]
541 impl<T> IntoIterator for BTreeSet<T> {
543 type IntoIter = IntoIter<T>;
545 /// Gets an iterator for moving out the BtreeSet's contents.
550 /// use std::collections::BTreeSet;
552 /// let set: BTreeSet<usize> = [1, 2, 3, 4].iter().cloned().collect();
554 /// let v: Vec<_> = set.into_iter().collect();
555 /// assert_eq!(v, [1, 2, 3, 4]);
557 fn into_iter(self) -> IntoIter<T> {
558 fn first<A, B>((a, _): (A, B)) -> A {
561 let first: fn((T, ())) -> T = first; // coerce to fn pointer
563 IntoIter { iter: self.map.into_iter().map(first) }
567 #[stable(feature = "rust1", since = "1.0.0")]
568 impl<'a, T> IntoIterator for &'a BTreeSet<T> {
570 type IntoIter = Iter<'a, T>;
572 fn into_iter(self) -> Iter<'a, T> {
577 #[stable(feature = "rust1", since = "1.0.0")]
578 impl<T: Ord> Extend<T> for BTreeSet<T> {
580 fn extend<Iter: IntoIterator<Item = T>>(&mut self, iter: Iter) {
587 #[stable(feature = "extend_ref", since = "1.2.0")]
588 impl<'a, T: 'a + Ord + Copy> Extend<&'a T> for BTreeSet<T> {
589 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
590 self.extend(iter.into_iter().cloned());
594 #[stable(feature = "rust1", since = "1.0.0")]
595 impl<T: Ord> Default for BTreeSet<T> {
596 fn default() -> BTreeSet<T> {
601 #[stable(feature = "rust1", since = "1.0.0")]
602 impl<'a, 'b, T: Ord + Clone> Sub<&'b BTreeSet<T>> for &'a BTreeSet<T> {
603 type Output = BTreeSet<T>;
605 /// Returns the difference of `self` and `rhs` as a new `BTreeSet<T>`.
610 /// use std::collections::BTreeSet;
612 /// let a: BTreeSet<_> = vec![1, 2, 3].into_iter().collect();
613 /// let b: BTreeSet<_> = vec![3, 4, 5].into_iter().collect();
615 /// let result = &a - &b;
616 /// let result_vec: Vec<_> = result.into_iter().collect();
617 /// assert_eq!(result_vec, [1, 2]);
619 fn sub(self, rhs: &BTreeSet<T>) -> BTreeSet<T> {
620 self.difference(rhs).cloned().collect()
624 #[stable(feature = "rust1", since = "1.0.0")]
625 impl<'a, 'b, T: Ord + Clone> BitXor<&'b BTreeSet<T>> for &'a BTreeSet<T> {
626 type Output = BTreeSet<T>;
628 /// Returns the symmetric difference of `self` and `rhs` as a new `BTreeSet<T>`.
633 /// use std::collections::BTreeSet;
635 /// let a: BTreeSet<_> = vec![1, 2, 3].into_iter().collect();
636 /// let b: BTreeSet<_> = vec![2, 3, 4].into_iter().collect();
638 /// let result = &a ^ &b;
639 /// let result_vec: Vec<_> = result.into_iter().collect();
640 /// assert_eq!(result_vec, [1, 4]);
642 fn bitxor(self, rhs: &BTreeSet<T>) -> BTreeSet<T> {
643 self.symmetric_difference(rhs).cloned().collect()
647 #[stable(feature = "rust1", since = "1.0.0")]
648 impl<'a, 'b, T: Ord + Clone> BitAnd<&'b BTreeSet<T>> for &'a BTreeSet<T> {
649 type Output = BTreeSet<T>;
651 /// Returns the intersection of `self` and `rhs` as a new `BTreeSet<T>`.
656 /// use std::collections::BTreeSet;
658 /// let a: BTreeSet<_> = vec![1, 2, 3].into_iter().collect();
659 /// let b: BTreeSet<_> = vec![2, 3, 4].into_iter().collect();
661 /// let result = &a & &b;
662 /// let result_vec: Vec<_> = result.into_iter().collect();
663 /// assert_eq!(result_vec, [2, 3]);
665 fn bitand(self, rhs: &BTreeSet<T>) -> BTreeSet<T> {
666 self.intersection(rhs).cloned().collect()
670 #[stable(feature = "rust1", since = "1.0.0")]
671 impl<'a, 'b, T: Ord + Clone> BitOr<&'b BTreeSet<T>> for &'a BTreeSet<T> {
672 type Output = BTreeSet<T>;
674 /// Returns the union of `self` and `rhs` as a new `BTreeSet<T>`.
679 /// use std::collections::BTreeSet;
681 /// let a: BTreeSet<_> = vec![1, 2, 3].into_iter().collect();
682 /// let b: BTreeSet<_> = vec![3, 4, 5].into_iter().collect();
684 /// let result = &a | &b;
685 /// let result_vec: Vec<_> = result.into_iter().collect();
686 /// assert_eq!(result_vec, [1, 2, 3, 4, 5]);
688 fn bitor(self, rhs: &BTreeSet<T>) -> BTreeSet<T> {
689 self.union(rhs).cloned().collect()
693 #[stable(feature = "rust1", since = "1.0.0")]
694 impl<T: Debug> Debug for BTreeSet<T> {
695 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
696 f.debug_set().entries(self.iter()).finish()
700 impl<'a, T> Clone for Iter<'a, T> {
701 fn clone(&self) -> Iter<'a, T> {
702 Iter { iter: self.iter.clone() }
705 #[stable(feature = "rust1", since = "1.0.0")]
706 impl<'a, T> Iterator for Iter<'a, T> {
709 fn next(&mut self) -> Option<&'a T> {
712 fn size_hint(&self) -> (usize, Option<usize>) {
713 self.iter.size_hint()
716 #[stable(feature = "rust1", since = "1.0.0")]
717 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
718 fn next_back(&mut self) -> Option<&'a T> {
719 self.iter.next_back()
722 #[stable(feature = "rust1", since = "1.0.0")]
723 impl<'a, T> ExactSizeIterator for Iter<'a, T> {}
726 #[stable(feature = "rust1", since = "1.0.0")]
727 impl<T> Iterator for IntoIter<T> {
730 fn next(&mut self) -> Option<T> {
733 fn size_hint(&self) -> (usize, Option<usize>) {
734 self.iter.size_hint()
737 #[stable(feature = "rust1", since = "1.0.0")]
738 impl<T> DoubleEndedIterator for IntoIter<T> {
739 fn next_back(&mut self) -> Option<T> {
740 self.iter.next_back()
743 #[stable(feature = "rust1", since = "1.0.0")]
744 impl<T> ExactSizeIterator for IntoIter<T> {}
747 impl<'a, T> Clone for Range<'a, T> {
748 fn clone(&self) -> Range<'a, T> {
749 Range { iter: self.iter.clone() }
752 impl<'a, T> Iterator for Range<'a, T> {
755 fn next(&mut self) -> Option<&'a T> {
759 impl<'a, T> DoubleEndedIterator for Range<'a, T> {
760 fn next_back(&mut self) -> Option<&'a T> {
761 self.iter.next_back()
765 /// Compare `x` and `y`, but return `short` if x is None and `long` if y is None
766 fn cmp_opt<T: Ord>(x: Option<&T>, y: Option<&T>, short: Ordering, long: Ordering) -> Ordering {
770 (Some(x1), Some(y1)) => x1.cmp(y1),
774 impl<'a, T> Clone for Difference<'a, T> {
775 fn clone(&self) -> Difference<'a, T> {
782 #[stable(feature = "rust1", since = "1.0.0")]
783 impl<'a, T: Ord> Iterator for Difference<'a, T> {
786 fn next(&mut self) -> Option<&'a T> {
788 match cmp_opt(self.a.peek(), self.b.peek(), Less, Less) {
789 Less => return self.a.next(),
802 impl<'a, T> Clone for SymmetricDifference<'a, T> {
803 fn clone(&self) -> SymmetricDifference<'a, T> {
804 SymmetricDifference {
810 #[stable(feature = "rust1", since = "1.0.0")]
811 impl<'a, T: Ord> Iterator for SymmetricDifference<'a, T> {
814 fn next(&mut self) -> Option<&'a T> {
816 match cmp_opt(self.a.peek(), self.b.peek(), Greater, Less) {
817 Less => return self.a.next(),
822 Greater => return self.b.next(),
828 impl<'a, T> Clone for Intersection<'a, T> {
829 fn clone(&self) -> Intersection<'a, T> {
836 #[stable(feature = "rust1", since = "1.0.0")]
837 impl<'a, T: Ord> Iterator for Intersection<'a, T> {
840 fn next(&mut self) -> Option<&'a T> {
842 let o_cmp = match (self.a.peek(), self.b.peek()) {
845 (Some(a1), Some(b1)) => Some(a1.cmp(b1)),
854 return self.a.next();
864 impl<'a, T> Clone for Union<'a, T> {
865 fn clone(&self) -> Union<'a, T> {
872 #[stable(feature = "rust1", since = "1.0.0")]
873 impl<'a, T: Ord> Iterator for Union<'a, T> {
876 fn next(&mut self) -> Option<&'a T> {
878 match cmp_opt(self.a.peek(), self.b.peek(), Greater, Less) {
879 Less => return self.a.next(),
882 return self.a.next();
884 Greater => return self.b.next(),