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`][`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")
147 /// A lazy iterator producing elements in the symmetric difference of `BTreeSet`s.
149 /// This `struct` is created by the [`symmetric_difference`] method on
150 /// [`BTreeSet`]. See its documentation for more.
152 /// [`BTreeSet`]: struct.BTreeSet.html
153 /// [`symmetric_difference`]: struct.BTreeSet.html#method.symmetric_difference
154 #[stable(feature = "rust1", since = "1.0.0")]
155 pub struct SymmetricDifference<'a, T: 'a> {
156 a: Peekable<Iter<'a, T>>,
157 b: Peekable<Iter<'a, T>>,
160 #[stable(feature = "collection_debug", since = "1.17.0")]
161 impl<'a, T: 'a + fmt::Debug> fmt::Debug for SymmetricDifference<'a, T> {
162 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
163 f.debug_tuple("SymmetricDifference")
170 /// A lazy iterator producing elements in the intersection of `BTreeSet`s.
172 /// This `struct` is created by the [`intersection`] method on [`BTreeSet`].
173 /// See its documentation for more.
175 /// [`BTreeSet`]: struct.BTreeSet.html
176 /// [`intersection`]: struct.BTreeSet.html#method.intersection
177 #[stable(feature = "rust1", since = "1.0.0")]
178 pub struct Intersection<'a, T: 'a> {
179 a: Peekable<Iter<'a, T>>,
180 b: Peekable<Iter<'a, T>>,
183 #[stable(feature = "collection_debug", since = "1.17.0")]
184 impl<'a, T: 'a + fmt::Debug> fmt::Debug for Intersection<'a, T> {
185 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
186 f.debug_tuple("Intersection")
193 /// A lazy iterator producing elements in the union of `BTreeSet`s.
195 /// This `struct` is created by the [`union`] method on [`BTreeSet`].
196 /// See its documentation for more.
198 /// [`BTreeSet`]: struct.BTreeSet.html
199 /// [`union`]: struct.BTreeSet.html#method.union
200 #[stable(feature = "rust1", since = "1.0.0")]
201 pub struct Union<'a, T: 'a> {
202 a: Peekable<Iter<'a, T>>,
203 b: Peekable<Iter<'a, T>>,
206 #[stable(feature = "collection_debug", since = "1.17.0")]
207 impl<'a, T: 'a + fmt::Debug> fmt::Debug for Union<'a, T> {
208 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
209 f.debug_tuple("Union")
216 impl<T: Ord> BTreeSet<T> {
217 /// Makes a new `BTreeSet` with a reasonable choice of B.
222 /// # #![allow(unused_mut)]
223 /// use std::collections::BTreeSet;
225 /// let mut set: BTreeSet<i32> = BTreeSet::new();
227 #[stable(feature = "rust1", since = "1.0.0")]
228 pub fn new() -> BTreeSet<T> {
229 BTreeSet { map: BTreeMap::new() }
232 /// Constructs a double-ended iterator over a sub-range of elements in the set.
233 /// The simplest way is to use the range syntax `min..max`, thus `range(min..max)` will
234 /// yield elements from min (inclusive) to max (exclusive).
235 /// The range may also be entered as `(Bound<T>, Bound<T>)`, so for example
236 /// `range((Excluded(4), Included(10)))` will yield a left-exclusive, right-inclusive
237 /// range from 4 to 10.
242 /// use std::collections::BTreeSet;
243 /// use std::collections::Bound::Included;
245 /// let mut set = BTreeSet::new();
249 /// for &elem in set.range((Included(&4), Included(&8))) {
250 /// println!("{}", elem);
252 /// assert_eq!(Some(&5), set.range(4..).next());
254 #[stable(feature = "btree_range", since = "1.17.0")]
255 pub fn range<K: ?Sized, R>(&self, range: R) -> Range<T>
256 where K: Ord, T: Borrow<K>, R: RangeArgument<K>
258 Range { iter: self.map.range(range) }
261 /// Visits the values representing the difference,
262 /// i.e. the values that are in `self` but not in `other`,
263 /// in ascending order.
268 /// use std::collections::BTreeSet;
270 /// let mut a = BTreeSet::new();
274 /// let mut b = BTreeSet::new();
278 /// let diff: Vec<_> = a.difference(&b).cloned().collect();
279 /// assert_eq!(diff, [1]);
281 #[stable(feature = "rust1", since = "1.0.0")]
282 pub fn difference<'a>(&'a self, other: &'a BTreeSet<T>) -> Difference<'a, T> {
284 a: self.iter().peekable(),
285 b: other.iter().peekable(),
289 /// Visits the values representing the symmetric difference,
290 /// i.e. the values that are in `self` or in `other` but not in both,
291 /// in ascending order.
296 /// use std::collections::BTreeSet;
298 /// let mut a = BTreeSet::new();
302 /// let mut b = BTreeSet::new();
306 /// let sym_diff: Vec<_> = a.symmetric_difference(&b).cloned().collect();
307 /// assert_eq!(sym_diff, [1, 3]);
309 #[stable(feature = "rust1", since = "1.0.0")]
310 pub fn symmetric_difference<'a>(&'a self,
311 other: &'a BTreeSet<T>)
312 -> SymmetricDifference<'a, T> {
313 SymmetricDifference {
314 a: self.iter().peekable(),
315 b: other.iter().peekable(),
319 /// Visits the values representing the intersection,
320 /// i.e. the values that are both in `self` and `other`,
321 /// in ascending order.
326 /// use std::collections::BTreeSet;
328 /// let mut a = BTreeSet::new();
332 /// let mut b = BTreeSet::new();
336 /// let intersection: Vec<_> = a.intersection(&b).cloned().collect();
337 /// assert_eq!(intersection, [2]);
339 #[stable(feature = "rust1", since = "1.0.0")]
340 pub fn intersection<'a>(&'a self, other: &'a BTreeSet<T>) -> Intersection<'a, T> {
342 a: self.iter().peekable(),
343 b: other.iter().peekable(),
347 /// Visits the values representing the union,
348 /// i.e. all the values in `self` or `other`, without duplicates,
349 /// in ascending order.
354 /// use std::collections::BTreeSet;
356 /// let mut a = BTreeSet::new();
359 /// let mut b = BTreeSet::new();
362 /// let union: Vec<_> = a.union(&b).cloned().collect();
363 /// assert_eq!(union, [1, 2]);
365 #[stable(feature = "rust1", since = "1.0.0")]
366 pub fn union<'a>(&'a self, other: &'a BTreeSet<T>) -> Union<'a, T> {
368 a: self.iter().peekable(),
369 b: other.iter().peekable(),
373 /// Clears the set, removing all values.
378 /// use std::collections::BTreeSet;
380 /// let mut v = BTreeSet::new();
383 /// assert!(v.is_empty());
385 #[stable(feature = "rust1", since = "1.0.0")]
386 pub fn clear(&mut self) {
390 /// Returns `true` if the set contains a value.
392 /// The value may be any borrowed form of the set's value type,
393 /// but the ordering on the borrowed form *must* match the
394 /// ordering on the value type.
399 /// use std::collections::BTreeSet;
401 /// let set: BTreeSet<_> = [1, 2, 3].iter().cloned().collect();
402 /// assert_eq!(set.contains(&1), true);
403 /// assert_eq!(set.contains(&4), false);
405 #[stable(feature = "rust1", since = "1.0.0")]
406 pub fn contains<Q: ?Sized>(&self, value: &Q) -> bool
410 self.map.contains_key(value)
413 /// Returns a reference to the value in the set, if any, that is equal to the given value.
415 /// The value may be any borrowed form of the set's value type,
416 /// but the ordering on the borrowed form *must* match the
417 /// ordering on the value type.
418 #[stable(feature = "set_recovery", since = "1.9.0")]
419 pub fn get<Q: ?Sized>(&self, value: &Q) -> Option<&T>
423 Recover::get(&self.map, value)
426 /// Returns `true` if `self` has no elements in common with `other`.
427 /// This is equivalent to checking for an empty intersection.
432 /// use std::collections::BTreeSet;
434 /// let a: BTreeSet<_> = [1, 2, 3].iter().cloned().collect();
435 /// let mut b = BTreeSet::new();
437 /// assert_eq!(a.is_disjoint(&b), true);
439 /// assert_eq!(a.is_disjoint(&b), true);
441 /// assert_eq!(a.is_disjoint(&b), false);
443 #[stable(feature = "rust1", since = "1.0.0")]
444 pub fn is_disjoint(&self, other: &BTreeSet<T>) -> bool {
445 self.intersection(other).next().is_none()
448 /// Returns `true` if the set is a subset of another,
449 /// i.e. `other` contains at least all the values in `self`.
454 /// use std::collections::BTreeSet;
456 /// let sup: BTreeSet<_> = [1, 2, 3].iter().cloned().collect();
457 /// let mut set = BTreeSet::new();
459 /// assert_eq!(set.is_subset(&sup), true);
461 /// assert_eq!(set.is_subset(&sup), true);
463 /// assert_eq!(set.is_subset(&sup), false);
465 #[stable(feature = "rust1", since = "1.0.0")]
466 pub fn is_subset(&self, other: &BTreeSet<T>) -> bool {
467 // Stolen from TreeMap
468 let mut x = self.iter();
469 let mut y = other.iter();
470 let mut a = x.next();
471 let mut b = y.next();
482 Greater => return false,
483 Equal => a = x.next(),
491 /// Returns `true` if the set is a superset of another,
492 /// i.e. `self` contains at least all the values in `other`.
497 /// use std::collections::BTreeSet;
499 /// let sub: BTreeSet<_> = [1, 2].iter().cloned().collect();
500 /// let mut set = BTreeSet::new();
502 /// assert_eq!(set.is_superset(&sub), false);
506 /// assert_eq!(set.is_superset(&sub), false);
509 /// assert_eq!(set.is_superset(&sub), true);
511 #[stable(feature = "rust1", since = "1.0.0")]
512 pub fn is_superset(&self, other: &BTreeSet<T>) -> bool {
513 other.is_subset(self)
516 /// Adds a value to the set.
518 /// If the set did not have this value present, `true` is returned.
520 /// If the set did have this value present, `false` is returned, and the
521 /// entry is not updated. See the [module-level documentation] for more.
523 /// [module-level documentation]: index.html#insert-and-complex-keys
528 /// use std::collections::BTreeSet;
530 /// let mut set = BTreeSet::new();
532 /// assert_eq!(set.insert(2), true);
533 /// assert_eq!(set.insert(2), false);
534 /// assert_eq!(set.len(), 1);
536 #[stable(feature = "rust1", since = "1.0.0")]
537 pub fn insert(&mut self, value: T) -> bool {
538 self.map.insert(value, ()).is_none()
541 /// Adds a value to the set, replacing the existing value, if any, that is equal to the given
542 /// one. Returns the replaced value.
543 #[stable(feature = "set_recovery", since = "1.9.0")]
544 pub fn replace(&mut self, value: T) -> Option<T> {
545 Recover::replace(&mut self.map, value)
548 /// Removes a value from the set. Returns `true` if the value was
549 /// present in the set.
551 /// The value may be any borrowed form of the set's value type,
552 /// but the ordering on the borrowed form *must* match the
553 /// ordering on the value type.
558 /// use std::collections::BTreeSet;
560 /// let mut set = BTreeSet::new();
563 /// assert_eq!(set.remove(&2), true);
564 /// assert_eq!(set.remove(&2), false);
566 #[stable(feature = "rust1", since = "1.0.0")]
567 pub fn remove<Q: ?Sized>(&mut self, value: &Q) -> bool
571 self.map.remove(value).is_some()
574 /// Removes and returns the value in the set, if any, that is equal to the given one.
576 /// The value may be any borrowed form of the set's value type,
577 /// but the ordering on the borrowed form *must* match the
578 /// ordering on the value type.
579 #[stable(feature = "set_recovery", since = "1.9.0")]
580 pub fn take<Q: ?Sized>(&mut self, value: &Q) -> Option<T>
584 Recover::take(&mut self.map, value)
587 /// Moves all elements from `other` into `Self`, leaving `other` empty.
592 /// use std::collections::BTreeSet;
594 /// let mut a = BTreeSet::new();
599 /// let mut b = BTreeSet::new();
604 /// a.append(&mut b);
606 /// assert_eq!(a.len(), 5);
607 /// assert_eq!(b.len(), 0);
609 /// assert!(a.contains(&1));
610 /// assert!(a.contains(&2));
611 /// assert!(a.contains(&3));
612 /// assert!(a.contains(&4));
613 /// assert!(a.contains(&5));
615 #[stable(feature = "btree_append", since = "1.11.0")]
616 pub fn append(&mut self, other: &mut Self) {
617 self.map.append(&mut other.map);
620 /// Splits the collection into two at the given key. Returns everything after the given key,
621 /// including the key.
628 /// use std::collections::BTreeMap;
630 /// let mut a = BTreeMap::new();
631 /// a.insert(1, "a");
632 /// a.insert(2, "b");
633 /// a.insert(3, "c");
634 /// a.insert(17, "d");
635 /// a.insert(41, "e");
637 /// let b = a.split_off(&3);
639 /// assert_eq!(a.len(), 2);
640 /// assert_eq!(b.len(), 3);
642 /// assert_eq!(a[&1], "a");
643 /// assert_eq!(a[&2], "b");
645 /// assert_eq!(b[&3], "c");
646 /// assert_eq!(b[&17], "d");
647 /// assert_eq!(b[&41], "e");
649 #[stable(feature = "btree_split_off", since = "1.11.0")]
650 pub fn split_off<Q: ?Sized + Ord>(&mut self, key: &Q) -> Self where T: Borrow<Q> {
651 BTreeSet { map: self.map.split_off(key) }
655 impl<T> BTreeSet<T> {
656 /// Gets an iterator that visits the values in the `BTreeSet` in ascending order.
661 /// use std::collections::BTreeSet;
663 /// let set: BTreeSet<usize> = [1, 2, 3].iter().cloned().collect();
664 /// let mut set_iter = set.iter();
665 /// assert_eq!(set_iter.next(), Some(&1));
666 /// assert_eq!(set_iter.next(), Some(&2));
667 /// assert_eq!(set_iter.next(), Some(&3));
668 /// assert_eq!(set_iter.next(), None);
671 /// Values returned by the iterator are returned in ascending order:
674 /// use std::collections::BTreeSet;
676 /// let set: BTreeSet<usize> = [3, 1, 2].iter().cloned().collect();
677 /// let mut set_iter = set.iter();
678 /// assert_eq!(set_iter.next(), Some(&1));
679 /// assert_eq!(set_iter.next(), Some(&2));
680 /// assert_eq!(set_iter.next(), Some(&3));
681 /// assert_eq!(set_iter.next(), None);
683 #[stable(feature = "rust1", since = "1.0.0")]
684 pub fn iter(&self) -> Iter<T> {
685 Iter { iter: self.map.keys() }
688 /// Returns the number of elements in the set.
693 /// use std::collections::BTreeSet;
695 /// let mut v = BTreeSet::new();
696 /// assert_eq!(v.len(), 0);
698 /// assert_eq!(v.len(), 1);
700 #[stable(feature = "rust1", since = "1.0.0")]
701 pub fn len(&self) -> usize {
705 /// Returns `true` if the set contains no elements.
710 /// use std::collections::BTreeSet;
712 /// let mut v = BTreeSet::new();
713 /// assert!(v.is_empty());
715 /// assert!(!v.is_empty());
717 #[stable(feature = "rust1", since = "1.0.0")]
718 pub fn is_empty(&self) -> bool {
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 match Ord::cmp(self.a.peek()?, self.b.peek()?) {
1072 return self.a.next();
1081 fn size_hint(&self) -> (usize, Option<usize>) {
1082 (0, Some(min(self.a.len(), self.b.len())))
1086 #[unstable(feature = "fused", issue = "35602")]
1087 impl<'a, T: Ord> FusedIterator for Intersection<'a, T> {}
1089 #[stable(feature = "rust1", since = "1.0.0")]
1090 impl<'a, T> Clone for Union<'a, T> {
1091 fn clone(&self) -> Union<'a, T> {
1098 #[stable(feature = "rust1", since = "1.0.0")]
1099 impl<'a, T: Ord> Iterator for Union<'a, T> {
1102 fn next(&mut self) -> Option<&'a T> {
1103 match cmp_opt(self.a.peek(), self.b.peek(), Greater, Less) {
1104 Less => self.a.next(),
1109 Greater => self.b.next(),
1113 fn size_hint(&self) -> (usize, Option<usize>) {
1114 let a_len = self.a.len();
1115 let b_len = self.b.len();
1116 (max(a_len, b_len), Some(a_len + b_len))
1120 #[unstable(feature = "fused", issue = "35602")]
1121 impl<'a, T: Ord> FusedIterator for Union<'a, T> {}