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> {
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 /// use std::collections::BTreeSet;
94 /// let mut set: BTreeSet<i32> = BTreeSet::new();
96 #[stable(feature = "rust1", since = "1.0.0")]
97 pub fn new() -> BTreeSet<T> {
98 BTreeSet { map: BTreeMap::new() }
101 /// Makes a new BTreeSet with the given B.
103 /// B cannot be less than 2.
104 #[unstable(feature = "btree_b",
105 reason = "probably want this to be on the type, eventually",
107 #[deprecated(since = "1.4.0", reason = "niche API")]
109 pub fn with_b(b: usize) -> BTreeSet<T> {
110 BTreeSet { map: BTreeMap::with_b(b) }
114 impl<T> BTreeSet<T> {
115 /// Gets an iterator over the BTreeSet's contents.
120 /// use std::collections::BTreeSet;
122 /// let set: BTreeSet<usize> = [1, 2, 3, 4].iter().cloned().collect();
124 /// for x in set.iter() {
125 /// println!("{}", x);
128 /// let v: Vec<_> = set.iter().cloned().collect();
129 /// assert_eq!(v, [1, 2, 3, 4]);
131 #[stable(feature = "rust1", since = "1.0.0")]
132 pub fn iter(&self) -> Iter<T> {
133 Iter { iter: self.map.keys() }
137 impl<T: Ord> BTreeSet<T> {
138 /// Constructs a double-ended iterator over a sub-range of elements in the set, starting
139 /// at min, and ending at max. If min is `Unbounded`, then it will be treated as "negative
140 /// infinity", and if max is `Unbounded`, then it will be treated as "positive infinity".
141 /// Thus range(Unbounded, Unbounded) will yield the whole collection.
146 /// #![feature(btree_range, collections_bound)]
148 /// use std::collections::BTreeSet;
149 /// use std::collections::Bound::{Included, Unbounded};
151 /// let mut set = BTreeSet::new();
155 /// for &elem in set.range(Included(&4), Included(&8)) {
156 /// println!("{}", elem);
158 /// assert_eq!(Some(&5), set.range(Included(&4), Unbounded).next());
160 #[unstable(feature = "btree_range",
161 reason = "matches collection reform specification, waiting for dust to settle",
163 pub fn range<'a, Min: ?Sized + Ord = T, Max: ?Sized + Ord = T>(&'a self, min: Bound<&Min>,
165 -> Range<'a, T> where
166 T: Borrow<Min> + Borrow<Max>,
168 fn first<A, B>((a, _): (A, B)) -> A { a }
169 let first: fn((&'a T, &'a ())) -> &'a T = first; // coerce to fn pointer
171 Range { iter: self.map.range(min, max).map(first) }
175 impl<T: Ord> BTreeSet<T> {
176 /// Visits the values representing the difference, in ascending order.
181 /// use std::collections::BTreeSet;
183 /// let mut a = BTreeSet::new();
187 /// let mut b = BTreeSet::new();
191 /// let diff: Vec<_> = a.difference(&b).cloned().collect();
192 /// assert_eq!(diff, [1]);
194 #[stable(feature = "rust1", since = "1.0.0")]
195 pub fn difference<'a>(&'a self, other: &'a BTreeSet<T>) -> Difference<'a, T> {
196 Difference{a: self.iter().peekable(), b: other.iter().peekable()}
199 /// Visits the values representing the symmetric difference, in ascending order.
204 /// use std::collections::BTreeSet;
206 /// let mut a = BTreeSet::new();
210 /// let mut b = BTreeSet::new();
214 /// let sym_diff: Vec<_> = a.symmetric_difference(&b).cloned().collect();
215 /// assert_eq!(sym_diff, [1, 3]);
217 #[stable(feature = "rust1", since = "1.0.0")]
218 pub fn symmetric_difference<'a>(&'a self, other: &'a BTreeSet<T>)
219 -> SymmetricDifference<'a, T> {
220 SymmetricDifference{a: self.iter().peekable(), b: other.iter().peekable()}
223 /// Visits the values representing the intersection, in ascending order.
228 /// use std::collections::BTreeSet;
230 /// let mut a = BTreeSet::new();
234 /// let mut b = BTreeSet::new();
238 /// let intersection: Vec<_> = a.intersection(&b).cloned().collect();
239 /// assert_eq!(intersection, [2]);
241 #[stable(feature = "rust1", since = "1.0.0")]
242 pub fn intersection<'a>(&'a self, other: &'a BTreeSet<T>)
243 -> Intersection<'a, T> {
244 Intersection{a: self.iter().peekable(), b: other.iter().peekable()}
247 /// Visits the values representing the union, in ascending order.
252 /// use std::collections::BTreeSet;
254 /// let mut a = BTreeSet::new();
257 /// let mut b = BTreeSet::new();
260 /// let union: Vec<_> = a.union(&b).cloned().collect();
261 /// assert_eq!(union, [1, 2]);
263 #[stable(feature = "rust1", since = "1.0.0")]
264 pub fn union<'a>(&'a self, other: &'a BTreeSet<T>) -> Union<'a, T> {
265 Union{a: self.iter().peekable(), b: other.iter().peekable()}
268 /// Returns the number of elements in the set.
273 /// use std::collections::BTreeSet;
275 /// let mut v = BTreeSet::new();
276 /// assert_eq!(v.len(), 0);
278 /// assert_eq!(v.len(), 1);
280 #[stable(feature = "rust1", since = "1.0.0")]
281 pub fn len(&self) -> usize { self.map.len() }
283 /// Returns true if the set contains no elements.
288 /// use std::collections::BTreeSet;
290 /// let mut v = BTreeSet::new();
291 /// assert!(v.is_empty());
293 /// assert!(!v.is_empty());
295 #[stable(feature = "rust1", since = "1.0.0")]
296 pub fn is_empty(&self) -> bool { self.len() == 0 }
298 /// Clears the set, removing all values.
303 /// use std::collections::BTreeSet;
305 /// let mut v = BTreeSet::new();
308 /// assert!(v.is_empty());
310 #[stable(feature = "rust1", since = "1.0.0")]
311 pub fn clear(&mut self) {
315 /// Returns `true` if the set contains a value.
317 /// The value may be any borrowed form of the set's value type,
318 /// but the ordering on the borrowed form *must* match the
319 /// ordering on the value type.
324 /// use std::collections::BTreeSet;
326 /// let set: BTreeSet<_> = [1, 2, 3].iter().cloned().collect();
327 /// assert_eq!(set.contains(&1), true);
328 /// assert_eq!(set.contains(&4), false);
330 #[stable(feature = "rust1", since = "1.0.0")]
331 pub fn contains<Q: ?Sized>(&self, value: &Q) -> bool where T: Borrow<Q>, Q: Ord {
332 self.map.contains_key(value)
335 /// Returns a reference to the value in the set, if any, that is equal to the given 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.
340 #[unstable(feature = "set_recovery", issue = "28050")]
341 pub fn get<Q: ?Sized>(&self, value: &Q) -> Option<&T> where T: Borrow<Q>, Q: Ord {
342 Recover::get(&self.map, value)
345 /// Returns `true` if the set has no elements in common with `other`.
346 /// This is equivalent to checking for an empty intersection.
351 /// use std::collections::BTreeSet;
353 /// let a: BTreeSet<_> = [1, 2, 3].iter().cloned().collect();
354 /// let mut b = BTreeSet::new();
356 /// assert_eq!(a.is_disjoint(&b), true);
358 /// assert_eq!(a.is_disjoint(&b), true);
360 /// assert_eq!(a.is_disjoint(&b), false);
362 #[stable(feature = "rust1", since = "1.0.0")]
363 pub fn is_disjoint(&self, other: &BTreeSet<T>) -> bool {
364 self.intersection(other).next().is_none()
367 /// Returns `true` if the set is a subset of another.
372 /// use std::collections::BTreeSet;
374 /// let sup: BTreeSet<_> = [1, 2, 3].iter().cloned().collect();
375 /// let mut set = BTreeSet::new();
377 /// assert_eq!(set.is_subset(&sup), true);
379 /// assert_eq!(set.is_subset(&sup), true);
381 /// assert_eq!(set.is_subset(&sup), false);
383 #[stable(feature = "rust1", since = "1.0.0")]
384 pub fn is_subset(&self, other: &BTreeSet<T>) -> bool {
385 // Stolen from TreeMap
386 let mut x = self.iter();
387 let mut y = other.iter();
388 let mut a = x.next();
389 let mut b = y.next();
400 Greater => return false,
401 Equal => a = x.next(),
409 /// Returns `true` if the set is a superset of another.
414 /// use std::collections::BTreeSet;
416 /// let sub: BTreeSet<_> = [1, 2].iter().cloned().collect();
417 /// let mut set = BTreeSet::new();
419 /// assert_eq!(set.is_superset(&sub), false);
423 /// assert_eq!(set.is_superset(&sub), false);
426 /// assert_eq!(set.is_superset(&sub), true);
428 #[stable(feature = "rust1", since = "1.0.0")]
429 pub fn is_superset(&self, other: &BTreeSet<T>) -> bool {
430 other.is_subset(self)
433 /// Adds a value to the set. Returns `true` if the value was not already
434 /// present in the set.
439 /// use std::collections::BTreeSet;
441 /// let mut set = BTreeSet::new();
443 /// assert_eq!(set.insert(2), true);
444 /// assert_eq!(set.insert(2), false);
445 /// assert_eq!(set.len(), 1);
447 #[stable(feature = "rust1", since = "1.0.0")]
448 pub fn insert(&mut self, value: T) -> bool {
449 self.map.insert(value, ()).is_none()
452 /// Adds a value to the set, replacing the existing value, if any, that is equal to the given
453 /// one. Returns the replaced value.
454 #[unstable(feature = "set_recovery", issue = "28050")]
455 pub fn replace(&mut self, value: T) -> Option<T> {
456 Recover::replace(&mut self.map, value)
459 /// Removes a value from the set. Returns `true` if the value was
460 /// present in the set.
462 /// The value may be any borrowed form of the set's value type,
463 /// but the ordering on the borrowed form *must* match the
464 /// ordering on the value type.
469 /// use std::collections::BTreeSet;
471 /// let mut set = BTreeSet::new();
474 /// assert_eq!(set.remove(&2), true);
475 /// assert_eq!(set.remove(&2), false);
477 #[stable(feature = "rust1", since = "1.0.0")]
478 pub fn remove<Q: ?Sized>(&mut self, value: &Q) -> bool where T: Borrow<Q>, Q: Ord {
479 self.map.remove(value).is_some()
482 /// Removes and returns the value in the set, if any, that is equal to the given one.
484 /// The value may be any borrowed form of the set's value type,
485 /// but the ordering on the borrowed form *must* match the
486 /// ordering on the value type.
487 #[unstable(feature = "set_recovery", issue = "28050")]
488 pub fn take<Q: ?Sized>(&mut self, value: &Q) -> Option<T> where T: Borrow<Q>, Q: Ord {
489 Recover::take(&mut self.map, value)
493 #[stable(feature = "rust1", since = "1.0.0")]
494 impl<T: Ord> FromIterator<T> for BTreeSet<T> {
495 fn from_iter<I: IntoIterator<Item=T>>(iter: I) -> BTreeSet<T> {
496 let mut set = BTreeSet::new();
502 #[stable(feature = "rust1", since = "1.0.0")]
503 impl<T> IntoIterator for BTreeSet<T> {
505 type IntoIter = IntoIter<T>;
507 /// Gets an iterator for moving out the BtreeSet's contents.
512 /// use std::collections::BTreeSet;
514 /// let set: BTreeSet<usize> = [1, 2, 3, 4].iter().cloned().collect();
516 /// let v: Vec<_> = set.into_iter().collect();
517 /// assert_eq!(v, [1, 2, 3, 4]);
519 fn into_iter(self) -> IntoIter<T> {
520 fn first<A, B>((a, _): (A, B)) -> A { a }
521 let first: fn((T, ())) -> T = first; // coerce to fn pointer
523 IntoIter { iter: self.map.into_iter().map(first) }
527 #[stable(feature = "rust1", since = "1.0.0")]
528 impl<'a, T> IntoIterator for &'a BTreeSet<T> {
530 type IntoIter = Iter<'a, T>;
532 fn into_iter(self) -> Iter<'a, T> {
537 #[stable(feature = "rust1", since = "1.0.0")]
538 impl<T: Ord> Extend<T> for BTreeSet<T> {
540 fn extend<Iter: IntoIterator<Item=T>>(&mut self, iter: Iter) {
547 #[stable(feature = "extend_ref", since = "1.2.0")]
548 impl<'a, T: 'a + Ord + Copy> Extend<&'a T> for BTreeSet<T> {
549 fn extend<I: IntoIterator<Item=&'a T>>(&mut self, iter: I) {
550 self.extend(iter.into_iter().cloned());
554 #[stable(feature = "rust1", since = "1.0.0")]
555 impl<T: Ord> Default for BTreeSet<T> {
556 #[stable(feature = "rust1", since = "1.0.0")]
557 fn default() -> BTreeSet<T> {
562 #[stable(feature = "rust1", since = "1.0.0")]
563 impl<'a, 'b, T: Ord + Clone> Sub<&'b BTreeSet<T>> for &'a BTreeSet<T> {
564 type Output = BTreeSet<T>;
566 /// Returns the difference of `self` and `rhs` as a new `BTreeSet<T>`.
571 /// use std::collections::BTreeSet;
573 /// let a: BTreeSet<_> = vec![1, 2, 3].into_iter().collect();
574 /// let b: BTreeSet<_> = vec![3, 4, 5].into_iter().collect();
576 /// let result = &a - &b;
577 /// let result_vec: Vec<_> = result.into_iter().collect();
578 /// assert_eq!(result_vec, [1, 2]);
580 fn sub(self, rhs: &BTreeSet<T>) -> BTreeSet<T> {
581 self.difference(rhs).cloned().collect()
585 #[stable(feature = "rust1", since = "1.0.0")]
586 impl<'a, 'b, T: Ord + Clone> BitXor<&'b BTreeSet<T>> for &'a BTreeSet<T> {
587 type Output = BTreeSet<T>;
589 /// Returns the symmetric difference of `self` and `rhs` as a new `BTreeSet<T>`.
594 /// use std::collections::BTreeSet;
596 /// let a: BTreeSet<_> = vec![1, 2, 3].into_iter().collect();
597 /// let b: BTreeSet<_> = vec![2, 3, 4].into_iter().collect();
599 /// let result = &a ^ &b;
600 /// let result_vec: Vec<_> = result.into_iter().collect();
601 /// assert_eq!(result_vec, [1, 4]);
603 fn bitxor(self, rhs: &BTreeSet<T>) -> BTreeSet<T> {
604 self.symmetric_difference(rhs).cloned().collect()
608 #[stable(feature = "rust1", since = "1.0.0")]
609 impl<'a, 'b, T: Ord + Clone> BitAnd<&'b BTreeSet<T>> for &'a BTreeSet<T> {
610 type Output = BTreeSet<T>;
612 /// Returns the intersection of `self` and `rhs` as a new `BTreeSet<T>`.
617 /// use std::collections::BTreeSet;
619 /// let a: BTreeSet<_> = vec![1, 2, 3].into_iter().collect();
620 /// let b: BTreeSet<_> = vec![2, 3, 4].into_iter().collect();
622 /// let result = &a & &b;
623 /// let result_vec: Vec<_> = result.into_iter().collect();
624 /// assert_eq!(result_vec, [2, 3]);
626 fn bitand(self, rhs: &BTreeSet<T>) -> BTreeSet<T> {
627 self.intersection(rhs).cloned().collect()
631 #[stable(feature = "rust1", since = "1.0.0")]
632 impl<'a, 'b, T: Ord + Clone> BitOr<&'b BTreeSet<T>> for &'a BTreeSet<T> {
633 type Output = BTreeSet<T>;
635 /// Returns the union of `self` and `rhs` as a new `BTreeSet<T>`.
640 /// use std::collections::BTreeSet;
642 /// let a: BTreeSet<_> = vec![1, 2, 3].into_iter().collect();
643 /// let b: BTreeSet<_> = vec![3, 4, 5].into_iter().collect();
645 /// let result = &a | &b;
646 /// let result_vec: Vec<_> = result.into_iter().collect();
647 /// assert_eq!(result_vec, [1, 2, 3, 4, 5]);
649 fn bitor(self, rhs: &BTreeSet<T>) -> BTreeSet<T> {
650 self.union(rhs).cloned().collect()
654 #[stable(feature = "rust1", since = "1.0.0")]
655 impl<T: Debug> Debug for BTreeSet<T> {
656 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
657 f.debug_set().entries(self.iter()).finish()
661 impl<'a, T> Clone for Iter<'a, T> {
662 fn clone(&self) -> Iter<'a, T> { Iter { iter: self.iter.clone() } }
664 #[stable(feature = "rust1", since = "1.0.0")]
665 impl<'a, T> Iterator for Iter<'a, T> {
668 fn next(&mut self) -> Option<&'a T> { self.iter.next() }
669 fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
671 #[stable(feature = "rust1", since = "1.0.0")]
672 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
673 fn next_back(&mut self) -> Option<&'a T> { self.iter.next_back() }
675 #[stable(feature = "rust1", since = "1.0.0")]
676 impl<'a, T> ExactSizeIterator for Iter<'a, T> {}
679 #[stable(feature = "rust1", since = "1.0.0")]
680 impl<T> Iterator for IntoIter<T> {
683 fn next(&mut self) -> Option<T> { self.iter.next() }
684 fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
686 #[stable(feature = "rust1", since = "1.0.0")]
687 impl<T> DoubleEndedIterator for IntoIter<T> {
688 fn next_back(&mut self) -> Option<T> { self.iter.next_back() }
690 #[stable(feature = "rust1", since = "1.0.0")]
691 impl<T> ExactSizeIterator for IntoIter<T> {}
694 impl<'a, T> Clone for Range<'a, T> {
695 fn clone(&self) -> Range<'a, T> { Range { iter: self.iter.clone() } }
697 impl<'a, T> Iterator for Range<'a, T> {
700 fn next(&mut self) -> Option<&'a T> { self.iter.next() }
702 impl<'a, T> DoubleEndedIterator for Range<'a, T> {
703 fn next_back(&mut self) -> Option<&'a T> { self.iter.next_back() }
706 /// Compare `x` and `y`, but return `short` if x is None and `long` if y is None
707 fn cmp_opt<T: Ord>(x: Option<&T>, y: Option<&T>,
708 short: Ordering, long: Ordering) -> Ordering {
710 (None , _ ) => short,
712 (Some(x1), Some(y1)) => x1.cmp(y1),
716 impl<'a, T> Clone for Difference<'a, T> {
717 fn clone(&self) -> Difference<'a, T> {
718 Difference { a: self.a.clone(), b: self.b.clone() }
721 #[stable(feature = "rust1", since = "1.0.0")]
722 impl<'a, T: Ord> Iterator for Difference<'a, T> {
725 fn next(&mut self) -> Option<&'a T> {
727 match cmp_opt(self.a.peek(), self.b.peek(), Less, Less) {
728 Less => return self.a.next(),
729 Equal => { self.a.next(); self.b.next(); }
730 Greater => { self.b.next(); }
736 impl<'a, T> Clone for SymmetricDifference<'a, T> {
737 fn clone(&self) -> SymmetricDifference<'a, T> {
738 SymmetricDifference { a: self.a.clone(), b: self.b.clone() }
741 #[stable(feature = "rust1", since = "1.0.0")]
742 impl<'a, T: Ord> Iterator for SymmetricDifference<'a, T> {
745 fn next(&mut self) -> Option<&'a T> {
747 match cmp_opt(self.a.peek(), self.b.peek(), Greater, Less) {
748 Less => return self.a.next(),
749 Equal => { self.a.next(); self.b.next(); }
750 Greater => return self.b.next(),
756 impl<'a, T> Clone for Intersection<'a, T> {
757 fn clone(&self) -> Intersection<'a, T> {
758 Intersection { a: self.a.clone(), b: self.b.clone() }
761 #[stable(feature = "rust1", since = "1.0.0")]
762 impl<'a, T: Ord> Iterator for Intersection<'a, T> {
765 fn next(&mut self) -> Option<&'a T> {
767 let o_cmp = match (self.a.peek(), self.b.peek()) {
770 (Some(a1), Some(b1)) => Some(a1.cmp(b1)),
774 Some(Less) => { self.a.next(); }
775 Some(Equal) => { self.b.next(); return self.a.next() }
776 Some(Greater) => { self.b.next(); }
782 impl<'a, T> Clone for Union<'a, T> {
783 fn clone(&self) -> Union<'a, T> {
784 Union { a: self.a.clone(), b: self.b.clone() }
787 #[stable(feature = "rust1", since = "1.0.0")]
788 impl<'a, T: Ord> Iterator for Union<'a, T> {
791 fn next(&mut self) -> Option<&'a T> {
793 match cmp_opt(self.a.peek(), self.b.peek(), Greater, Less) {
794 Less => return self.a.next(),
795 Equal => { self.b.next(); return self.a.next() }
796 Greater => return self.b.next(),