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
16 use core::cmp::Ordering::{self, Less, Greater, Equal};
19 use core::iter::{Peekable, Map, FromIterator};
20 use core::ops::{BitOr, BitAnd, BitXor, Sub};
23 use btree_map::{BTreeMap, Keys};
26 // FIXME(conventions): implement bounded iterators
28 /// A set based on a B-Tree.
30 /// See BTreeMap's documentation for a detailed discussion of this collection's performance
31 /// benefits and drawbacks.
33 /// It is a logic error for an item to be modified in such a way that the item's ordering relative
34 /// to any other item, as determined by the `Ord` trait, changes while it is in the set. This is
35 /// normally only possible through `Cell`, `RefCell`, global state, I/O, or unsafe code.
36 #[derive(Clone, Hash, PartialEq, Eq, Ord, PartialOrd)]
37 #[stable(feature = "rust1", since = "1.0.0")]
38 pub struct BTreeSet<T>{
42 /// An iterator over a BTreeSet's items.
43 #[stable(feature = "rust1", since = "1.0.0")]
44 pub struct Iter<'a, T: 'a> {
48 /// An owning iterator over a BTreeSet's items.
49 #[stable(feature = "rust1", since = "1.0.0")]
50 pub struct IntoIter<T> {
51 iter: Map<::btree_map::IntoIter<T, ()>, fn((T, ())) -> T>
54 /// An iterator over a sub-range of BTreeSet's items.
55 pub struct Range<'a, T: 'a> {
56 iter: Map<::btree_map::Range<'a, T, ()>, fn((&'a T, &'a ())) -> &'a T>
59 /// A lazy iterator producing elements in the set difference (in-order).
60 #[stable(feature = "rust1", since = "1.0.0")]
61 pub struct Difference<'a, T:'a> {
62 a: Peekable<Iter<'a, T>>,
63 b: Peekable<Iter<'a, T>>,
66 /// A lazy iterator producing elements in the set symmetric difference (in-order).
67 #[stable(feature = "rust1", since = "1.0.0")]
68 pub struct SymmetricDifference<'a, T:'a> {
69 a: Peekable<Iter<'a, T>>,
70 b: Peekable<Iter<'a, T>>,
73 /// A lazy iterator producing elements in the set intersection (in-order).
74 #[stable(feature = "rust1", since = "1.0.0")]
75 pub struct Intersection<'a, T:'a> {
76 a: Peekable<Iter<'a, T>>,
77 b: Peekable<Iter<'a, T>>,
80 /// A lazy iterator producing elements in the set union (in-order).
81 #[stable(feature = "rust1", since = "1.0.0")]
82 pub struct Union<'a, T:'a> {
83 a: Peekable<Iter<'a, T>>,
84 b: Peekable<Iter<'a, T>>,
87 impl<T: Ord> BTreeSet<T> {
88 /// Makes a new BTreeSet with a reasonable choice of B.
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 = "collections",
106 reason = "probably want this to be on the type, eventually")]
107 pub fn with_b(b: usize) -> BTreeSet<T> {
108 BTreeSet { map: BTreeMap::with_b(b) }
112 impl<T> BTreeSet<T> {
113 /// Gets an iterator over the BTreeSet's contents.
118 /// use std::collections::BTreeSet;
120 /// let set: BTreeSet<usize> = [1, 2, 3, 4].iter().cloned().collect();
122 /// for x in set.iter() {
123 /// println!("{}", x);
126 /// let v: Vec<_> = set.iter().cloned().collect();
127 /// assert_eq!(v, [1, 2, 3, 4]);
129 #[stable(feature = "rust1", since = "1.0.0")]
130 pub fn iter(&self) -> Iter<T> {
131 Iter { iter: self.map.keys() }
135 impl<T: Ord> BTreeSet<T> {
136 /// Constructs a double-ended iterator over a sub-range of elements in the set, starting
137 /// at min, and ending at max. If min is `Unbounded`, then it will be treated as "negative
138 /// infinity", and if max is `Unbounded`, then it will be treated as "positive infinity".
139 /// Thus range(Unbounded, Unbounded) will yield the whole collection.
144 /// # #![feature(collections)]
145 /// use std::collections::BTreeSet;
146 /// use std::collections::Bound::{Included, Unbounded};
148 /// let mut set = BTreeSet::new();
152 /// for &elem in set.range(Included(&4), Included(&8)) {
153 /// println!("{}", elem);
155 /// assert_eq!(Some(&5), set.range(Included(&4), Unbounded).next());
157 #[unstable(feature = "collections",
158 reason = "matches collection reform specification, waiting for dust to settle")]
159 pub fn range<'a>(&'a self, min: Bound<&T>, max: Bound<&T>) -> Range<'a, T> {
160 fn first<A, B>((a, _): (A, B)) -> A { 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> {
188 Difference{a: self.iter().peekable(), b: other.iter().peekable()}
191 /// Visits the values representing the symmetric difference, in ascending order.
196 /// use std::collections::BTreeSet;
198 /// let mut a = BTreeSet::new();
202 /// let mut b = BTreeSet::new();
206 /// let sym_diff: Vec<_> = a.symmetric_difference(&b).cloned().collect();
207 /// assert_eq!(sym_diff, [1, 3]);
209 #[stable(feature = "rust1", since = "1.0.0")]
210 pub fn symmetric_difference<'a>(&'a self, other: &'a BTreeSet<T>)
211 -> SymmetricDifference<'a, T> {
212 SymmetricDifference{a: self.iter().peekable(), b: other.iter().peekable()}
215 /// Visits the values representing the intersection, in ascending order.
220 /// use std::collections::BTreeSet;
222 /// let mut a = BTreeSet::new();
226 /// let mut b = BTreeSet::new();
230 /// let intersection: Vec<_> = a.intersection(&b).cloned().collect();
231 /// assert_eq!(intersection, [2]);
233 #[stable(feature = "rust1", since = "1.0.0")]
234 pub fn intersection<'a>(&'a self, other: &'a BTreeSet<T>)
235 -> Intersection<'a, T> {
236 Intersection{a: self.iter().peekable(), b: other.iter().peekable()}
239 /// Visits the values representing the union, in ascending order.
244 /// use std::collections::BTreeSet;
246 /// let mut a = BTreeSet::new();
249 /// let mut b = BTreeSet::new();
252 /// let union: Vec<_> = a.union(&b).cloned().collect();
253 /// assert_eq!(union, [1, 2]);
255 #[stable(feature = "rust1", since = "1.0.0")]
256 pub fn union<'a>(&'a self, other: &'a BTreeSet<T>) -> Union<'a, T> {
257 Union{a: self.iter().peekable(), b: other.iter().peekable()}
260 /// Returns the number of elements in the set.
265 /// use std::collections::BTreeSet;
267 /// let mut v = BTreeSet::new();
268 /// assert_eq!(v.len(), 0);
270 /// assert_eq!(v.len(), 1);
272 #[stable(feature = "rust1", since = "1.0.0")]
273 pub fn len(&self) -> usize { self.map.len() }
275 /// Returns true if the set contains no elements.
280 /// use std::collections::BTreeSet;
282 /// let mut v = BTreeSet::new();
283 /// assert!(v.is_empty());
285 /// assert!(!v.is_empty());
287 #[stable(feature = "rust1", since = "1.0.0")]
288 pub fn is_empty(&self) -> bool { self.len() == 0 }
290 /// Clears the set, removing all values.
295 /// use std::collections::BTreeSet;
297 /// let mut v = BTreeSet::new();
300 /// assert!(v.is_empty());
302 #[stable(feature = "rust1", since = "1.0.0")]
303 pub fn clear(&mut self) {
307 /// Returns `true` if the set contains a value.
309 /// The value may be any borrowed form of the set's value type,
310 /// but the ordering on the borrowed form *must* match the
311 /// ordering on the value type.
316 /// use std::collections::BTreeSet;
318 /// let set: BTreeSet<_> = [1, 2, 3].iter().cloned().collect();
319 /// assert_eq!(set.contains(&1), true);
320 /// assert_eq!(set.contains(&4), false);
322 #[stable(feature = "rust1", since = "1.0.0")]
323 pub fn contains<Q: ?Sized>(&self, value: &Q) -> bool where T: Borrow<Q>, Q: Ord {
324 self.map.contains_key(value)
327 /// Returns `true` if the set has no elements in common with `other`.
328 /// This is equivalent to checking for an empty intersection.
333 /// use std::collections::BTreeSet;
335 /// let a: BTreeSet<_> = [1, 2, 3].iter().cloned().collect();
336 /// let mut b = BTreeSet::new();
338 /// assert_eq!(a.is_disjoint(&b), true);
340 /// assert_eq!(a.is_disjoint(&b), true);
342 /// assert_eq!(a.is_disjoint(&b), false);
344 #[stable(feature = "rust1", since = "1.0.0")]
345 pub fn is_disjoint(&self, other: &BTreeSet<T>) -> bool {
346 self.intersection(other).next().is_none()
349 /// Returns `true` if the set is a subset of another.
354 /// use std::collections::BTreeSet;
356 /// let sup: BTreeSet<_> = [1, 2, 3].iter().cloned().collect();
357 /// let mut set = BTreeSet::new();
359 /// assert_eq!(set.is_subset(&sup), true);
361 /// assert_eq!(set.is_subset(&sup), true);
363 /// assert_eq!(set.is_subset(&sup), false);
365 #[stable(feature = "rust1", since = "1.0.0")]
366 pub fn is_subset(&self, other: &BTreeSet<T>) -> bool {
367 // Stolen from TreeMap
368 let mut x = self.iter();
369 let mut y = other.iter();
370 let mut a = x.next();
371 let mut b = y.next();
382 Greater => return false,
383 Equal => a = x.next(),
391 /// Returns `true` if the set is a superset of another.
396 /// use std::collections::BTreeSet;
398 /// let sub: BTreeSet<_> = [1, 2].iter().cloned().collect();
399 /// let mut set = BTreeSet::new();
401 /// assert_eq!(set.is_superset(&sub), false);
405 /// assert_eq!(set.is_superset(&sub), false);
408 /// assert_eq!(set.is_superset(&sub), true);
410 #[stable(feature = "rust1", since = "1.0.0")]
411 pub fn is_superset(&self, other: &BTreeSet<T>) -> bool {
412 other.is_subset(self)
415 /// Adds a value to the set. Returns `true` if the value was not already
416 /// present in the set.
421 /// use std::collections::BTreeSet;
423 /// let mut set = BTreeSet::new();
425 /// assert_eq!(set.insert(2), true);
426 /// assert_eq!(set.insert(2), false);
427 /// assert_eq!(set.len(), 1);
429 #[stable(feature = "rust1", since = "1.0.0")]
430 pub fn insert(&mut self, value: T) -> bool {
431 self.map.insert(value, ()).is_none()
434 /// Removes a value from the set. Returns `true` if the value was
435 /// present in the set.
437 /// The value may be any borrowed form of the set's value type,
438 /// but the ordering on the borrowed form *must* match the
439 /// ordering on the value type.
444 /// use std::collections::BTreeSet;
446 /// let mut set = BTreeSet::new();
449 /// assert_eq!(set.remove(&2), true);
450 /// assert_eq!(set.remove(&2), false);
452 #[stable(feature = "rust1", since = "1.0.0")]
453 pub fn remove<Q: ?Sized>(&mut self, value: &Q) -> bool where T: Borrow<Q>, Q: Ord {
454 self.map.remove(value).is_some()
458 #[stable(feature = "rust1", since = "1.0.0")]
459 impl<T: Ord> FromIterator<T> for BTreeSet<T> {
460 fn from_iter<I: IntoIterator<Item=T>>(iter: I) -> BTreeSet<T> {
461 let mut set = BTreeSet::new();
467 #[stable(feature = "rust1", since = "1.0.0")]
468 impl<T> IntoIterator for BTreeSet<T> {
470 type IntoIter = IntoIter<T>;
472 /// Gets an iterator for moving out the BtreeSet's contents.
477 /// use std::collections::BTreeSet;
479 /// let set: BTreeSet<usize> = [1, 2, 3, 4].iter().cloned().collect();
481 /// let v: Vec<_> = set.into_iter().collect();
482 /// assert_eq!(v, [1, 2, 3, 4]);
484 fn into_iter(self) -> IntoIter<T> {
485 fn first<A, B>((a, _): (A, B)) -> A { a }
486 let first: fn((T, ())) -> T = first; // coerce to fn pointer
488 IntoIter { iter: self.map.into_iter().map(first) }
492 #[stable(feature = "rust1", since = "1.0.0")]
493 impl<'a, T> IntoIterator for &'a BTreeSet<T> {
495 type IntoIter = Iter<'a, T>;
497 fn into_iter(self) -> Iter<'a, T> {
502 #[stable(feature = "rust1", since = "1.0.0")]
503 impl<T: Ord> Extend<T> for BTreeSet<T> {
505 fn extend<Iter: IntoIterator<Item=T>>(&mut self, iter: Iter) {
512 #[stable(feature = "rust1", since = "1.0.0")]
513 impl<T: Ord> Default for BTreeSet<T> {
514 #[stable(feature = "rust1", since = "1.0.0")]
515 fn default() -> BTreeSet<T> {
520 #[stable(feature = "rust1", since = "1.0.0")]
521 impl<'a, 'b, T: Ord + Clone> Sub<&'b BTreeSet<T>> for &'a BTreeSet<T> {
522 type Output = BTreeSet<T>;
524 /// Returns the difference of `self` and `rhs` as a new `BTreeSet<T>`.
529 /// use std::collections::BTreeSet;
531 /// let a: BTreeSet<_> = vec![1, 2, 3].into_iter().collect();
532 /// let b: BTreeSet<_> = vec![3, 4, 5].into_iter().collect();
534 /// let result = &a - &b;
535 /// let result_vec: Vec<_> = result.into_iter().collect();
536 /// assert_eq!(result_vec, [1, 2]);
538 fn sub(self, rhs: &BTreeSet<T>) -> BTreeSet<T> {
539 self.difference(rhs).cloned().collect()
543 #[stable(feature = "rust1", since = "1.0.0")]
544 impl<'a, 'b, T: Ord + Clone> BitXor<&'b BTreeSet<T>> for &'a BTreeSet<T> {
545 type Output = BTreeSet<T>;
547 /// Returns the symmetric difference of `self` and `rhs` as a new `BTreeSet<T>`.
552 /// use std::collections::BTreeSet;
554 /// let a: BTreeSet<_> = vec![1, 2, 3].into_iter().collect();
555 /// let b: BTreeSet<_> = vec![2, 3, 4].into_iter().collect();
557 /// let result = &a ^ &b;
558 /// let result_vec: Vec<_> = result.into_iter().collect();
559 /// assert_eq!(result_vec, [1, 4]);
561 fn bitxor(self, rhs: &BTreeSet<T>) -> BTreeSet<T> {
562 self.symmetric_difference(rhs).cloned().collect()
566 #[stable(feature = "rust1", since = "1.0.0")]
567 impl<'a, 'b, T: Ord + Clone> BitAnd<&'b BTreeSet<T>> for &'a BTreeSet<T> {
568 type Output = BTreeSet<T>;
570 /// Returns the intersection of `self` and `rhs` as a new `BTreeSet<T>`.
575 /// use std::collections::BTreeSet;
577 /// let a: BTreeSet<_> = vec![1, 2, 3].into_iter().collect();
578 /// let b: BTreeSet<_> = vec![2, 3, 4].into_iter().collect();
580 /// let result = &a & &b;
581 /// let result_vec: Vec<_> = result.into_iter().collect();
582 /// assert_eq!(result_vec, [2, 3]);
584 fn bitand(self, rhs: &BTreeSet<T>) -> BTreeSet<T> {
585 self.intersection(rhs).cloned().collect()
589 #[stable(feature = "rust1", since = "1.0.0")]
590 impl<'a, 'b, T: Ord + Clone> BitOr<&'b BTreeSet<T>> for &'a BTreeSet<T> {
591 type Output = BTreeSet<T>;
593 /// Returns the union 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, 3, 4, 5]);
607 fn bitor(self, rhs: &BTreeSet<T>) -> BTreeSet<T> {
608 self.union(rhs).cloned().collect()
612 #[stable(feature = "rust1", since = "1.0.0")]
613 impl<T: Debug> Debug for BTreeSet<T> {
614 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
615 self.iter().fold(f.debug_set(), |b, e| b.entry(e)).finish()
619 impl<'a, T> Clone for Iter<'a, T> {
620 fn clone(&self) -> Iter<'a, T> { Iter { iter: self.iter.clone() } }
622 #[stable(feature = "rust1", since = "1.0.0")]
623 impl<'a, T> Iterator for Iter<'a, T> {
626 fn next(&mut self) -> Option<&'a T> { self.iter.next() }
627 fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
629 #[stable(feature = "rust1", since = "1.0.0")]
630 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
631 fn next_back(&mut self) -> Option<&'a T> { self.iter.next_back() }
633 #[stable(feature = "rust1", since = "1.0.0")]
634 impl<'a, T> ExactSizeIterator for Iter<'a, T> {}
637 #[stable(feature = "rust1", since = "1.0.0")]
638 impl<T> Iterator for IntoIter<T> {
641 fn next(&mut self) -> Option<T> { self.iter.next() }
642 fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
644 #[stable(feature = "rust1", since = "1.0.0")]
645 impl<T> DoubleEndedIterator for IntoIter<T> {
646 fn next_back(&mut self) -> Option<T> { self.iter.next_back() }
648 #[stable(feature = "rust1", since = "1.0.0")]
649 impl<T> ExactSizeIterator for IntoIter<T> {}
652 impl<'a, T> Clone for Range<'a, T> {
653 fn clone(&self) -> Range<'a, T> { Range { iter: self.iter.clone() } }
655 impl<'a, T> Iterator for Range<'a, T> {
658 fn next(&mut self) -> Option<&'a T> { self.iter.next() }
660 impl<'a, T> DoubleEndedIterator for Range<'a, T> {
661 fn next_back(&mut self) -> Option<&'a T> { self.iter.next_back() }
664 /// Compare `x` and `y`, but return `short` if x is None and `long` if y is None
665 fn cmp_opt<T: Ord>(x: Option<&T>, y: Option<&T>,
666 short: Ordering, long: Ordering) -> Ordering {
668 (None , _ ) => short,
670 (Some(x1), Some(y1)) => x1.cmp(y1),
674 impl<'a, T> Clone for Difference<'a, T> {
675 fn clone(&self) -> Difference<'a, T> {
676 Difference { a: self.a.clone(), b: self.b.clone() }
679 #[stable(feature = "rust1", since = "1.0.0")]
680 impl<'a, T: Ord> Iterator for Difference<'a, T> {
683 fn next(&mut self) -> Option<&'a T> {
685 match cmp_opt(self.a.peek(), self.b.peek(), Less, Less) {
686 Less => return self.a.next(),
687 Equal => { self.a.next(); self.b.next(); }
688 Greater => { self.b.next(); }
694 impl<'a, T> Clone for SymmetricDifference<'a, T> {
695 fn clone(&self) -> SymmetricDifference<'a, T> {
696 SymmetricDifference { a: self.a.clone(), b: self.b.clone() }
699 #[stable(feature = "rust1", since = "1.0.0")]
700 impl<'a, T: Ord> Iterator for SymmetricDifference<'a, T> {
703 fn next(&mut self) -> Option<&'a T> {
705 match cmp_opt(self.a.peek(), self.b.peek(), Greater, Less) {
706 Less => return self.a.next(),
707 Equal => { self.a.next(); self.b.next(); }
708 Greater => return self.b.next(),
714 impl<'a, T> Clone for Intersection<'a, T> {
715 fn clone(&self) -> Intersection<'a, T> {
716 Intersection { a: self.a.clone(), b: self.b.clone() }
719 #[stable(feature = "rust1", since = "1.0.0")]
720 impl<'a, T: Ord> Iterator for Intersection<'a, T> {
723 fn next(&mut self) -> Option<&'a T> {
725 let o_cmp = match (self.a.peek(), self.b.peek()) {
728 (Some(a1), Some(b1)) => Some(a1.cmp(b1)),
732 Some(Less) => { self.a.next(); }
733 Some(Equal) => { self.b.next(); return self.a.next() }
734 Some(Greater) => { self.b.next(); }
740 impl<'a, T> Clone for Union<'a, T> {
741 fn clone(&self) -> Union<'a, T> {
742 Union { a: self.a.clone(), b: self.b.clone() }
745 #[stable(feature = "rust1", since = "1.0.0")]
746 impl<'a, T: Ord> Iterator for Union<'a, T> {
749 fn next(&mut self) -> Option<&'a T> {
751 match cmp_opt(self.a.peek(), self.b.peek(), Greater, Less) {
752 Less => return self.a.next(),
753 Equal => { self.b.next(); return self.a.next() }
754 Greater => return self.b.next(),