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};
15 use core::cmp::{min, max};
18 use core::iter::{Peekable, FromIterator, FusedIterator};
19 use core::ops::{BitOr, BitAnd, BitXor, Sub};
22 use btree_map::{BTreeMap, Keys};
24 use range::RangeArgument;
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.
37 /// [`BTreeMap`]: struct.BTreeMap.html
38 /// [`Ord`]: ../../std/cmp/trait.Ord.html
39 /// [`Cell`]: ../../std/cell/struct.Cell.html
40 /// [`RefCell`]: ../../std/cell/struct.RefCell.html
45 /// use std::collections::BTreeSet;
47 /// // Type inference lets us omit an explicit type signature (which
48 /// // would be `BTreeSet<&str>` in this example).
49 /// let mut books = BTreeSet::new();
51 /// // Add some books.
52 /// books.insert("A Dance With Dragons");
53 /// books.insert("To Kill a Mockingbird");
54 /// books.insert("The Odyssey");
55 /// books.insert("The Great Gatsby");
57 /// // Check for a specific one.
58 /// if !books.contains("The Winds of Winter") {
59 /// println!("We have {} books, but The Winds of Winter ain't one.",
64 /// books.remove("The Odyssey");
66 /// // Iterate over everything.
67 /// for book in &books {
68 /// println!("{}", book);
71 #[derive(Clone, Hash, PartialEq, Eq, Ord, PartialOrd)]
72 #[stable(feature = "rust1", since = "1.0.0")]
73 pub struct BTreeSet<T> {
77 /// An iterator over the items of a `BTreeSet`.
79 /// This `struct` is created by the [`iter`] method on [`BTreeSet`].
80 /// See its documentation for more.
82 /// [`BTreeSet`]: struct.BTreeSet.html
83 /// [`iter`]: struct.BTreeSet.html#method.iter
84 #[stable(feature = "rust1", since = "1.0.0")]
85 pub struct Iter<'a, T: 'a> {
86 iter: Keys<'a, T, ()>,
89 #[stable(feature = "collection_debug", since = "1.17.0")]
90 impl<'a, T: 'a + fmt::Debug> fmt::Debug for Iter<'a, T> {
91 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
93 .field(&self.iter.clone())
98 /// An owning iterator over the items of a `BTreeSet`.
100 /// This `struct` is created by the [`into_iter`] method on [`BTreeSet`]
101 /// (provided by the `IntoIterator` trait). See its documentation for more.
103 /// [`BTreeSet`]: struct.BTreeSet.html
104 /// [`into_iter`]: struct.BTreeSet.html#method.into_iter
105 #[stable(feature = "rust1", since = "1.0.0")]
107 pub struct IntoIter<T> {
108 iter: ::btree_map::IntoIter<T, ()>,
111 /// An iterator over a sub-range of items in a `BTreeSet`.
113 /// This `struct` is created by the [`range`] method on [`BTreeSet`].
114 /// See its documentation for more.
116 /// [`BTreeSet`]: struct.BTreeSet.html
117 /// [`range`]: struct.BTreeSet.html#method.range
119 #[stable(feature = "btree_range", since = "1.17.0")]
120 pub struct Range<'a, T: 'a> {
121 iter: ::btree_map::Range<'a, T, ()>,
124 /// A lazy iterator producing elements in the difference of `BTreeSet`s.
126 /// This `struct` is created by the [`difference`] method on [`BTreeSet`].
127 /// See its documentation for more.
129 /// [`BTreeSet`]: struct.BTreeSet.html
130 /// [`difference`]: struct.BTreeSet.html#method.difference
131 #[stable(feature = "rust1", since = "1.0.0")]
132 pub struct Difference<'a, T: 'a> {
133 a: Peekable<Iter<'a, T>>,
134 b: Peekable<Iter<'a, T>>,
137 #[stable(feature = "collection_debug", since = "1.17.0")]
138 impl<'a, T: 'a + fmt::Debug> fmt::Debug for Difference<'a, T> {
139 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
140 f.debug_tuple("Difference")
141 .field(&self.clone())
146 /// A lazy iterator producing elements in the symmetric difference of `BTreeSet`s.
148 /// This `struct` is created by the [`symmetric_difference`] method on
149 /// [`BTreeSet`]. See its documentation for more.
151 /// [`BTreeSet`]: struct.BTreeSet.html
152 /// [`symmetric_difference`]: struct.BTreeSet.html#method.symmetric_difference
153 #[stable(feature = "rust1", since = "1.0.0")]
154 pub struct SymmetricDifference<'a, T: 'a> {
155 a: Peekable<Iter<'a, T>>,
156 b: Peekable<Iter<'a, T>>,
159 #[stable(feature = "collection_debug", since = "1.17.0")]
160 impl<'a, T: 'a + fmt::Debug> fmt::Debug for SymmetricDifference<'a, T> {
161 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
162 f.debug_tuple("SymmetricDifference")
163 .field(&self.clone())
168 /// A lazy iterator producing elements in the intersection of `BTreeSet`s.
170 /// This `struct` is created by the [`intersection`] method on [`BTreeSet`].
171 /// See its documentation for more.
173 /// [`BTreeSet`]: struct.BTreeSet.html
174 /// [`intersection`]: struct.BTreeSet.html#method.intersection
175 #[stable(feature = "rust1", since = "1.0.0")]
176 pub struct Intersection<'a, T: 'a> {
177 a: Peekable<Iter<'a, T>>,
178 b: Peekable<Iter<'a, T>>,
181 #[stable(feature = "collection_debug", since = "1.17.0")]
182 impl<'a, T: 'a + fmt::Debug> fmt::Debug for Intersection<'a, T> {
183 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
184 f.debug_tuple("Intersection")
185 .field(&self.clone())
190 /// A lazy iterator producing elements in the union of `BTreeSet`s.
192 /// This `struct` is created by the [`union`] method on [`BTreeSet`].
193 /// See its documentation for more.
195 /// [`BTreeSet`]: struct.BTreeSet.html
196 /// [`union`]: struct.BTreeSet.html#method.union
197 #[stable(feature = "rust1", since = "1.0.0")]
198 pub struct Union<'a, T: 'a> {
199 a: Peekable<Iter<'a, T>>,
200 b: Peekable<Iter<'a, T>>,
203 #[stable(feature = "collection_debug", since = "1.17.0")]
204 impl<'a, T: 'a + fmt::Debug> fmt::Debug for Union<'a, T> {
205 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
206 f.debug_tuple("Union")
207 .field(&self.clone())
212 impl<T: Ord> BTreeSet<T> {
213 /// Makes a new `BTreeSet` with a reasonable choice of B.
218 /// # #![allow(unused_mut)]
219 /// use std::collections::BTreeSet;
221 /// let mut set: BTreeSet<i32> = BTreeSet::new();
223 #[stable(feature = "rust1", since = "1.0.0")]
224 pub fn new() -> BTreeSet<T> {
225 BTreeSet { map: BTreeMap::new() }
229 impl<T> BTreeSet<T> {
230 /// Gets an iterator that visits the values in the `BTreeSet` in ascending order.
235 /// use std::collections::BTreeSet;
237 /// let set: BTreeSet<usize> = [1, 2, 3].iter().cloned().collect();
238 /// let mut set_iter = set.iter();
239 /// assert_eq!(set_iter.next(), Some(&1));
240 /// assert_eq!(set_iter.next(), Some(&2));
241 /// assert_eq!(set_iter.next(), Some(&3));
242 /// assert_eq!(set_iter.next(), None);
245 /// Values returned by the iterator are returned in ascending order:
248 /// use std::collections::BTreeSet;
250 /// let set: BTreeSet<usize> = [3, 1, 2].iter().cloned().collect();
251 /// let mut set_iter = set.iter();
252 /// assert_eq!(set_iter.next(), Some(&1));
253 /// assert_eq!(set_iter.next(), Some(&2));
254 /// assert_eq!(set_iter.next(), Some(&3));
255 /// assert_eq!(set_iter.next(), None);
257 #[stable(feature = "rust1", since = "1.0.0")]
258 pub fn iter(&self) -> Iter<T> {
259 Iter { iter: self.map.keys() }
263 impl<T: Ord> BTreeSet<T> {
264 /// Constructs a double-ended iterator over a sub-range of elements in the set.
265 /// The simplest way is to use the range syntax `min..max`, thus `range(min..max)` will
266 /// yield elements from min (inclusive) to max (exclusive).
267 /// The range may also be entered as `(Bound<T>, Bound<T>)`, so for example
268 /// `range((Excluded(4), Included(10)))` will yield a left-exclusive, right-inclusive
269 /// range from 4 to 10.
274 /// use std::collections::BTreeSet;
275 /// use std::collections::Bound::Included;
277 /// let mut set = BTreeSet::new();
281 /// for &elem in set.range((Included(&4), Included(&8))) {
282 /// println!("{}", elem);
284 /// assert_eq!(Some(&5), set.range(4..).next());
286 #[stable(feature = "btree_range", since = "1.17.0")]
287 pub fn range<K: ?Sized, R>(&self, range: R) -> Range<T>
288 where K: Ord, T: Borrow<K>, R: RangeArgument<K>
290 Range { iter: self.map.range(range) }
294 impl<T: Ord> BTreeSet<T> {
295 /// Visits the values representing the difference,
296 /// i.e. the values that are in `self` but not in `other`,
297 /// in ascending order.
302 /// use std::collections::BTreeSet;
304 /// let mut a = BTreeSet::new();
308 /// let mut b = BTreeSet::new();
312 /// let diff: Vec<_> = a.difference(&b).cloned().collect();
313 /// assert_eq!(diff, [1]);
315 #[stable(feature = "rust1", since = "1.0.0")]
316 pub fn difference<'a>(&'a self, other: &'a BTreeSet<T>) -> Difference<'a, T> {
318 a: self.iter().peekable(),
319 b: other.iter().peekable(),
323 /// Visits the values representing the symmetric difference,
324 /// i.e. the values that are in `self` or in `other` but not in both,
325 /// in ascending order.
330 /// use std::collections::BTreeSet;
332 /// let mut a = BTreeSet::new();
336 /// let mut b = BTreeSet::new();
340 /// let sym_diff: Vec<_> = a.symmetric_difference(&b).cloned().collect();
341 /// assert_eq!(sym_diff, [1, 3]);
343 #[stable(feature = "rust1", since = "1.0.0")]
344 pub fn symmetric_difference<'a>(&'a self,
345 other: &'a BTreeSet<T>)
346 -> SymmetricDifference<'a, T> {
347 SymmetricDifference {
348 a: self.iter().peekable(),
349 b: other.iter().peekable(),
353 /// Visits the values representing the intersection,
354 /// i.e. the values that are both in `self` and `other`,
355 /// in ascending order.
360 /// use std::collections::BTreeSet;
362 /// let mut a = BTreeSet::new();
366 /// let mut b = BTreeSet::new();
370 /// let intersection: Vec<_> = a.intersection(&b).cloned().collect();
371 /// assert_eq!(intersection, [2]);
373 #[stable(feature = "rust1", since = "1.0.0")]
374 pub fn intersection<'a>(&'a self, other: &'a BTreeSet<T>) -> Intersection<'a, T> {
376 a: self.iter().peekable(),
377 b: other.iter().peekable(),
381 /// Visits the values representing the union,
382 /// i.e. all the values in `self` or `other`, without duplicates,
383 /// in ascending order.
388 /// use std::collections::BTreeSet;
390 /// let mut a = BTreeSet::new();
393 /// let mut b = BTreeSet::new();
396 /// let union: Vec<_> = a.union(&b).cloned().collect();
397 /// assert_eq!(union, [1, 2]);
399 #[stable(feature = "rust1", since = "1.0.0")]
400 pub fn union<'a>(&'a self, other: &'a BTreeSet<T>) -> Union<'a, T> {
402 a: self.iter().peekable(),
403 b: other.iter().peekable(),
407 /// Returns the number of elements in the set.
412 /// use std::collections::BTreeSet;
414 /// let mut v = BTreeSet::new();
415 /// assert_eq!(v.len(), 0);
417 /// assert_eq!(v.len(), 1);
419 #[stable(feature = "rust1", since = "1.0.0")]
420 pub fn len(&self) -> usize {
424 /// Returns `true` if the set contains no elements.
429 /// use std::collections::BTreeSet;
431 /// let mut v = BTreeSet::new();
432 /// assert!(v.is_empty());
434 /// assert!(!v.is_empty());
436 #[stable(feature = "rust1", since = "1.0.0")]
437 pub fn is_empty(&self) -> bool {
441 /// Clears the set, removing all values.
446 /// use std::collections::BTreeSet;
448 /// let mut v = BTreeSet::new();
451 /// assert!(v.is_empty());
453 #[stable(feature = "rust1", since = "1.0.0")]
454 pub fn clear(&mut self) {
458 /// Returns `true` if the set contains a value.
460 /// The value may be any borrowed form of the set's value type,
461 /// but the ordering on the borrowed form *must* match the
462 /// ordering on the value type.
467 /// use std::collections::BTreeSet;
469 /// let set: BTreeSet<_> = [1, 2, 3].iter().cloned().collect();
470 /// assert_eq!(set.contains(&1), true);
471 /// assert_eq!(set.contains(&4), false);
473 #[stable(feature = "rust1", since = "1.0.0")]
474 pub fn contains<Q: ?Sized>(&self, value: &Q) -> bool
478 self.map.contains_key(value)
481 /// Returns a reference to the value in the set, if any, that is equal to the given value.
483 /// The value may be any borrowed form of the set's value type,
484 /// but the ordering on the borrowed form *must* match the
485 /// ordering on the value type.
486 #[stable(feature = "set_recovery", since = "1.9.0")]
487 pub fn get<Q: ?Sized>(&self, value: &Q) -> Option<&T>
491 Recover::get(&self.map, value)
494 /// Returns `true` if `self` has no elements in common with `other`.
495 /// This is equivalent to checking for an empty intersection.
500 /// use std::collections::BTreeSet;
502 /// let a: BTreeSet<_> = [1, 2, 3].iter().cloned().collect();
503 /// let mut b = BTreeSet::new();
505 /// assert_eq!(a.is_disjoint(&b), true);
507 /// assert_eq!(a.is_disjoint(&b), true);
509 /// assert_eq!(a.is_disjoint(&b), false);
511 #[stable(feature = "rust1", since = "1.0.0")]
512 pub fn is_disjoint(&self, other: &BTreeSet<T>) -> bool {
513 self.intersection(other).next().is_none()
516 /// Returns `true` if the set is a subset of another,
517 /// i.e. `other` contains at least all the values in `self`.
522 /// use std::collections::BTreeSet;
524 /// let sup: BTreeSet<_> = [1, 2, 3].iter().cloned().collect();
525 /// let mut set = BTreeSet::new();
527 /// assert_eq!(set.is_subset(&sup), true);
529 /// assert_eq!(set.is_subset(&sup), true);
531 /// assert_eq!(set.is_subset(&sup), false);
533 #[stable(feature = "rust1", since = "1.0.0")]
534 pub fn is_subset(&self, other: &BTreeSet<T>) -> bool {
535 // Stolen from TreeMap
536 let mut x = self.iter();
537 let mut y = other.iter();
538 let mut a = x.next();
539 let mut b = y.next();
550 Greater => return false,
551 Equal => a = x.next(),
559 /// Returns `true` if the set is a superset of another,
560 /// i.e. `self` contains at least all the values in `other`.
565 /// use std::collections::BTreeSet;
567 /// let sub: BTreeSet<_> = [1, 2].iter().cloned().collect();
568 /// let mut set = BTreeSet::new();
570 /// assert_eq!(set.is_superset(&sub), false);
574 /// assert_eq!(set.is_superset(&sub), false);
577 /// assert_eq!(set.is_superset(&sub), true);
579 #[stable(feature = "rust1", since = "1.0.0")]
580 pub fn is_superset(&self, other: &BTreeSet<T>) -> bool {
581 other.is_subset(self)
584 /// Adds a value to the set.
586 /// If the set did not have this value present, `true` is returned.
588 /// If the set did have this value present, `false` is returned, and the
589 /// entry is not updated. See the [module-level documentation] for more.
591 /// [module-level documentation]: index.html#insert-and-complex-keys
596 /// use std::collections::BTreeSet;
598 /// let mut set = BTreeSet::new();
600 /// assert_eq!(set.insert(2), true);
601 /// assert_eq!(set.insert(2), false);
602 /// assert_eq!(set.len(), 1);
604 #[stable(feature = "rust1", since = "1.0.0")]
605 pub fn insert(&mut self, value: T) -> bool {
606 self.map.insert(value, ()).is_none()
609 /// Adds a value to the set, replacing the existing value, if any, that is equal to the given
610 /// one. Returns the replaced value.
611 #[stable(feature = "set_recovery", since = "1.9.0")]
612 pub fn replace(&mut self, value: T) -> Option<T> {
613 Recover::replace(&mut self.map, value)
616 /// Removes a value from the set. Returns `true` if the value was
617 /// present in the set.
619 /// The value may be any borrowed form of the set's value type,
620 /// but the ordering on the borrowed form *must* match the
621 /// ordering on the value type.
626 /// use std::collections::BTreeSet;
628 /// let mut set = BTreeSet::new();
631 /// assert_eq!(set.remove(&2), true);
632 /// assert_eq!(set.remove(&2), false);
634 #[stable(feature = "rust1", since = "1.0.0")]
635 pub fn remove<Q: ?Sized>(&mut self, value: &Q) -> bool
639 self.map.remove(value).is_some()
642 /// Removes and returns the value in the set, if any, that is equal to the given one.
644 /// The value may be any borrowed form of the set's value type,
645 /// but the ordering on the borrowed form *must* match the
646 /// ordering on the value type.
647 #[stable(feature = "set_recovery", since = "1.9.0")]
648 pub fn take<Q: ?Sized>(&mut self, value: &Q) -> Option<T>
652 Recover::take(&mut self.map, value)
655 /// Moves all elements from `other` into `Self`, leaving `other` empty.
660 /// use std::collections::BTreeSet;
662 /// let mut a = BTreeSet::new();
667 /// let mut b = BTreeSet::new();
672 /// a.append(&mut b);
674 /// assert_eq!(a.len(), 5);
675 /// assert_eq!(b.len(), 0);
677 /// assert!(a.contains(&1));
678 /// assert!(a.contains(&2));
679 /// assert!(a.contains(&3));
680 /// assert!(a.contains(&4));
681 /// assert!(a.contains(&5));
683 #[stable(feature = "btree_append", since = "1.11.0")]
684 pub fn append(&mut self, other: &mut Self) {
685 self.map.append(&mut other.map);
688 /// Splits the collection into two at the given key. Returns everything after the given key,
689 /// including the key.
696 /// use std::collections::BTreeMap;
698 /// let mut a = BTreeMap::new();
699 /// a.insert(1, "a");
700 /// a.insert(2, "b");
701 /// a.insert(3, "c");
702 /// a.insert(17, "d");
703 /// a.insert(41, "e");
705 /// let b = a.split_off(&3);
707 /// assert_eq!(a.len(), 2);
708 /// assert_eq!(b.len(), 3);
710 /// assert_eq!(a[&1], "a");
711 /// assert_eq!(a[&2], "b");
713 /// assert_eq!(b[&3], "c");
714 /// assert_eq!(b[&17], "d");
715 /// assert_eq!(b[&41], "e");
717 #[stable(feature = "btree_split_off", since = "1.11.0")]
718 pub fn split_off<Q: ?Sized + Ord>(&mut self, key: &Q) -> Self where T: Borrow<Q> {
719 BTreeSet { map: self.map.split_off(key) }
723 #[stable(feature = "rust1", since = "1.0.0")]
724 impl<T: Ord> FromIterator<T> for BTreeSet<T> {
725 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> BTreeSet<T> {
726 let mut set = BTreeSet::new();
732 #[stable(feature = "rust1", since = "1.0.0")]
733 impl<T> IntoIterator for BTreeSet<T> {
735 type IntoIter = IntoIter<T>;
737 /// Gets an iterator for moving out the `BTreeSet`'s contents.
742 /// use std::collections::BTreeSet;
744 /// let set: BTreeSet<usize> = [1, 2, 3, 4].iter().cloned().collect();
746 /// let v: Vec<_> = set.into_iter().collect();
747 /// assert_eq!(v, [1, 2, 3, 4]);
749 fn into_iter(self) -> IntoIter<T> {
750 IntoIter { iter: self.map.into_iter() }
754 #[stable(feature = "rust1", since = "1.0.0")]
755 impl<'a, T> IntoIterator for &'a BTreeSet<T> {
757 type IntoIter = Iter<'a, T>;
759 fn into_iter(self) -> Iter<'a, T> {
764 #[stable(feature = "rust1", since = "1.0.0")]
765 impl<T: Ord> Extend<T> for BTreeSet<T> {
767 fn extend<Iter: IntoIterator<Item = T>>(&mut self, iter: Iter) {
774 #[stable(feature = "extend_ref", since = "1.2.0")]
775 impl<'a, T: 'a + Ord + Copy> Extend<&'a T> for BTreeSet<T> {
776 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
777 self.extend(iter.into_iter().cloned());
781 #[stable(feature = "rust1", since = "1.0.0")]
782 impl<T: Ord> Default for BTreeSet<T> {
783 /// Makes an empty `BTreeSet<T>` with a reasonable choice of B.
784 fn default() -> BTreeSet<T> {
789 #[stable(feature = "rust1", since = "1.0.0")]
790 impl<'a, 'b, T: Ord + Clone> Sub<&'b BTreeSet<T>> for &'a BTreeSet<T> {
791 type Output = BTreeSet<T>;
793 /// Returns the difference of `self` and `rhs` as a new `BTreeSet<T>`.
798 /// use std::collections::BTreeSet;
800 /// let a: BTreeSet<_> = vec![1, 2, 3].into_iter().collect();
801 /// let b: BTreeSet<_> = vec![3, 4, 5].into_iter().collect();
803 /// let result = &a - &b;
804 /// let result_vec: Vec<_> = result.into_iter().collect();
805 /// assert_eq!(result_vec, [1, 2]);
807 fn sub(self, rhs: &BTreeSet<T>) -> BTreeSet<T> {
808 self.difference(rhs).cloned().collect()
812 #[stable(feature = "rust1", since = "1.0.0")]
813 impl<'a, 'b, T: Ord + Clone> BitXor<&'b BTreeSet<T>> for &'a BTreeSet<T> {
814 type Output = BTreeSet<T>;
816 /// Returns the symmetric difference of `self` and `rhs` as a new `BTreeSet<T>`.
821 /// use std::collections::BTreeSet;
823 /// let a: BTreeSet<_> = vec![1, 2, 3].into_iter().collect();
824 /// let b: BTreeSet<_> = vec![2, 3, 4].into_iter().collect();
826 /// let result = &a ^ &b;
827 /// let result_vec: Vec<_> = result.into_iter().collect();
828 /// assert_eq!(result_vec, [1, 4]);
830 fn bitxor(self, rhs: &BTreeSet<T>) -> BTreeSet<T> {
831 self.symmetric_difference(rhs).cloned().collect()
835 #[stable(feature = "rust1", since = "1.0.0")]
836 impl<'a, 'b, T: Ord + Clone> BitAnd<&'b BTreeSet<T>> for &'a BTreeSet<T> {
837 type Output = BTreeSet<T>;
839 /// Returns the intersection of `self` and `rhs` as a new `BTreeSet<T>`.
844 /// use std::collections::BTreeSet;
846 /// let a: BTreeSet<_> = vec![1, 2, 3].into_iter().collect();
847 /// let b: BTreeSet<_> = vec![2, 3, 4].into_iter().collect();
849 /// let result = &a & &b;
850 /// let result_vec: Vec<_> = result.into_iter().collect();
851 /// assert_eq!(result_vec, [2, 3]);
853 fn bitand(self, rhs: &BTreeSet<T>) -> BTreeSet<T> {
854 self.intersection(rhs).cloned().collect()
858 #[stable(feature = "rust1", since = "1.0.0")]
859 impl<'a, 'b, T: Ord + Clone> BitOr<&'b BTreeSet<T>> for &'a BTreeSet<T> {
860 type Output = BTreeSet<T>;
862 /// Returns the union of `self` and `rhs` as a new `BTreeSet<T>`.
867 /// use std::collections::BTreeSet;
869 /// let a: BTreeSet<_> = vec![1, 2, 3].into_iter().collect();
870 /// let b: BTreeSet<_> = vec![3, 4, 5].into_iter().collect();
872 /// let result = &a | &b;
873 /// let result_vec: Vec<_> = result.into_iter().collect();
874 /// assert_eq!(result_vec, [1, 2, 3, 4, 5]);
876 fn bitor(self, rhs: &BTreeSet<T>) -> BTreeSet<T> {
877 self.union(rhs).cloned().collect()
881 #[stable(feature = "rust1", since = "1.0.0")]
882 impl<T: Debug> Debug for BTreeSet<T> {
883 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
884 f.debug_set().entries(self.iter()).finish()
888 #[stable(feature = "rust1", since = "1.0.0")]
889 impl<'a, T> Clone for Iter<'a, T> {
890 fn clone(&self) -> Iter<'a, T> {
891 Iter { iter: self.iter.clone() }
894 #[stable(feature = "rust1", since = "1.0.0")]
895 impl<'a, T> Iterator for Iter<'a, T> {
898 fn next(&mut self) -> Option<&'a T> {
901 fn size_hint(&self) -> (usize, Option<usize>) {
902 self.iter.size_hint()
905 #[stable(feature = "rust1", since = "1.0.0")]
906 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
907 fn next_back(&mut self) -> Option<&'a T> {
908 self.iter.next_back()
911 #[stable(feature = "rust1", since = "1.0.0")]
912 impl<'a, T> ExactSizeIterator for Iter<'a, T> {
913 fn len(&self) -> usize { self.iter.len() }
916 #[unstable(feature = "fused", issue = "35602")]
917 impl<'a, T> FusedIterator for Iter<'a, T> {}
919 #[stable(feature = "rust1", since = "1.0.0")]
920 impl<T> Iterator for IntoIter<T> {
923 fn next(&mut self) -> Option<T> {
924 self.iter.next().map(|(k, _)| k)
926 fn size_hint(&self) -> (usize, Option<usize>) {
927 self.iter.size_hint()
930 #[stable(feature = "rust1", since = "1.0.0")]
931 impl<T> DoubleEndedIterator for IntoIter<T> {
932 fn next_back(&mut self) -> Option<T> {
933 self.iter.next_back().map(|(k, _)| k)
936 #[stable(feature = "rust1", since = "1.0.0")]
937 impl<T> ExactSizeIterator for IntoIter<T> {
938 fn len(&self) -> usize { self.iter.len() }
941 #[unstable(feature = "fused", issue = "35602")]
942 impl<T> FusedIterator for IntoIter<T> {}
944 #[stable(feature = "btree_range", since = "1.17.0")]
945 impl<'a, T> Clone for Range<'a, T> {
946 fn clone(&self) -> Range<'a, T> {
947 Range { iter: self.iter.clone() }
951 #[stable(feature = "btree_range", since = "1.17.0")]
952 impl<'a, T> Iterator for Range<'a, T> {
955 fn next(&mut self) -> Option<&'a T> {
956 self.iter.next().map(|(k, _)| k)
960 #[stable(feature = "btree_range", since = "1.17.0")]
961 impl<'a, T> DoubleEndedIterator for Range<'a, T> {
962 fn next_back(&mut self) -> Option<&'a T> {
963 self.iter.next_back().map(|(k, _)| k)
967 #[unstable(feature = "fused", issue = "35602")]
968 impl<'a, T> FusedIterator for Range<'a, T> {}
970 /// Compare `x` and `y`, but return `short` if x is None and `long` if y is None
971 fn cmp_opt<T: Ord>(x: Option<&T>, y: Option<&T>, short: Ordering, long: Ordering) -> Ordering {
975 (Some(x1), Some(y1)) => x1.cmp(y1),
979 #[stable(feature = "rust1", since = "1.0.0")]
980 impl<'a, T> Clone for Difference<'a, T> {
981 fn clone(&self) -> Difference<'a, T> {
988 #[stable(feature = "rust1", since = "1.0.0")]
989 impl<'a, T: Ord> Iterator for Difference<'a, T> {
992 fn next(&mut self) -> Option<&'a T> {
994 match cmp_opt(self.a.peek(), self.b.peek(), Less, Less) {
995 Less => return self.a.next(),
1007 fn size_hint(&self) -> (usize, Option<usize>) {
1008 let a_len = self.a.len();
1009 let b_len = self.b.len();
1010 (a_len.saturating_sub(b_len), Some(a_len))
1014 #[unstable(feature = "fused", issue = "35602")]
1015 impl<'a, T: Ord> FusedIterator for Difference<'a, T> {}
1017 #[stable(feature = "rust1", since = "1.0.0")]
1018 impl<'a, T> Clone for SymmetricDifference<'a, T> {
1019 fn clone(&self) -> SymmetricDifference<'a, T> {
1020 SymmetricDifference {
1026 #[stable(feature = "rust1", since = "1.0.0")]
1027 impl<'a, T: Ord> Iterator for SymmetricDifference<'a, T> {
1030 fn next(&mut self) -> Option<&'a T> {
1032 match cmp_opt(self.a.peek(), self.b.peek(), Greater, Less) {
1033 Less => return self.a.next(),
1038 Greater => return self.b.next(),
1043 fn size_hint(&self) -> (usize, Option<usize>) {
1044 (0, Some(self.a.len() + self.b.len()))
1048 #[unstable(feature = "fused", issue = "35602")]
1049 impl<'a, T: Ord> FusedIterator for SymmetricDifference<'a, T> {}
1051 #[stable(feature = "rust1", since = "1.0.0")]
1052 impl<'a, T> Clone for Intersection<'a, T> {
1053 fn clone(&self) -> Intersection<'a, T> {
1060 #[stable(feature = "rust1", since = "1.0.0")]
1061 impl<'a, T: Ord> Iterator for Intersection<'a, T> {
1064 fn next(&mut self) -> Option<&'a T> {
1066 let o_cmp = match (self.a.peek(), self.b.peek()) {
1069 (Some(a1), Some(b1)) => Some(a1.cmp(b1)),
1072 None => return None,
1078 return self.a.next();
1087 fn size_hint(&self) -> (usize, Option<usize>) {
1088 (0, Some(min(self.a.len(), self.b.len())))
1092 #[unstable(feature = "fused", issue = "35602")]
1093 impl<'a, T: Ord> FusedIterator for Intersection<'a, T> {}
1095 #[stable(feature = "rust1", since = "1.0.0")]
1096 impl<'a, T> Clone for Union<'a, T> {
1097 fn clone(&self) -> Union<'a, T> {
1104 #[stable(feature = "rust1", since = "1.0.0")]
1105 impl<'a, T: Ord> Iterator for Union<'a, T> {
1108 fn next(&mut self) -> Option<&'a T> {
1110 match cmp_opt(self.a.peek(), self.b.peek(), Greater, Less) {
1111 Less => return self.a.next(),
1114 return self.a.next();
1116 Greater => return self.b.next(),
1121 fn size_hint(&self) -> (usize, Option<usize>) {
1122 let a_len = self.a.len();
1123 let b_len = self.b.len();
1124 (max(a_len, b_len), Some(a_len + b_len))
1128 #[unstable(feature = "fused", issue = "35602")]
1129 impl<'a, T: Ord> FusedIterator for Union<'a, T> {}