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.
422 /// use std::collections::BTreeSet;
424 /// let set: BTreeSet<_> = [1, 2, 3].iter().cloned().collect();
425 /// assert_eq!(set.get(&2), Some(&2));
426 /// assert_eq!(set.get(&4), None);
428 #[stable(feature = "set_recovery", since = "1.9.0")]
429 pub fn get<Q: ?Sized>(&self, value: &Q) -> Option<&T>
433 Recover::get(&self.map, value)
436 /// Returns `true` if `self` has no elements in common with `other`.
437 /// This is equivalent to checking for an empty intersection.
442 /// use std::collections::BTreeSet;
444 /// let a: BTreeSet<_> = [1, 2, 3].iter().cloned().collect();
445 /// let mut b = BTreeSet::new();
447 /// assert_eq!(a.is_disjoint(&b), true);
449 /// assert_eq!(a.is_disjoint(&b), true);
451 /// assert_eq!(a.is_disjoint(&b), false);
453 #[stable(feature = "rust1", since = "1.0.0")]
454 pub fn is_disjoint(&self, other: &BTreeSet<T>) -> bool {
455 self.intersection(other).next().is_none()
458 /// Returns `true` if the set is a subset of another,
459 /// i.e. `other` contains at least all the values in `self`.
464 /// use std::collections::BTreeSet;
466 /// let sup: BTreeSet<_> = [1, 2, 3].iter().cloned().collect();
467 /// let mut set = BTreeSet::new();
469 /// assert_eq!(set.is_subset(&sup), true);
471 /// assert_eq!(set.is_subset(&sup), true);
473 /// assert_eq!(set.is_subset(&sup), false);
475 #[stable(feature = "rust1", since = "1.0.0")]
476 pub fn is_subset(&self, other: &BTreeSet<T>) -> bool {
477 // Stolen from TreeMap
478 let mut x = self.iter();
479 let mut y = other.iter();
480 let mut a = x.next();
481 let mut b = y.next();
492 Greater => return false,
493 Equal => a = x.next(),
501 /// Returns `true` if the set is a superset of another,
502 /// i.e. `self` contains at least all the values in `other`.
507 /// use std::collections::BTreeSet;
509 /// let sub: BTreeSet<_> = [1, 2].iter().cloned().collect();
510 /// let mut set = BTreeSet::new();
512 /// assert_eq!(set.is_superset(&sub), false);
516 /// assert_eq!(set.is_superset(&sub), false);
519 /// assert_eq!(set.is_superset(&sub), true);
521 #[stable(feature = "rust1", since = "1.0.0")]
522 pub fn is_superset(&self, other: &BTreeSet<T>) -> bool {
523 other.is_subset(self)
526 /// Adds a value to the set.
528 /// If the set did not have this value present, `true` is returned.
530 /// If the set did have this value present, `false` is returned, and the
531 /// entry is not updated. See the [module-level documentation] for more.
533 /// [module-level documentation]: index.html#insert-and-complex-keys
538 /// use std::collections::BTreeSet;
540 /// let mut set = BTreeSet::new();
542 /// assert_eq!(set.insert(2), true);
543 /// assert_eq!(set.insert(2), false);
544 /// assert_eq!(set.len(), 1);
546 #[stable(feature = "rust1", since = "1.0.0")]
547 pub fn insert(&mut self, value: T) -> bool {
548 self.map.insert(value, ()).is_none()
551 /// Adds a value to the set, replacing the existing value, if any, that is equal to the given
552 /// one. Returns the replaced value.
557 /// use std::collections::BTreeSet;
559 /// let mut set = BTreeSet::new();
560 /// set.insert(Vec::<i32>::new());
562 /// assert_eq!(set.get(&[][..]).unwrap().capacity(), 0);
563 /// set.replace(Vec::with_capacity(10));
564 /// assert_eq!(set.get(&[][..]).unwrap().capacity(), 10);
566 #[stable(feature = "set_recovery", since = "1.9.0")]
567 pub fn replace(&mut self, value: T) -> Option<T> {
568 Recover::replace(&mut self.map, value)
571 /// Removes a value from the set. Returns `true` if the value was
572 /// present in the set.
574 /// The value may be any borrowed form of the set's value type,
575 /// but the ordering on the borrowed form *must* match the
576 /// ordering on the value type.
581 /// use std::collections::BTreeSet;
583 /// let mut set = BTreeSet::new();
586 /// assert_eq!(set.remove(&2), true);
587 /// assert_eq!(set.remove(&2), false);
589 #[stable(feature = "rust1", since = "1.0.0")]
590 pub fn remove<Q: ?Sized>(&mut self, value: &Q) -> bool
594 self.map.remove(value).is_some()
597 /// Removes and returns the value in the set, if any, that is equal to the given one.
599 /// The value may be any borrowed form of the set's value type,
600 /// but the ordering on the borrowed form *must* match the
601 /// ordering on the value type.
606 /// use std::collections::BTreeSet;
608 /// let mut set: BTreeSet<_> = [1, 2, 3].iter().cloned().collect();
609 /// assert_eq!(set.take(&2), Some(2));
610 /// assert_eq!(set.take(&2), None);
612 #[stable(feature = "set_recovery", since = "1.9.0")]
613 pub fn take<Q: ?Sized>(&mut self, value: &Q) -> Option<T>
617 Recover::take(&mut self.map, value)
620 /// Moves all elements from `other` into `Self`, leaving `other` empty.
625 /// use std::collections::BTreeSet;
627 /// let mut a = BTreeSet::new();
632 /// let mut b = BTreeSet::new();
637 /// a.append(&mut b);
639 /// assert_eq!(a.len(), 5);
640 /// assert_eq!(b.len(), 0);
642 /// assert!(a.contains(&1));
643 /// assert!(a.contains(&2));
644 /// assert!(a.contains(&3));
645 /// assert!(a.contains(&4));
646 /// assert!(a.contains(&5));
648 #[stable(feature = "btree_append", since = "1.11.0")]
649 pub fn append(&mut self, other: &mut Self) {
650 self.map.append(&mut other.map);
653 /// Splits the collection into two at the given key. Returns everything after the given key,
654 /// including the key.
661 /// use std::collections::BTreeMap;
663 /// let mut a = BTreeMap::new();
664 /// a.insert(1, "a");
665 /// a.insert(2, "b");
666 /// a.insert(3, "c");
667 /// a.insert(17, "d");
668 /// a.insert(41, "e");
670 /// let b = a.split_off(&3);
672 /// assert_eq!(a.len(), 2);
673 /// assert_eq!(b.len(), 3);
675 /// assert_eq!(a[&1], "a");
676 /// assert_eq!(a[&2], "b");
678 /// assert_eq!(b[&3], "c");
679 /// assert_eq!(b[&17], "d");
680 /// assert_eq!(b[&41], "e");
682 #[stable(feature = "btree_split_off", since = "1.11.0")]
683 pub fn split_off<Q: ?Sized + Ord>(&mut self, key: &Q) -> Self where T: Borrow<Q> {
684 BTreeSet { map: self.map.split_off(key) }
688 impl<T> BTreeSet<T> {
689 /// Gets an iterator that visits the values in the `BTreeSet` in ascending order.
694 /// use std::collections::BTreeSet;
696 /// let set: BTreeSet<usize> = [1, 2, 3].iter().cloned().collect();
697 /// let mut set_iter = set.iter();
698 /// assert_eq!(set_iter.next(), Some(&1));
699 /// assert_eq!(set_iter.next(), Some(&2));
700 /// assert_eq!(set_iter.next(), Some(&3));
701 /// assert_eq!(set_iter.next(), None);
704 /// Values returned by the iterator are returned in ascending order:
707 /// use std::collections::BTreeSet;
709 /// let set: BTreeSet<usize> = [3, 1, 2].iter().cloned().collect();
710 /// let mut set_iter = set.iter();
711 /// assert_eq!(set_iter.next(), Some(&1));
712 /// assert_eq!(set_iter.next(), Some(&2));
713 /// assert_eq!(set_iter.next(), Some(&3));
714 /// assert_eq!(set_iter.next(), None);
716 #[stable(feature = "rust1", since = "1.0.0")]
717 pub fn iter(&self) -> Iter<T> {
718 Iter { iter: self.map.keys() }
721 /// Returns the number of elements in the set.
726 /// use std::collections::BTreeSet;
728 /// let mut v = BTreeSet::new();
729 /// assert_eq!(v.len(), 0);
731 /// assert_eq!(v.len(), 1);
733 #[stable(feature = "rust1", since = "1.0.0")]
734 pub fn len(&self) -> usize {
738 /// Returns `true` if the set contains no elements.
743 /// use std::collections::BTreeSet;
745 /// let mut v = BTreeSet::new();
746 /// assert!(v.is_empty());
748 /// assert!(!v.is_empty());
750 #[stable(feature = "rust1", since = "1.0.0")]
751 pub fn is_empty(&self) -> bool {
756 #[stable(feature = "rust1", since = "1.0.0")]
757 impl<T: Ord> FromIterator<T> for BTreeSet<T> {
758 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> BTreeSet<T> {
759 let mut set = BTreeSet::new();
765 #[stable(feature = "rust1", since = "1.0.0")]
766 impl<T> IntoIterator for BTreeSet<T> {
768 type IntoIter = IntoIter<T>;
770 /// Gets an iterator for moving out the `BTreeSet`'s contents.
775 /// use std::collections::BTreeSet;
777 /// let set: BTreeSet<usize> = [1, 2, 3, 4].iter().cloned().collect();
779 /// let v: Vec<_> = set.into_iter().collect();
780 /// assert_eq!(v, [1, 2, 3, 4]);
782 fn into_iter(self) -> IntoIter<T> {
783 IntoIter { iter: self.map.into_iter() }
787 #[stable(feature = "rust1", since = "1.0.0")]
788 impl<'a, T> IntoIterator for &'a BTreeSet<T> {
790 type IntoIter = Iter<'a, T>;
792 fn into_iter(self) -> Iter<'a, T> {
797 #[stable(feature = "rust1", since = "1.0.0")]
798 impl<T: Ord> Extend<T> for BTreeSet<T> {
800 fn extend<Iter: IntoIterator<Item = T>>(&mut self, iter: Iter) {
807 #[stable(feature = "extend_ref", since = "1.2.0")]
808 impl<'a, T: 'a + Ord + Copy> Extend<&'a T> for BTreeSet<T> {
809 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
810 self.extend(iter.into_iter().cloned());
814 #[stable(feature = "rust1", since = "1.0.0")]
815 impl<T: Ord> Default for BTreeSet<T> {
816 /// Makes an empty `BTreeSet<T>` with a reasonable choice of B.
817 fn default() -> BTreeSet<T> {
822 #[stable(feature = "rust1", since = "1.0.0")]
823 impl<'a, 'b, T: Ord + Clone> Sub<&'b BTreeSet<T>> for &'a BTreeSet<T> {
824 type Output = BTreeSet<T>;
826 /// Returns the difference of `self` and `rhs` as a new `BTreeSet<T>`.
831 /// use std::collections::BTreeSet;
833 /// let a: BTreeSet<_> = vec![1, 2, 3].into_iter().collect();
834 /// let b: BTreeSet<_> = vec![3, 4, 5].into_iter().collect();
836 /// let result = &a - &b;
837 /// let result_vec: Vec<_> = result.into_iter().collect();
838 /// assert_eq!(result_vec, [1, 2]);
840 fn sub(self, rhs: &BTreeSet<T>) -> BTreeSet<T> {
841 self.difference(rhs).cloned().collect()
845 #[stable(feature = "rust1", since = "1.0.0")]
846 impl<'a, 'b, T: Ord + Clone> BitXor<&'b BTreeSet<T>> for &'a BTreeSet<T> {
847 type Output = BTreeSet<T>;
849 /// Returns the symmetric difference of `self` and `rhs` as a new `BTreeSet<T>`.
854 /// use std::collections::BTreeSet;
856 /// let a: BTreeSet<_> = vec![1, 2, 3].into_iter().collect();
857 /// let b: BTreeSet<_> = vec![2, 3, 4].into_iter().collect();
859 /// let result = &a ^ &b;
860 /// let result_vec: Vec<_> = result.into_iter().collect();
861 /// assert_eq!(result_vec, [1, 4]);
863 fn bitxor(self, rhs: &BTreeSet<T>) -> BTreeSet<T> {
864 self.symmetric_difference(rhs).cloned().collect()
868 #[stable(feature = "rust1", since = "1.0.0")]
869 impl<'a, 'b, T: Ord + Clone> BitAnd<&'b BTreeSet<T>> for &'a BTreeSet<T> {
870 type Output = BTreeSet<T>;
872 /// Returns the intersection of `self` and `rhs` as a new `BTreeSet<T>`.
877 /// use std::collections::BTreeSet;
879 /// let a: BTreeSet<_> = vec![1, 2, 3].into_iter().collect();
880 /// let b: BTreeSet<_> = vec![2, 3, 4].into_iter().collect();
882 /// let result = &a & &b;
883 /// let result_vec: Vec<_> = result.into_iter().collect();
884 /// assert_eq!(result_vec, [2, 3]);
886 fn bitand(self, rhs: &BTreeSet<T>) -> BTreeSet<T> {
887 self.intersection(rhs).cloned().collect()
891 #[stable(feature = "rust1", since = "1.0.0")]
892 impl<'a, 'b, T: Ord + Clone> BitOr<&'b BTreeSet<T>> for &'a BTreeSet<T> {
893 type Output = BTreeSet<T>;
895 /// Returns the union of `self` and `rhs` as a new `BTreeSet<T>`.
900 /// use std::collections::BTreeSet;
902 /// let a: BTreeSet<_> = vec![1, 2, 3].into_iter().collect();
903 /// let b: BTreeSet<_> = vec![3, 4, 5].into_iter().collect();
905 /// let result = &a | &b;
906 /// let result_vec: Vec<_> = result.into_iter().collect();
907 /// assert_eq!(result_vec, [1, 2, 3, 4, 5]);
909 fn bitor(self, rhs: &BTreeSet<T>) -> BTreeSet<T> {
910 self.union(rhs).cloned().collect()
914 #[stable(feature = "rust1", since = "1.0.0")]
915 impl<T: Debug> Debug for BTreeSet<T> {
916 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
917 f.debug_set().entries(self.iter()).finish()
921 #[stable(feature = "rust1", since = "1.0.0")]
922 impl<'a, T> Clone for Iter<'a, T> {
923 fn clone(&self) -> Iter<'a, T> {
924 Iter { iter: self.iter.clone() }
927 #[stable(feature = "rust1", since = "1.0.0")]
928 impl<'a, T> Iterator for Iter<'a, T> {
931 fn next(&mut self) -> Option<&'a T> {
934 fn size_hint(&self) -> (usize, Option<usize>) {
935 self.iter.size_hint()
938 #[stable(feature = "rust1", since = "1.0.0")]
939 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
940 fn next_back(&mut self) -> Option<&'a T> {
941 self.iter.next_back()
944 #[stable(feature = "rust1", since = "1.0.0")]
945 impl<'a, T> ExactSizeIterator for Iter<'a, T> {
946 fn len(&self) -> usize { self.iter.len() }
949 #[unstable(feature = "fused", issue = "35602")]
950 impl<'a, T> FusedIterator for Iter<'a, T> {}
952 #[stable(feature = "rust1", since = "1.0.0")]
953 impl<T> Iterator for IntoIter<T> {
956 fn next(&mut self) -> Option<T> {
957 self.iter.next().map(|(k, _)| k)
959 fn size_hint(&self) -> (usize, Option<usize>) {
960 self.iter.size_hint()
963 #[stable(feature = "rust1", since = "1.0.0")]
964 impl<T> DoubleEndedIterator for IntoIter<T> {
965 fn next_back(&mut self) -> Option<T> {
966 self.iter.next_back().map(|(k, _)| k)
969 #[stable(feature = "rust1", since = "1.0.0")]
970 impl<T> ExactSizeIterator for IntoIter<T> {
971 fn len(&self) -> usize { self.iter.len() }
974 #[unstable(feature = "fused", issue = "35602")]
975 impl<T> FusedIterator for IntoIter<T> {}
977 #[stable(feature = "btree_range", since = "1.17.0")]
978 impl<'a, T> Clone for Range<'a, T> {
979 fn clone(&self) -> Range<'a, T> {
980 Range { iter: self.iter.clone() }
984 #[stable(feature = "btree_range", since = "1.17.0")]
985 impl<'a, T> Iterator for Range<'a, T> {
988 fn next(&mut self) -> Option<&'a T> {
989 self.iter.next().map(|(k, _)| k)
993 #[stable(feature = "btree_range", since = "1.17.0")]
994 impl<'a, T> DoubleEndedIterator for Range<'a, T> {
995 fn next_back(&mut self) -> Option<&'a T> {
996 self.iter.next_back().map(|(k, _)| k)
1000 #[unstable(feature = "fused", issue = "35602")]
1001 impl<'a, T> FusedIterator for Range<'a, T> {}
1003 /// Compare `x` and `y`, but return `short` if x is None and `long` if y is None
1004 fn cmp_opt<T: Ord>(x: Option<&T>, y: Option<&T>, short: Ordering, long: Ordering) -> Ordering {
1008 (Some(x1), Some(y1)) => x1.cmp(y1),
1012 #[stable(feature = "rust1", since = "1.0.0")]
1013 impl<'a, T> Clone for Difference<'a, T> {
1014 fn clone(&self) -> Difference<'a, T> {
1021 #[stable(feature = "rust1", since = "1.0.0")]
1022 impl<'a, T: Ord> Iterator for Difference<'a, T> {
1025 fn next(&mut self) -> Option<&'a T> {
1027 match cmp_opt(self.a.peek(), self.b.peek(), Less, Less) {
1028 Less => return self.a.next(),
1040 fn size_hint(&self) -> (usize, Option<usize>) {
1041 let a_len = self.a.len();
1042 let b_len = self.b.len();
1043 (a_len.saturating_sub(b_len), Some(a_len))
1047 #[unstable(feature = "fused", issue = "35602")]
1048 impl<'a, T: Ord> FusedIterator for Difference<'a, T> {}
1050 #[stable(feature = "rust1", since = "1.0.0")]
1051 impl<'a, T> Clone for SymmetricDifference<'a, T> {
1052 fn clone(&self) -> SymmetricDifference<'a, T> {
1053 SymmetricDifference {
1059 #[stable(feature = "rust1", since = "1.0.0")]
1060 impl<'a, T: Ord> Iterator for SymmetricDifference<'a, T> {
1063 fn next(&mut self) -> Option<&'a T> {
1065 match cmp_opt(self.a.peek(), self.b.peek(), Greater, Less) {
1066 Less => return self.a.next(),
1071 Greater => return self.b.next(),
1076 fn size_hint(&self) -> (usize, Option<usize>) {
1077 (0, Some(self.a.len() + self.b.len()))
1081 #[unstable(feature = "fused", issue = "35602")]
1082 impl<'a, T: Ord> FusedIterator for SymmetricDifference<'a, T> {}
1084 #[stable(feature = "rust1", since = "1.0.0")]
1085 impl<'a, T> Clone for Intersection<'a, T> {
1086 fn clone(&self) -> Intersection<'a, T> {
1093 #[stable(feature = "rust1", since = "1.0.0")]
1094 impl<'a, T: Ord> Iterator for Intersection<'a, T> {
1097 fn next(&mut self) -> Option<&'a T> {
1099 match Ord::cmp(self.a.peek()?, self.b.peek()?) {
1105 return self.a.next();
1114 fn size_hint(&self) -> (usize, Option<usize>) {
1115 (0, Some(min(self.a.len(), self.b.len())))
1119 #[unstable(feature = "fused", issue = "35602")]
1120 impl<'a, T: Ord> FusedIterator for Intersection<'a, T> {}
1122 #[stable(feature = "rust1", since = "1.0.0")]
1123 impl<'a, T> Clone for Union<'a, T> {
1124 fn clone(&self) -> Union<'a, T> {
1131 #[stable(feature = "rust1", since = "1.0.0")]
1132 impl<'a, T: Ord> Iterator for Union<'a, T> {
1135 fn next(&mut self) -> Option<&'a T> {
1136 match cmp_opt(self.a.peek(), self.b.peek(), Greater, Less) {
1137 Less => self.a.next(),
1142 Greater => self.b.next(),
1146 fn size_hint(&self) -> (usize, Option<usize>) {
1147 let a_len = self.a.len();
1148 let b_len = self.b.len();
1149 (max(a_len, b_len), Some(a_len + b_len))
1153 #[unstable(feature = "fused", issue = "35602")]
1154 impl<'a, T: Ord> FusedIterator for Union<'a, T> {}