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() }
103 impl<T> BTreeSet<T> {
104 /// Gets an iterator over the BTreeSet's contents.
109 /// use std::collections::BTreeSet;
111 /// let set: BTreeSet<usize> = [1, 2, 3, 4].iter().cloned().collect();
113 /// for x in set.iter() {
114 /// println!("{}", x);
117 /// let v: Vec<_> = set.iter().cloned().collect();
118 /// assert_eq!(v, [1, 2, 3, 4]);
120 #[stable(feature = "rust1", since = "1.0.0")]
121 pub fn iter(&self) -> Iter<T> {
122 Iter { iter: self.map.keys() }
126 impl<T: Ord> BTreeSet<T> {
127 /// Constructs a double-ended iterator over a sub-range of elements in the set, starting
128 /// at min, and ending at max. If min is `Unbounded`, then it will be treated as "negative
129 /// infinity", and if max is `Unbounded`, then it will be treated as "positive infinity".
130 /// Thus range(Unbounded, Unbounded) will yield the whole collection.
135 /// #![feature(btree_range, collections_bound)]
137 /// use std::collections::BTreeSet;
138 /// use std::collections::Bound::{Included, Unbounded};
140 /// let mut set = BTreeSet::new();
144 /// for &elem in set.range(Included(&4), Included(&8)) {
145 /// println!("{}", elem);
147 /// assert_eq!(Some(&5), set.range(Included(&4), Unbounded).next());
149 #[unstable(feature = "btree_range",
150 reason = "matches collection reform specification, waiting for dust to settle",
152 pub fn range<'a, Min: ?Sized + Ord = T, Max: ?Sized + Ord = T>(&'a self,
156 where T: Borrow<Min> + Borrow<Max>
158 fn first<A, B>((a, _): (A, B)) -> A {
161 let first: fn((&'a T, &'a ())) -> &'a T = first; // coerce to fn pointer
163 Range { iter: self.map.range(min, max).map(first) }
167 impl<T: Ord> BTreeSet<T> {
168 /// Visits the values representing the difference, in ascending order.
173 /// use std::collections::BTreeSet;
175 /// let mut a = BTreeSet::new();
179 /// let mut b = BTreeSet::new();
183 /// let diff: Vec<_> = a.difference(&b).cloned().collect();
184 /// assert_eq!(diff, [1]);
186 #[stable(feature = "rust1", since = "1.0.0")]
187 pub fn difference<'a>(&'a self, other: &'a BTreeSet<T>) -> Difference<'a, T> {
189 a: self.iter().peekable(),
190 b: other.iter().peekable(),
194 /// Visits the values representing the symmetric difference, in ascending order.
199 /// use std::collections::BTreeSet;
201 /// let mut a = BTreeSet::new();
205 /// let mut b = BTreeSet::new();
209 /// let sym_diff: Vec<_> = a.symmetric_difference(&b).cloned().collect();
210 /// assert_eq!(sym_diff, [1, 3]);
212 #[stable(feature = "rust1", since = "1.0.0")]
213 pub fn symmetric_difference<'a>(&'a self,
214 other: &'a BTreeSet<T>)
215 -> SymmetricDifference<'a, T> {
216 SymmetricDifference {
217 a: self.iter().peekable(),
218 b: other.iter().peekable(),
222 /// Visits the values representing the intersection, in ascending order.
227 /// use std::collections::BTreeSet;
229 /// let mut a = BTreeSet::new();
233 /// let mut b = BTreeSet::new();
237 /// let intersection: Vec<_> = a.intersection(&b).cloned().collect();
238 /// assert_eq!(intersection, [2]);
240 #[stable(feature = "rust1", since = "1.0.0")]
241 pub fn intersection<'a>(&'a self, other: &'a BTreeSet<T>) -> Intersection<'a, T> {
243 a: self.iter().peekable(),
244 b: other.iter().peekable(),
248 /// Visits the values representing the union, in ascending order.
253 /// use std::collections::BTreeSet;
255 /// let mut a = BTreeSet::new();
258 /// let mut b = BTreeSet::new();
261 /// let union: Vec<_> = a.union(&b).cloned().collect();
262 /// assert_eq!(union, [1, 2]);
264 #[stable(feature = "rust1", since = "1.0.0")]
265 pub fn union<'a>(&'a self, other: &'a BTreeSet<T>) -> Union<'a, T> {
267 a: self.iter().peekable(),
268 b: other.iter().peekable(),
272 /// Returns the number of elements in the set.
277 /// use std::collections::BTreeSet;
279 /// let mut v = BTreeSet::new();
280 /// assert_eq!(v.len(), 0);
282 /// assert_eq!(v.len(), 1);
284 #[stable(feature = "rust1", since = "1.0.0")]
285 pub fn len(&self) -> usize {
289 /// Returns true if the set contains no elements.
294 /// use std::collections::BTreeSet;
296 /// let mut v = BTreeSet::new();
297 /// assert!(v.is_empty());
299 /// assert!(!v.is_empty());
301 #[stable(feature = "rust1", since = "1.0.0")]
302 pub fn is_empty(&self) -> bool {
306 /// Clears the set, removing all values.
311 /// use std::collections::BTreeSet;
313 /// let mut v = BTreeSet::new();
316 /// assert!(v.is_empty());
318 #[stable(feature = "rust1", since = "1.0.0")]
319 pub fn clear(&mut self) {
323 /// Returns `true` if the set contains a value.
325 /// The value may be any borrowed form of the set's value type,
326 /// but the ordering on the borrowed form *must* match the
327 /// ordering on the value type.
332 /// use std::collections::BTreeSet;
334 /// let set: BTreeSet<_> = [1, 2, 3].iter().cloned().collect();
335 /// assert_eq!(set.contains(&1), true);
336 /// assert_eq!(set.contains(&4), false);
338 #[stable(feature = "rust1", since = "1.0.0")]
339 pub fn contains<Q: ?Sized>(&self, value: &Q) -> bool
343 self.map.contains_key(value)
346 /// Returns a reference to the value in the set, if any, that is equal to the given value.
348 /// The value may be any borrowed form of the set's value type,
349 /// but the ordering on the borrowed form *must* match the
350 /// ordering on the value type.
351 #[unstable(feature = "set_recovery", issue = "28050")]
352 pub fn get<Q: ?Sized>(&self, value: &Q) -> Option<&T>
356 Recover::get(&self.map, value)
359 /// Returns `true` if the set has no elements in common with `other`.
360 /// This is equivalent to checking for an empty intersection.
365 /// use std::collections::BTreeSet;
367 /// let a: BTreeSet<_> = [1, 2, 3].iter().cloned().collect();
368 /// let mut b = BTreeSet::new();
370 /// assert_eq!(a.is_disjoint(&b), true);
372 /// assert_eq!(a.is_disjoint(&b), true);
374 /// assert_eq!(a.is_disjoint(&b), false);
376 #[stable(feature = "rust1", since = "1.0.0")]
377 pub fn is_disjoint(&self, other: &BTreeSet<T>) -> bool {
378 self.intersection(other).next().is_none()
381 /// Returns `true` if the set is a subset of another.
386 /// use std::collections::BTreeSet;
388 /// let sup: BTreeSet<_> = [1, 2, 3].iter().cloned().collect();
389 /// let mut set = BTreeSet::new();
391 /// assert_eq!(set.is_subset(&sup), true);
393 /// assert_eq!(set.is_subset(&sup), true);
395 /// assert_eq!(set.is_subset(&sup), false);
397 #[stable(feature = "rust1", since = "1.0.0")]
398 pub fn is_subset(&self, other: &BTreeSet<T>) -> bool {
399 // Stolen from TreeMap
400 let mut x = self.iter();
401 let mut y = other.iter();
402 let mut a = x.next();
403 let mut b = y.next();
414 Greater => return false,
415 Equal => a = x.next(),
423 /// Returns `true` if the set is a superset of another.
428 /// use std::collections::BTreeSet;
430 /// let sub: BTreeSet<_> = [1, 2].iter().cloned().collect();
431 /// let mut set = BTreeSet::new();
433 /// assert_eq!(set.is_superset(&sub), false);
437 /// assert_eq!(set.is_superset(&sub), false);
440 /// assert_eq!(set.is_superset(&sub), true);
442 #[stable(feature = "rust1", since = "1.0.0")]
443 pub fn is_superset(&self, other: &BTreeSet<T>) -> bool {
444 other.is_subset(self)
447 /// Adds a value to the set.
449 /// If the set did not have a value present, `true` is returned.
451 /// If the set did have this key present, that value is returned, and the
452 /// entry is not updated. See the [module-level documentation] for more.
454 /// [module-level documentation]: index.html#insert-and-complex-keys
459 /// use std::collections::BTreeSet;
461 /// let mut set = BTreeSet::new();
463 /// assert_eq!(set.insert(2), true);
464 /// assert_eq!(set.insert(2), false);
465 /// assert_eq!(set.len(), 1);
467 #[stable(feature = "rust1", since = "1.0.0")]
468 pub fn insert(&mut self, value: T) -> bool {
469 self.map.insert(value, ()).is_none()
472 /// Adds a value to the set, replacing the existing value, if any, that is equal to the given
473 /// one. Returns the replaced value.
474 #[unstable(feature = "set_recovery", issue = "28050")]
475 pub fn replace(&mut self, value: T) -> Option<T> {
476 Recover::replace(&mut self.map, value)
479 /// Removes a value from the set. Returns `true` if the value was
480 /// present in the set.
482 /// The value may be any borrowed form of the set's value type,
483 /// but the ordering on the borrowed form *must* match the
484 /// ordering on the value type.
489 /// use std::collections::BTreeSet;
491 /// let mut set = BTreeSet::new();
494 /// assert_eq!(set.remove(&2), true);
495 /// assert_eq!(set.remove(&2), false);
497 #[stable(feature = "rust1", since = "1.0.0")]
498 pub fn remove<Q: ?Sized>(&mut self, value: &Q) -> bool
502 self.map.remove(value).is_some()
505 /// Removes and returns the value in the set, if any, that is equal to the given one.
507 /// The value may be any borrowed form of the set's value type,
508 /// but the ordering on the borrowed form *must* match the
509 /// ordering on the value type.
510 #[unstable(feature = "set_recovery", issue = "28050")]
511 pub fn take<Q: ?Sized>(&mut self, value: &Q) -> Option<T>
515 Recover::take(&mut self.map, value)
519 #[stable(feature = "rust1", since = "1.0.0")]
520 impl<T: Ord> FromIterator<T> for BTreeSet<T> {
521 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> BTreeSet<T> {
522 let mut set = BTreeSet::new();
528 #[stable(feature = "rust1", since = "1.0.0")]
529 impl<T> IntoIterator for BTreeSet<T> {
531 type IntoIter = IntoIter<T>;
533 /// Gets an iterator for moving out the BtreeSet's contents.
538 /// use std::collections::BTreeSet;
540 /// let set: BTreeSet<usize> = [1, 2, 3, 4].iter().cloned().collect();
542 /// let v: Vec<_> = set.into_iter().collect();
543 /// assert_eq!(v, [1, 2, 3, 4]);
545 fn into_iter(self) -> IntoIter<T> {
546 fn first<A, B>((a, _): (A, B)) -> A {
549 let first: fn((T, ())) -> T = first; // coerce to fn pointer
551 IntoIter { iter: self.map.into_iter().map(first) }
555 #[stable(feature = "rust1", since = "1.0.0")]
556 impl<'a, T> IntoIterator for &'a BTreeSet<T> {
558 type IntoIter = Iter<'a, T>;
560 fn into_iter(self) -> Iter<'a, T> {
565 #[stable(feature = "rust1", since = "1.0.0")]
566 impl<T: Ord> Extend<T> for BTreeSet<T> {
568 fn extend<Iter: IntoIterator<Item = T>>(&mut self, iter: Iter) {
575 #[stable(feature = "extend_ref", since = "1.2.0")]
576 impl<'a, T: 'a + Ord + Copy> Extend<&'a T> for BTreeSet<T> {
577 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
578 self.extend(iter.into_iter().cloned());
582 #[stable(feature = "rust1", since = "1.0.0")]
583 impl<T: Ord> Default for BTreeSet<T> {
584 fn default() -> BTreeSet<T> {
589 #[stable(feature = "rust1", since = "1.0.0")]
590 impl<'a, 'b, T: Ord + Clone> Sub<&'b BTreeSet<T>> for &'a BTreeSet<T> {
591 type Output = BTreeSet<T>;
593 /// Returns the difference of `self` and `rhs` as a new `BTreeSet<T>`.
598 /// use std::collections::BTreeSet;
600 /// let a: BTreeSet<_> = vec![1, 2, 3].into_iter().collect();
601 /// let b: BTreeSet<_> = vec![3, 4, 5].into_iter().collect();
603 /// let result = &a - &b;
604 /// let result_vec: Vec<_> = result.into_iter().collect();
605 /// assert_eq!(result_vec, [1, 2]);
607 fn sub(self, rhs: &BTreeSet<T>) -> BTreeSet<T> {
608 self.difference(rhs).cloned().collect()
612 #[stable(feature = "rust1", since = "1.0.0")]
613 impl<'a, 'b, T: Ord + Clone> BitXor<&'b BTreeSet<T>> for &'a BTreeSet<T> {
614 type Output = BTreeSet<T>;
616 /// Returns the symmetric difference of `self` and `rhs` as a new `BTreeSet<T>`.
621 /// use std::collections::BTreeSet;
623 /// let a: BTreeSet<_> = vec![1, 2, 3].into_iter().collect();
624 /// let b: BTreeSet<_> = vec![2, 3, 4].into_iter().collect();
626 /// let result = &a ^ &b;
627 /// let result_vec: Vec<_> = result.into_iter().collect();
628 /// assert_eq!(result_vec, [1, 4]);
630 fn bitxor(self, rhs: &BTreeSet<T>) -> BTreeSet<T> {
631 self.symmetric_difference(rhs).cloned().collect()
635 #[stable(feature = "rust1", since = "1.0.0")]
636 impl<'a, 'b, T: Ord + Clone> BitAnd<&'b BTreeSet<T>> for &'a BTreeSet<T> {
637 type Output = BTreeSet<T>;
639 /// Returns the intersection of `self` and `rhs` as a new `BTreeSet<T>`.
644 /// use std::collections::BTreeSet;
646 /// let a: BTreeSet<_> = vec![1, 2, 3].into_iter().collect();
647 /// let b: BTreeSet<_> = vec![2, 3, 4].into_iter().collect();
649 /// let result = &a & &b;
650 /// let result_vec: Vec<_> = result.into_iter().collect();
651 /// assert_eq!(result_vec, [2, 3]);
653 fn bitand(self, rhs: &BTreeSet<T>) -> BTreeSet<T> {
654 self.intersection(rhs).cloned().collect()
658 #[stable(feature = "rust1", since = "1.0.0")]
659 impl<'a, 'b, T: Ord + Clone> BitOr<&'b BTreeSet<T>> for &'a BTreeSet<T> {
660 type Output = BTreeSet<T>;
662 /// Returns the union of `self` and `rhs` as a new `BTreeSet<T>`.
667 /// use std::collections::BTreeSet;
669 /// let a: BTreeSet<_> = vec![1, 2, 3].into_iter().collect();
670 /// let b: BTreeSet<_> = vec![3, 4, 5].into_iter().collect();
672 /// let result = &a | &b;
673 /// let result_vec: Vec<_> = result.into_iter().collect();
674 /// assert_eq!(result_vec, [1, 2, 3, 4, 5]);
676 fn bitor(self, rhs: &BTreeSet<T>) -> BTreeSet<T> {
677 self.union(rhs).cloned().collect()
681 #[stable(feature = "rust1", since = "1.0.0")]
682 impl<T: Debug> Debug for BTreeSet<T> {
683 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
684 f.debug_set().entries(self.iter()).finish()
688 impl<'a, T> Clone for Iter<'a, T> {
689 fn clone(&self) -> Iter<'a, T> {
690 Iter { iter: self.iter.clone() }
693 #[stable(feature = "rust1", since = "1.0.0")]
694 impl<'a, T> Iterator for Iter<'a, T> {
697 fn next(&mut self) -> Option<&'a T> {
700 fn size_hint(&self) -> (usize, Option<usize>) {
701 self.iter.size_hint()
704 #[stable(feature = "rust1", since = "1.0.0")]
705 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
706 fn next_back(&mut self) -> Option<&'a T> {
707 self.iter.next_back()
710 #[stable(feature = "rust1", since = "1.0.0")]
711 impl<'a, T> ExactSizeIterator for Iter<'a, T> {}
714 #[stable(feature = "rust1", since = "1.0.0")]
715 impl<T> Iterator for IntoIter<T> {
718 fn next(&mut self) -> Option<T> {
721 fn size_hint(&self) -> (usize, Option<usize>) {
722 self.iter.size_hint()
725 #[stable(feature = "rust1", since = "1.0.0")]
726 impl<T> DoubleEndedIterator for IntoIter<T> {
727 fn next_back(&mut self) -> Option<T> {
728 self.iter.next_back()
731 #[stable(feature = "rust1", since = "1.0.0")]
732 impl<T> ExactSizeIterator for IntoIter<T> {}
735 impl<'a, T> Clone for Range<'a, T> {
736 fn clone(&self) -> Range<'a, T> {
737 Range { iter: self.iter.clone() }
740 impl<'a, T> Iterator for Range<'a, T> {
743 fn next(&mut self) -> Option<&'a T> {
747 impl<'a, T> DoubleEndedIterator for Range<'a, T> {
748 fn next_back(&mut self) -> Option<&'a T> {
749 self.iter.next_back()
753 /// Compare `x` and `y`, but return `short` if x is None and `long` if y is None
754 fn cmp_opt<T: Ord>(x: Option<&T>, y: Option<&T>, short: Ordering, long: Ordering) -> Ordering {
758 (Some(x1), Some(y1)) => x1.cmp(y1),
762 impl<'a, T> Clone for Difference<'a, T> {
763 fn clone(&self) -> Difference<'a, T> {
770 #[stable(feature = "rust1", since = "1.0.0")]
771 impl<'a, T: Ord> Iterator for Difference<'a, T> {
774 fn next(&mut self) -> Option<&'a T> {
776 match cmp_opt(self.a.peek(), self.b.peek(), Less, Less) {
777 Less => return self.a.next(),
790 impl<'a, T> Clone for SymmetricDifference<'a, T> {
791 fn clone(&self) -> SymmetricDifference<'a, T> {
792 SymmetricDifference {
798 #[stable(feature = "rust1", since = "1.0.0")]
799 impl<'a, T: Ord> Iterator for SymmetricDifference<'a, T> {
802 fn next(&mut self) -> Option<&'a T> {
804 match cmp_opt(self.a.peek(), self.b.peek(), Greater, Less) {
805 Less => return self.a.next(),
810 Greater => return self.b.next(),
816 impl<'a, T> Clone for Intersection<'a, T> {
817 fn clone(&self) -> Intersection<'a, T> {
824 #[stable(feature = "rust1", since = "1.0.0")]
825 impl<'a, T: Ord> Iterator for Intersection<'a, T> {
828 fn next(&mut self) -> Option<&'a T> {
830 let o_cmp = match (self.a.peek(), self.b.peek()) {
833 (Some(a1), Some(b1)) => Some(a1.cmp(b1)),
842 return self.a.next();
852 impl<'a, T> Clone for Union<'a, T> {
853 fn clone(&self) -> Union<'a, T> {
860 #[stable(feature = "rust1", since = "1.0.0")]
861 impl<'a, T: Ord> Iterator for Union<'a, T> {
864 fn next(&mut self) -> Option<&'a T> {
866 match cmp_opt(self.a.peek(), self.b.peek(), Greater, Less) {
867 Less => return self.a.next(),
870 return self.a.next();
872 Greater => return self.b.next(),