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 a `BTreeSet`'s items.
79 /// This structure is created by the [`iter`] method on [`BTreeSet`].
81 /// [`BTreeSet`]: struct.BTreeSet.html
82 /// [`iter`]: struct.BTreeSet.html#method.iter
83 #[stable(feature = "rust1", since = "1.0.0")]
84 pub struct Iter<'a, T: 'a> {
85 iter: Keys<'a, T, ()>,
88 #[stable(feature = "collection_debug", since = "1.17.0")]
89 impl<'a, T: 'a + fmt::Debug> fmt::Debug for Iter<'a, T> {
90 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
92 .field(&self.iter.clone())
97 /// An owning iterator over a `BTreeSet`'s items.
99 /// This structure is created by the `into_iter` method on [`BTreeSet`]
100 /// [`BTreeSet`] (provided by the `IntoIterator` trait).
102 /// [`BTreeSet`]: struct.BTreeSet.html
103 #[stable(feature = "rust1", since = "1.0.0")]
105 pub struct IntoIter<T> {
106 iter: ::btree_map::IntoIter<T, ()>,
109 /// An iterator over a sub-range of `BTreeSet`'s items.
111 /// This structure is created by the [`range`] method on [`BTreeSet`].
113 /// [`BTreeSet`]: struct.BTreeSet.html
114 /// [`range`]: struct.BTreeSet.html#method.range
116 pub struct Range<'a, T: 'a> {
117 iter: ::btree_map::Range<'a, T, ()>,
120 /// A lazy iterator producing elements in the set difference (in-order).
122 /// This structure is created by the [`difference`] method on [`BTreeSet`].
124 /// [`BTreeSet`]: struct.BTreeSet.html
125 /// [`difference`]: struct.BTreeSet.html#method.difference
126 #[stable(feature = "rust1", since = "1.0.0")]
127 pub struct Difference<'a, T: 'a> {
128 a: Peekable<Iter<'a, T>>,
129 b: Peekable<Iter<'a, T>>,
132 #[stable(feature = "collection_debug", since = "1.17.0")]
133 impl<'a, T: 'a + fmt::Debug> fmt::Debug for Difference<'a, T> {
134 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
135 f.debug_tuple("Difference")
136 .field(&self.clone())
141 /// A lazy iterator producing elements in the set symmetric difference (in-order).
143 /// This structure is created by the [`symmetric_difference`] method on
146 /// [`BTreeSet`]: struct.BTreeSet.html
147 /// [`symmetric_difference`]: struct.BTreeSet.html#method.symmetric_difference
148 #[stable(feature = "rust1", since = "1.0.0")]
149 pub struct SymmetricDifference<'a, T: 'a> {
150 a: Peekable<Iter<'a, T>>,
151 b: Peekable<Iter<'a, T>>,
154 #[stable(feature = "collection_debug", since = "1.17.0")]
155 impl<'a, T: 'a + fmt::Debug> fmt::Debug for SymmetricDifference<'a, T> {
156 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
157 f.debug_tuple("SymmetricDifference")
158 .field(&self.clone())
163 /// A lazy iterator producing elements in the set intersection (in-order).
165 /// This structure is created by the [`intersection`] method on [`BTreeSet`].
167 /// [`BTreeSet`]: struct.BTreeSet.html
168 /// [`intersection`]: struct.BTreeSet.html#method.intersection
169 #[stable(feature = "rust1", since = "1.0.0")]
170 pub struct Intersection<'a, T: 'a> {
171 a: Peekable<Iter<'a, T>>,
172 b: Peekable<Iter<'a, T>>,
175 #[stable(feature = "collection_debug", since = "1.17.0")]
176 impl<'a, T: 'a + fmt::Debug> fmt::Debug for Intersection<'a, T> {
177 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
178 f.debug_tuple("Intersection")
179 .field(&self.clone())
184 /// A lazy iterator producing elements in the set union (in-order).
186 /// This structure is created by the [`union`] method on [`BTreeSet`].
188 /// [`BTreeSet`]: struct.BTreeSet.html
189 /// [`union`]: struct.BTreeSet.html#method.union
190 #[stable(feature = "rust1", since = "1.0.0")]
191 pub struct Union<'a, T: 'a> {
192 a: Peekable<Iter<'a, T>>,
193 b: Peekable<Iter<'a, T>>,
196 #[stable(feature = "collection_debug", since = "1.17.0")]
197 impl<'a, T: 'a + fmt::Debug> fmt::Debug for Union<'a, T> {
198 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
199 f.debug_tuple("Union")
200 .field(&self.clone())
205 impl<T: Ord> BTreeSet<T> {
206 /// Makes a new `BTreeSet` with a reasonable choice of B.
211 /// # #![allow(unused_mut)]
212 /// use std::collections::BTreeSet;
214 /// let mut set: BTreeSet<i32> = BTreeSet::new();
216 #[stable(feature = "rust1", since = "1.0.0")]
217 pub fn new() -> BTreeSet<T> {
218 BTreeSet { map: BTreeMap::new() }
222 impl<T> BTreeSet<T> {
223 /// Gets an iterator that visits the values in the `BTreeSet` in ascending order.
228 /// use std::collections::BTreeSet;
230 /// let set: BTreeSet<usize> = [1, 2, 3].iter().cloned().collect();
231 /// let mut set_iter = set.iter();
232 /// assert_eq!(set_iter.next(), Some(&1));
233 /// assert_eq!(set_iter.next(), Some(&2));
234 /// assert_eq!(set_iter.next(), Some(&3));
235 /// assert_eq!(set_iter.next(), None);
238 /// Values returned by the iterator are returned in ascending order:
241 /// use std::collections::BTreeSet;
243 /// let set: BTreeSet<usize> = [3, 1, 2].iter().cloned().collect();
244 /// let mut set_iter = set.iter();
245 /// assert_eq!(set_iter.next(), Some(&1));
246 /// assert_eq!(set_iter.next(), Some(&2));
247 /// assert_eq!(set_iter.next(), Some(&3));
248 /// assert_eq!(set_iter.next(), None);
250 #[stable(feature = "rust1", since = "1.0.0")]
251 pub fn iter(&self) -> Iter<T> {
252 Iter { iter: self.map.keys() }
256 impl<T: Ord> BTreeSet<T> {
257 /// Constructs a double-ended iterator over a sub-range of elements in the set.
258 /// The simplest way is to use the range syntax `min..max`, thus `range(min..max)` will
259 /// yield elements from min (inclusive) to max (exclusive).
260 /// The range may also be entered as `(Bound<T>, Bound<T>)`, so for example
261 /// `range((Excluded(4), Included(10)))` will yield a left-exclusive, right-inclusive
262 /// range from 4 to 10.
267 /// #![feature(btree_range, collections_bound)]
269 /// use std::collections::BTreeSet;
270 /// use std::collections::Bound::Included;
272 /// let mut set = BTreeSet::new();
276 /// for &elem in set.range((Included(&4), Included(&8))) {
277 /// println!("{}", elem);
279 /// assert_eq!(Some(&5), set.range(4..).next());
281 #[unstable(feature = "btree_range",
282 reason = "matches collection reform specification, waiting for dust to settle",
284 pub fn range<K: ?Sized, R>(&self, range: R) -> Range<T>
285 where K: Ord, T: Borrow<K>, R: RangeArgument<K>
287 Range { iter: self.map.range(range) }
291 impl<T: Ord> BTreeSet<T> {
292 /// Visits the values representing the difference,
293 /// i.e. the values that are in `self` but not in `other`,
294 /// in ascending order.
299 /// use std::collections::BTreeSet;
301 /// let mut a = BTreeSet::new();
305 /// let mut b = BTreeSet::new();
309 /// let diff: Vec<_> = a.difference(&b).cloned().collect();
310 /// assert_eq!(diff, [1]);
312 #[stable(feature = "rust1", since = "1.0.0")]
313 pub fn difference<'a>(&'a self, other: &'a BTreeSet<T>) -> Difference<'a, T> {
315 a: self.iter().peekable(),
316 b: other.iter().peekable(),
320 /// Visits the values representing the symmetric difference,
321 /// i.e. the values that are in `self` or in `other` but not in both,
322 /// in ascending order.
327 /// use std::collections::BTreeSet;
329 /// let mut a = BTreeSet::new();
333 /// let mut b = BTreeSet::new();
337 /// let sym_diff: Vec<_> = a.symmetric_difference(&b).cloned().collect();
338 /// assert_eq!(sym_diff, [1, 3]);
340 #[stable(feature = "rust1", since = "1.0.0")]
341 pub fn symmetric_difference<'a>(&'a self,
342 other: &'a BTreeSet<T>)
343 -> SymmetricDifference<'a, T> {
344 SymmetricDifference {
345 a: self.iter().peekable(),
346 b: other.iter().peekable(),
350 /// Visits the values representing the intersection,
351 /// i.e. the values that are both in `self` and `other`,
352 /// in ascending order.
357 /// use std::collections::BTreeSet;
359 /// let mut a = BTreeSet::new();
363 /// let mut b = BTreeSet::new();
367 /// let intersection: Vec<_> = a.intersection(&b).cloned().collect();
368 /// assert_eq!(intersection, [2]);
370 #[stable(feature = "rust1", since = "1.0.0")]
371 pub fn intersection<'a>(&'a self, other: &'a BTreeSet<T>) -> Intersection<'a, T> {
373 a: self.iter().peekable(),
374 b: other.iter().peekable(),
378 /// Visits the values representing the union,
379 /// i.e. all the values in `self` or `other`, without duplicates,
380 /// in ascending order.
385 /// use std::collections::BTreeSet;
387 /// let mut a = BTreeSet::new();
390 /// let mut b = BTreeSet::new();
393 /// let union: Vec<_> = a.union(&b).cloned().collect();
394 /// assert_eq!(union, [1, 2]);
396 #[stable(feature = "rust1", since = "1.0.0")]
397 pub fn union<'a>(&'a self, other: &'a BTreeSet<T>) -> Union<'a, T> {
399 a: self.iter().peekable(),
400 b: other.iter().peekable(),
404 /// Returns the number of elements in the set.
409 /// use std::collections::BTreeSet;
411 /// let mut v = BTreeSet::new();
412 /// assert_eq!(v.len(), 0);
414 /// assert_eq!(v.len(), 1);
416 #[stable(feature = "rust1", since = "1.0.0")]
417 pub fn len(&self) -> usize {
421 /// Returns true if the set contains no elements.
426 /// use std::collections::BTreeSet;
428 /// let mut v = BTreeSet::new();
429 /// assert!(v.is_empty());
431 /// assert!(!v.is_empty());
433 #[stable(feature = "rust1", since = "1.0.0")]
434 pub fn is_empty(&self) -> bool {
438 /// Clears the set, removing all values.
443 /// use std::collections::BTreeSet;
445 /// let mut v = BTreeSet::new();
448 /// assert!(v.is_empty());
450 #[stable(feature = "rust1", since = "1.0.0")]
451 pub fn clear(&mut self) {
455 /// Returns `true` if the set contains a value.
457 /// The value may be any borrowed form of the set's value type,
458 /// but the ordering on the borrowed form *must* match the
459 /// ordering on the value type.
464 /// use std::collections::BTreeSet;
466 /// let set: BTreeSet<_> = [1, 2, 3].iter().cloned().collect();
467 /// assert_eq!(set.contains(&1), true);
468 /// assert_eq!(set.contains(&4), false);
470 #[stable(feature = "rust1", since = "1.0.0")]
471 pub fn contains<Q: ?Sized>(&self, value: &Q) -> bool
475 self.map.contains_key(value)
478 /// Returns a reference to the value in the set, if any, that is equal to the given value.
480 /// The value may be any borrowed form of the set's value type,
481 /// but the ordering on the borrowed form *must* match the
482 /// ordering on the value type.
483 #[stable(feature = "set_recovery", since = "1.9.0")]
484 pub fn get<Q: ?Sized>(&self, value: &Q) -> Option<&T>
488 Recover::get(&self.map, value)
491 /// Returns `true` if `self` has no elements in common with `other`.
492 /// This is equivalent to checking for an empty intersection.
497 /// use std::collections::BTreeSet;
499 /// let a: BTreeSet<_> = [1, 2, 3].iter().cloned().collect();
500 /// let mut b = BTreeSet::new();
502 /// assert_eq!(a.is_disjoint(&b), true);
504 /// assert_eq!(a.is_disjoint(&b), true);
506 /// assert_eq!(a.is_disjoint(&b), false);
508 #[stable(feature = "rust1", since = "1.0.0")]
509 pub fn is_disjoint(&self, other: &BTreeSet<T>) -> bool {
510 self.intersection(other).next().is_none()
513 /// Returns `true` if the set is a subset of another,
514 /// i.e. `other` contains at least all the values in `self`.
519 /// use std::collections::BTreeSet;
521 /// let sup: BTreeSet<_> = [1, 2, 3].iter().cloned().collect();
522 /// let mut set = BTreeSet::new();
524 /// assert_eq!(set.is_subset(&sup), true);
526 /// assert_eq!(set.is_subset(&sup), true);
528 /// assert_eq!(set.is_subset(&sup), false);
530 #[stable(feature = "rust1", since = "1.0.0")]
531 pub fn is_subset(&self, other: &BTreeSet<T>) -> bool {
532 // Stolen from TreeMap
533 let mut x = self.iter();
534 let mut y = other.iter();
535 let mut a = x.next();
536 let mut b = y.next();
547 Greater => return false,
548 Equal => a = x.next(),
556 /// Returns `true` if the set is a superset of another,
557 /// i.e. `self` contains at least all the values in `other`.
562 /// use std::collections::BTreeSet;
564 /// let sub: BTreeSet<_> = [1, 2].iter().cloned().collect();
565 /// let mut set = BTreeSet::new();
567 /// assert_eq!(set.is_superset(&sub), false);
571 /// assert_eq!(set.is_superset(&sub), false);
574 /// assert_eq!(set.is_superset(&sub), true);
576 #[stable(feature = "rust1", since = "1.0.0")]
577 pub fn is_superset(&self, other: &BTreeSet<T>) -> bool {
578 other.is_subset(self)
581 /// Adds a value to the set.
583 /// If the set did not have this value present, `true` is returned.
585 /// If the set did have this value present, `false` is returned, and the
586 /// entry is not updated. See the [module-level documentation] for more.
588 /// [module-level documentation]: index.html#insert-and-complex-keys
593 /// use std::collections::BTreeSet;
595 /// let mut set = BTreeSet::new();
597 /// assert_eq!(set.insert(2), true);
598 /// assert_eq!(set.insert(2), false);
599 /// assert_eq!(set.len(), 1);
601 #[stable(feature = "rust1", since = "1.0.0")]
602 pub fn insert(&mut self, value: T) -> bool {
603 self.map.insert(value, ()).is_none()
606 /// Adds a value to the set, replacing the existing value, if any, that is equal to the given
607 /// one. Returns the replaced value.
608 #[stable(feature = "set_recovery", since = "1.9.0")]
609 pub fn replace(&mut self, value: T) -> Option<T> {
610 Recover::replace(&mut self.map, value)
613 /// Removes a value from the set. Returns `true` if the value was
614 /// present in the set.
616 /// The value may be any borrowed form of the set's value type,
617 /// but the ordering on the borrowed form *must* match the
618 /// ordering on the value type.
623 /// use std::collections::BTreeSet;
625 /// let mut set = BTreeSet::new();
628 /// assert_eq!(set.remove(&2), true);
629 /// assert_eq!(set.remove(&2), false);
631 #[stable(feature = "rust1", since = "1.0.0")]
632 pub fn remove<Q: ?Sized>(&mut self, value: &Q) -> bool
636 self.map.remove(value).is_some()
639 /// Removes and returns the value in the set, if any, that is equal to the given one.
641 /// The value may be any borrowed form of the set's value type,
642 /// but the ordering on the borrowed form *must* match the
643 /// ordering on the value type.
644 #[stable(feature = "set_recovery", since = "1.9.0")]
645 pub fn take<Q: ?Sized>(&mut self, value: &Q) -> Option<T>
649 Recover::take(&mut self.map, value)
652 /// Moves all elements from `other` into `Self`, leaving `other` empty.
657 /// use std::collections::BTreeSet;
659 /// let mut a = BTreeSet::new();
664 /// let mut b = BTreeSet::new();
669 /// a.append(&mut b);
671 /// assert_eq!(a.len(), 5);
672 /// assert_eq!(b.len(), 0);
674 /// assert!(a.contains(&1));
675 /// assert!(a.contains(&2));
676 /// assert!(a.contains(&3));
677 /// assert!(a.contains(&4));
678 /// assert!(a.contains(&5));
680 #[stable(feature = "btree_append", since = "1.11.0")]
681 pub fn append(&mut self, other: &mut Self) {
682 self.map.append(&mut other.map);
685 /// Splits the collection into two at the given key. Returns everything after the given key,
686 /// including the key.
693 /// use std::collections::BTreeMap;
695 /// let mut a = BTreeMap::new();
696 /// a.insert(1, "a");
697 /// a.insert(2, "b");
698 /// a.insert(3, "c");
699 /// a.insert(17, "d");
700 /// a.insert(41, "e");
702 /// let b = a.split_off(&3);
704 /// assert_eq!(a.len(), 2);
705 /// assert_eq!(b.len(), 3);
707 /// assert_eq!(a[&1], "a");
708 /// assert_eq!(a[&2], "b");
710 /// assert_eq!(b[&3], "c");
711 /// assert_eq!(b[&17], "d");
712 /// assert_eq!(b[&41], "e");
714 #[stable(feature = "btree_split_off", since = "1.11.0")]
715 pub fn split_off<Q: ?Sized + Ord>(&mut self, key: &Q) -> Self where T: Borrow<Q> {
716 BTreeSet { map: self.map.split_off(key) }
720 #[stable(feature = "rust1", since = "1.0.0")]
721 impl<T: Ord> FromIterator<T> for BTreeSet<T> {
722 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> BTreeSet<T> {
723 let mut set = BTreeSet::new();
729 #[stable(feature = "rust1", since = "1.0.0")]
730 impl<T> IntoIterator for BTreeSet<T> {
732 type IntoIter = IntoIter<T>;
734 /// Gets an iterator for moving out the BtreeSet's contents.
739 /// use std::collections::BTreeSet;
741 /// let set: BTreeSet<usize> = [1, 2, 3, 4].iter().cloned().collect();
743 /// let v: Vec<_> = set.into_iter().collect();
744 /// assert_eq!(v, [1, 2, 3, 4]);
746 fn into_iter(self) -> IntoIter<T> {
747 IntoIter { iter: self.map.into_iter() }
751 #[stable(feature = "rust1", since = "1.0.0")]
752 impl<'a, T> IntoIterator for &'a BTreeSet<T> {
754 type IntoIter = Iter<'a, T>;
756 fn into_iter(self) -> Iter<'a, T> {
761 #[stable(feature = "rust1", since = "1.0.0")]
762 impl<T: Ord> Extend<T> for BTreeSet<T> {
764 fn extend<Iter: IntoIterator<Item = T>>(&mut self, iter: Iter) {
771 #[stable(feature = "extend_ref", since = "1.2.0")]
772 impl<'a, T: 'a + Ord + Copy> Extend<&'a T> for BTreeSet<T> {
773 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
774 self.extend(iter.into_iter().cloned());
778 #[stable(feature = "rust1", since = "1.0.0")]
779 impl<T: Ord> Default for BTreeSet<T> {
780 /// Makes an empty `BTreeSet<T>` with a reasonable choice of B.
781 fn default() -> BTreeSet<T> {
786 #[stable(feature = "rust1", since = "1.0.0")]
787 impl<'a, 'b, T: Ord + Clone> Sub<&'b BTreeSet<T>> for &'a BTreeSet<T> {
788 type Output = BTreeSet<T>;
790 /// Returns the difference of `self` and `rhs` as a new `BTreeSet<T>`.
795 /// use std::collections::BTreeSet;
797 /// let a: BTreeSet<_> = vec![1, 2, 3].into_iter().collect();
798 /// let b: BTreeSet<_> = vec![3, 4, 5].into_iter().collect();
800 /// let result = &a - &b;
801 /// let result_vec: Vec<_> = result.into_iter().collect();
802 /// assert_eq!(result_vec, [1, 2]);
804 fn sub(self, rhs: &BTreeSet<T>) -> BTreeSet<T> {
805 self.difference(rhs).cloned().collect()
809 #[stable(feature = "rust1", since = "1.0.0")]
810 impl<'a, 'b, T: Ord + Clone> BitXor<&'b BTreeSet<T>> for &'a BTreeSet<T> {
811 type Output = BTreeSet<T>;
813 /// Returns the symmetric difference of `self` and `rhs` as a new `BTreeSet<T>`.
818 /// use std::collections::BTreeSet;
820 /// let a: BTreeSet<_> = vec![1, 2, 3].into_iter().collect();
821 /// let b: BTreeSet<_> = vec![2, 3, 4].into_iter().collect();
823 /// let result = &a ^ &b;
824 /// let result_vec: Vec<_> = result.into_iter().collect();
825 /// assert_eq!(result_vec, [1, 4]);
827 fn bitxor(self, rhs: &BTreeSet<T>) -> BTreeSet<T> {
828 self.symmetric_difference(rhs).cloned().collect()
832 #[stable(feature = "rust1", since = "1.0.0")]
833 impl<'a, 'b, T: Ord + Clone> BitAnd<&'b BTreeSet<T>> for &'a BTreeSet<T> {
834 type Output = BTreeSet<T>;
836 /// Returns the intersection of `self` and `rhs` as a new `BTreeSet<T>`.
841 /// use std::collections::BTreeSet;
843 /// let a: BTreeSet<_> = vec![1, 2, 3].into_iter().collect();
844 /// let b: BTreeSet<_> = vec![2, 3, 4].into_iter().collect();
846 /// let result = &a & &b;
847 /// let result_vec: Vec<_> = result.into_iter().collect();
848 /// assert_eq!(result_vec, [2, 3]);
850 fn bitand(self, rhs: &BTreeSet<T>) -> BTreeSet<T> {
851 self.intersection(rhs).cloned().collect()
855 #[stable(feature = "rust1", since = "1.0.0")]
856 impl<'a, 'b, T: Ord + Clone> BitOr<&'b BTreeSet<T>> for &'a BTreeSet<T> {
857 type Output = BTreeSet<T>;
859 /// Returns the union of `self` and `rhs` as a new `BTreeSet<T>`.
864 /// use std::collections::BTreeSet;
866 /// let a: BTreeSet<_> = vec![1, 2, 3].into_iter().collect();
867 /// let b: BTreeSet<_> = vec![3, 4, 5].into_iter().collect();
869 /// let result = &a | &b;
870 /// let result_vec: Vec<_> = result.into_iter().collect();
871 /// assert_eq!(result_vec, [1, 2, 3, 4, 5]);
873 fn bitor(self, rhs: &BTreeSet<T>) -> BTreeSet<T> {
874 self.union(rhs).cloned().collect()
878 #[stable(feature = "rust1", since = "1.0.0")]
879 impl<T: Debug> Debug for BTreeSet<T> {
880 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
881 f.debug_set().entries(self.iter()).finish()
885 #[stable(feature = "rust1", since = "1.0.0")]
886 impl<'a, T> Clone for Iter<'a, T> {
887 fn clone(&self) -> Iter<'a, T> {
888 Iter { iter: self.iter.clone() }
891 #[stable(feature = "rust1", since = "1.0.0")]
892 impl<'a, T> Iterator for Iter<'a, T> {
895 fn next(&mut self) -> Option<&'a T> {
898 fn size_hint(&self) -> (usize, Option<usize>) {
899 self.iter.size_hint()
902 #[stable(feature = "rust1", since = "1.0.0")]
903 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
904 fn next_back(&mut self) -> Option<&'a T> {
905 self.iter.next_back()
908 #[stable(feature = "rust1", since = "1.0.0")]
909 impl<'a, T> ExactSizeIterator for Iter<'a, T> {
910 fn len(&self) -> usize { self.iter.len() }
913 #[unstable(feature = "fused", issue = "35602")]
914 impl<'a, T> FusedIterator for Iter<'a, T> {}
916 #[stable(feature = "rust1", since = "1.0.0")]
917 impl<T> Iterator for IntoIter<T> {
920 fn next(&mut self) -> Option<T> {
921 self.iter.next().map(|(k, _)| k)
923 fn size_hint(&self) -> (usize, Option<usize>) {
924 self.iter.size_hint()
927 #[stable(feature = "rust1", since = "1.0.0")]
928 impl<T> DoubleEndedIterator for IntoIter<T> {
929 fn next_back(&mut self) -> Option<T> {
930 self.iter.next_back().map(|(k, _)| k)
933 #[stable(feature = "rust1", since = "1.0.0")]
934 impl<T> ExactSizeIterator for IntoIter<T> {
935 fn len(&self) -> usize { self.iter.len() }
938 #[unstable(feature = "fused", issue = "35602")]
939 impl<T> FusedIterator for IntoIter<T> {}
941 impl<'a, T> Clone for Range<'a, T> {
942 fn clone(&self) -> Range<'a, T> {
943 Range { iter: self.iter.clone() }
946 impl<'a, T> Iterator for Range<'a, T> {
949 fn next(&mut self) -> Option<&'a T> {
950 self.iter.next().map(|(k, _)| k)
953 impl<'a, T> DoubleEndedIterator for Range<'a, T> {
954 fn next_back(&mut self) -> Option<&'a T> {
955 self.iter.next_back().map(|(k, _)| k)
959 #[unstable(feature = "fused", issue = "35602")]
960 impl<'a, T> FusedIterator for Range<'a, T> {}
962 /// Compare `x` and `y`, but return `short` if x is None and `long` if y is None
963 fn cmp_opt<T: Ord>(x: Option<&T>, y: Option<&T>, short: Ordering, long: Ordering) -> Ordering {
967 (Some(x1), Some(y1)) => x1.cmp(y1),
971 #[stable(feature = "rust1", since = "1.0.0")]
972 impl<'a, T> Clone for Difference<'a, T> {
973 fn clone(&self) -> Difference<'a, T> {
980 #[stable(feature = "rust1", since = "1.0.0")]
981 impl<'a, T: Ord> Iterator for Difference<'a, T> {
984 fn next(&mut self) -> Option<&'a T> {
986 match cmp_opt(self.a.peek(), self.b.peek(), Less, Less) {
987 Less => return self.a.next(),
999 fn size_hint(&self) -> (usize, Option<usize>) {
1000 let a_len = self.a.len();
1001 let b_len = self.b.len();
1002 (a_len.saturating_sub(b_len), Some(a_len))
1006 #[unstable(feature = "fused", issue = "35602")]
1007 impl<'a, T: Ord> FusedIterator for Difference<'a, T> {}
1009 #[stable(feature = "rust1", since = "1.0.0")]
1010 impl<'a, T> Clone for SymmetricDifference<'a, T> {
1011 fn clone(&self) -> SymmetricDifference<'a, T> {
1012 SymmetricDifference {
1018 #[stable(feature = "rust1", since = "1.0.0")]
1019 impl<'a, T: Ord> Iterator for SymmetricDifference<'a, T> {
1022 fn next(&mut self) -> Option<&'a T> {
1024 match cmp_opt(self.a.peek(), self.b.peek(), Greater, Less) {
1025 Less => return self.a.next(),
1030 Greater => return self.b.next(),
1035 fn size_hint(&self) -> (usize, Option<usize>) {
1036 (0, Some(self.a.len() + self.b.len()))
1040 #[unstable(feature = "fused", issue = "35602")]
1041 impl<'a, T: Ord> FusedIterator for SymmetricDifference<'a, T> {}
1043 #[stable(feature = "rust1", since = "1.0.0")]
1044 impl<'a, T> Clone for Intersection<'a, T> {
1045 fn clone(&self) -> Intersection<'a, T> {
1052 #[stable(feature = "rust1", since = "1.0.0")]
1053 impl<'a, T: Ord> Iterator for Intersection<'a, T> {
1056 fn next(&mut self) -> Option<&'a T> {
1058 let o_cmp = match (self.a.peek(), self.b.peek()) {
1061 (Some(a1), Some(b1)) => Some(a1.cmp(b1)),
1064 None => return None,
1070 return self.a.next();
1079 fn size_hint(&self) -> (usize, Option<usize>) {
1080 (0, Some(min(self.a.len(), self.b.len())))
1084 #[unstable(feature = "fused", issue = "35602")]
1085 impl<'a, T: Ord> FusedIterator for Intersection<'a, T> {}
1087 #[stable(feature = "rust1", since = "1.0.0")]
1088 impl<'a, T> Clone for Union<'a, T> {
1089 fn clone(&self) -> Union<'a, T> {
1096 #[stable(feature = "rust1", since = "1.0.0")]
1097 impl<'a, T: Ord> Iterator for Union<'a, T> {
1100 fn next(&mut self) -> Option<&'a T> {
1102 match cmp_opt(self.a.peek(), self.b.peek(), Greater, Less) {
1103 Less => return self.a.next(),
1106 return self.a.next();
1108 Greater => return 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> {}