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")
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() }
233 impl<T> BTreeSet<T> {
234 /// Gets an iterator that visits the values in the `BTreeSet` in ascending order.
239 /// use std::collections::BTreeSet;
241 /// let set: BTreeSet<usize> = [1, 2, 3].iter().cloned().collect();
242 /// let mut set_iter = set.iter();
243 /// assert_eq!(set_iter.next(), Some(&1));
244 /// assert_eq!(set_iter.next(), Some(&2));
245 /// assert_eq!(set_iter.next(), Some(&3));
246 /// assert_eq!(set_iter.next(), None);
249 /// Values returned by the iterator are returned in ascending order:
252 /// use std::collections::BTreeSet;
254 /// let set: BTreeSet<usize> = [3, 1, 2].iter().cloned().collect();
255 /// let mut set_iter = set.iter();
256 /// assert_eq!(set_iter.next(), Some(&1));
257 /// assert_eq!(set_iter.next(), Some(&2));
258 /// assert_eq!(set_iter.next(), Some(&3));
259 /// assert_eq!(set_iter.next(), None);
261 #[stable(feature = "rust1", since = "1.0.0")]
262 pub fn iter(&self) -> Iter<T> {
263 Iter { iter: self.map.keys() }
267 impl<T: Ord> BTreeSet<T> {
268 /// Constructs a double-ended iterator over a sub-range of elements in the set.
269 /// The simplest way is to use the range syntax `min..max`, thus `range(min..max)` will
270 /// yield elements from min (inclusive) to max (exclusive).
271 /// The range may also be entered as `(Bound<T>, Bound<T>)`, so for example
272 /// `range((Excluded(4), Included(10)))` will yield a left-exclusive, right-inclusive
273 /// range from 4 to 10.
278 /// use std::collections::BTreeSet;
279 /// use std::collections::Bound::Included;
281 /// let mut set = BTreeSet::new();
285 /// for &elem in set.range((Included(&4), Included(&8))) {
286 /// println!("{}", elem);
288 /// assert_eq!(Some(&5), set.range(4..).next());
290 #[stable(feature = "btree_range", since = "1.17.0")]
291 pub fn range<K: ?Sized, R>(&self, range: R) -> Range<T>
292 where K: Ord, T: Borrow<K>, R: RangeArgument<K>
294 Range { iter: self.map.range(range) }
298 impl<T: Ord> BTreeSet<T> {
299 /// Visits the values representing the difference,
300 /// i.e. the values that are in `self` but not in `other`,
301 /// in ascending order.
306 /// use std::collections::BTreeSet;
308 /// let mut a = BTreeSet::new();
312 /// let mut b = BTreeSet::new();
316 /// let diff: Vec<_> = a.difference(&b).cloned().collect();
317 /// assert_eq!(diff, [1]);
319 #[stable(feature = "rust1", since = "1.0.0")]
320 pub fn difference<'a>(&'a self, other: &'a BTreeSet<T>) -> Difference<'a, T> {
322 a: self.iter().peekable(),
323 b: other.iter().peekable(),
327 /// Visits the values representing the symmetric difference,
328 /// i.e. the values that are in `self` or in `other` but not in both,
329 /// in ascending order.
334 /// use std::collections::BTreeSet;
336 /// let mut a = BTreeSet::new();
340 /// let mut b = BTreeSet::new();
344 /// let sym_diff: Vec<_> = a.symmetric_difference(&b).cloned().collect();
345 /// assert_eq!(sym_diff, [1, 3]);
347 #[stable(feature = "rust1", since = "1.0.0")]
348 pub fn symmetric_difference<'a>(&'a self,
349 other: &'a BTreeSet<T>)
350 -> SymmetricDifference<'a, T> {
351 SymmetricDifference {
352 a: self.iter().peekable(),
353 b: other.iter().peekable(),
357 /// Visits the values representing the intersection,
358 /// i.e. the values that are both in `self` and `other`,
359 /// in ascending order.
364 /// use std::collections::BTreeSet;
366 /// let mut a = BTreeSet::new();
370 /// let mut b = BTreeSet::new();
374 /// let intersection: Vec<_> = a.intersection(&b).cloned().collect();
375 /// assert_eq!(intersection, [2]);
377 #[stable(feature = "rust1", since = "1.0.0")]
378 pub fn intersection<'a>(&'a self, other: &'a BTreeSet<T>) -> Intersection<'a, T> {
380 a: self.iter().peekable(),
381 b: other.iter().peekable(),
385 /// Visits the values representing the union,
386 /// i.e. all the values in `self` or `other`, without duplicates,
387 /// in ascending order.
392 /// use std::collections::BTreeSet;
394 /// let mut a = BTreeSet::new();
397 /// let mut b = BTreeSet::new();
400 /// let union: Vec<_> = a.union(&b).cloned().collect();
401 /// assert_eq!(union, [1, 2]);
403 #[stable(feature = "rust1", since = "1.0.0")]
404 pub fn union<'a>(&'a self, other: &'a BTreeSet<T>) -> Union<'a, T> {
406 a: self.iter().peekable(),
407 b: other.iter().peekable(),
411 /// Returns the number of elements in the set.
416 /// use std::collections::BTreeSet;
418 /// let mut v = BTreeSet::new();
419 /// assert_eq!(v.len(), 0);
421 /// assert_eq!(v.len(), 1);
423 #[stable(feature = "rust1", since = "1.0.0")]
424 pub fn len(&self) -> usize {
428 /// Returns `true` if the set contains no elements.
433 /// use std::collections::BTreeSet;
435 /// let mut v = BTreeSet::new();
436 /// assert!(v.is_empty());
438 /// assert!(!v.is_empty());
440 #[stable(feature = "rust1", since = "1.0.0")]
441 pub fn is_empty(&self) -> bool {
445 /// Clears the set, removing all values.
450 /// use std::collections::BTreeSet;
452 /// let mut v = BTreeSet::new();
455 /// assert!(v.is_empty());
457 #[stable(feature = "rust1", since = "1.0.0")]
458 pub fn clear(&mut self) {
462 /// Returns `true` if the set contains a value.
464 /// The value may be any borrowed form of the set's value type,
465 /// but the ordering on the borrowed form *must* match the
466 /// ordering on the value type.
471 /// use std::collections::BTreeSet;
473 /// let set: BTreeSet<_> = [1, 2, 3].iter().cloned().collect();
474 /// assert_eq!(set.contains(&1), true);
475 /// assert_eq!(set.contains(&4), false);
477 #[stable(feature = "rust1", since = "1.0.0")]
478 pub fn contains<Q: ?Sized>(&self, value: &Q) -> bool
482 self.map.contains_key(value)
485 /// Returns a reference to the value in the set, if any, that is equal to the given value.
487 /// The value may be any borrowed form of the set's value type,
488 /// but the ordering on the borrowed form *must* match the
489 /// ordering on the value type.
490 #[stable(feature = "set_recovery", since = "1.9.0")]
491 pub fn get<Q: ?Sized>(&self, value: &Q) -> Option<&T>
495 Recover::get(&self.map, value)
498 /// Returns `true` if `self` has no elements in common with `other`.
499 /// This is equivalent to checking for an empty intersection.
504 /// use std::collections::BTreeSet;
506 /// let a: BTreeSet<_> = [1, 2, 3].iter().cloned().collect();
507 /// let mut b = BTreeSet::new();
509 /// assert_eq!(a.is_disjoint(&b), true);
511 /// assert_eq!(a.is_disjoint(&b), true);
513 /// assert_eq!(a.is_disjoint(&b), false);
515 #[stable(feature = "rust1", since = "1.0.0")]
516 pub fn is_disjoint(&self, other: &BTreeSet<T>) -> bool {
517 self.intersection(other).next().is_none()
520 /// Returns `true` if the set is a subset of another,
521 /// i.e. `other` contains at least all the values in `self`.
526 /// use std::collections::BTreeSet;
528 /// let sup: BTreeSet<_> = [1, 2, 3].iter().cloned().collect();
529 /// let mut set = BTreeSet::new();
531 /// assert_eq!(set.is_subset(&sup), true);
533 /// assert_eq!(set.is_subset(&sup), true);
535 /// assert_eq!(set.is_subset(&sup), false);
537 #[stable(feature = "rust1", since = "1.0.0")]
538 pub fn is_subset(&self, other: &BTreeSet<T>) -> bool {
539 // Stolen from TreeMap
540 let mut x = self.iter();
541 let mut y = other.iter();
542 let mut a = x.next();
543 let mut b = y.next();
554 Greater => return false,
555 Equal => a = x.next(),
563 /// Returns `true` if the set is a superset of another,
564 /// i.e. `self` contains at least all the values in `other`.
569 /// use std::collections::BTreeSet;
571 /// let sub: BTreeSet<_> = [1, 2].iter().cloned().collect();
572 /// let mut set = BTreeSet::new();
574 /// assert_eq!(set.is_superset(&sub), false);
578 /// assert_eq!(set.is_superset(&sub), false);
581 /// assert_eq!(set.is_superset(&sub), true);
583 #[stable(feature = "rust1", since = "1.0.0")]
584 pub fn is_superset(&self, other: &BTreeSet<T>) -> bool {
585 other.is_subset(self)
588 /// Adds a value to the set.
590 /// If the set did not have this value present, `true` is returned.
592 /// If the set did have this value present, `false` is returned, and the
593 /// entry is not updated. See the [module-level documentation] for more.
595 /// [module-level documentation]: index.html#insert-and-complex-keys
600 /// use std::collections::BTreeSet;
602 /// let mut set = BTreeSet::new();
604 /// assert_eq!(set.insert(2), true);
605 /// assert_eq!(set.insert(2), false);
606 /// assert_eq!(set.len(), 1);
608 #[stable(feature = "rust1", since = "1.0.0")]
609 pub fn insert(&mut self, value: T) -> bool {
610 self.map.insert(value, ()).is_none()
613 /// Adds a value to the set, replacing the existing value, if any, that is equal to the given
614 /// one. Returns the replaced value.
615 #[stable(feature = "set_recovery", since = "1.9.0")]
616 pub fn replace(&mut self, value: T) -> Option<T> {
617 Recover::replace(&mut self.map, value)
620 /// Removes a value from the set. Returns `true` if the value was
621 /// present in the set.
623 /// The value may be any borrowed form of the set's value type,
624 /// but the ordering on the borrowed form *must* match the
625 /// ordering on the value type.
630 /// use std::collections::BTreeSet;
632 /// let mut set = BTreeSet::new();
635 /// assert_eq!(set.remove(&2), true);
636 /// assert_eq!(set.remove(&2), false);
638 #[stable(feature = "rust1", since = "1.0.0")]
639 pub fn remove<Q: ?Sized>(&mut self, value: &Q) -> bool
643 self.map.remove(value).is_some()
646 /// Removes and returns the value in the set, if any, that is equal to the given one.
648 /// The value may be any borrowed form of the set's value type,
649 /// but the ordering on the borrowed form *must* match the
650 /// ordering on the value type.
651 #[stable(feature = "set_recovery", since = "1.9.0")]
652 pub fn take<Q: ?Sized>(&mut self, value: &Q) -> Option<T>
656 Recover::take(&mut self.map, value)
659 /// Moves all elements from `other` into `Self`, leaving `other` empty.
664 /// use std::collections::BTreeSet;
666 /// let mut a = BTreeSet::new();
671 /// let mut b = BTreeSet::new();
676 /// a.append(&mut b);
678 /// assert_eq!(a.len(), 5);
679 /// assert_eq!(b.len(), 0);
681 /// assert!(a.contains(&1));
682 /// assert!(a.contains(&2));
683 /// assert!(a.contains(&3));
684 /// assert!(a.contains(&4));
685 /// assert!(a.contains(&5));
687 #[stable(feature = "btree_append", since = "1.11.0")]
688 pub fn append(&mut self, other: &mut Self) {
689 self.map.append(&mut other.map);
692 /// Splits the collection into two at the given key. Returns everything after the given key,
693 /// including the key.
700 /// use std::collections::BTreeMap;
702 /// let mut a = BTreeMap::new();
703 /// a.insert(1, "a");
704 /// a.insert(2, "b");
705 /// a.insert(3, "c");
706 /// a.insert(17, "d");
707 /// a.insert(41, "e");
709 /// let b = a.split_off(&3);
711 /// assert_eq!(a.len(), 2);
712 /// assert_eq!(b.len(), 3);
714 /// assert_eq!(a[&1], "a");
715 /// assert_eq!(a[&2], "b");
717 /// assert_eq!(b[&3], "c");
718 /// assert_eq!(b[&17], "d");
719 /// assert_eq!(b[&41], "e");
721 #[stable(feature = "btree_split_off", since = "1.11.0")]
722 pub fn split_off<Q: ?Sized + Ord>(&mut self, key: &Q) -> Self where T: Borrow<Q> {
723 BTreeSet { map: self.map.split_off(key) }
727 #[stable(feature = "rust1", since = "1.0.0")]
728 impl<T: Ord> FromIterator<T> for BTreeSet<T> {
729 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> BTreeSet<T> {
730 let mut set = BTreeSet::new();
736 #[stable(feature = "rust1", since = "1.0.0")]
737 impl<T> IntoIterator for BTreeSet<T> {
739 type IntoIter = IntoIter<T>;
741 /// Gets an iterator for moving out the `BTreeSet`'s contents.
746 /// use std::collections::BTreeSet;
748 /// let set: BTreeSet<usize> = [1, 2, 3, 4].iter().cloned().collect();
750 /// let v: Vec<_> = set.into_iter().collect();
751 /// assert_eq!(v, [1, 2, 3, 4]);
753 fn into_iter(self) -> IntoIter<T> {
754 IntoIter { iter: self.map.into_iter() }
758 #[stable(feature = "rust1", since = "1.0.0")]
759 impl<'a, T> IntoIterator for &'a BTreeSet<T> {
761 type IntoIter = Iter<'a, T>;
763 fn into_iter(self) -> Iter<'a, T> {
768 #[stable(feature = "rust1", since = "1.0.0")]
769 impl<T: Ord> Extend<T> for BTreeSet<T> {
771 fn extend<Iter: IntoIterator<Item = T>>(&mut self, iter: Iter) {
778 #[stable(feature = "extend_ref", since = "1.2.0")]
779 impl<'a, T: 'a + Ord + Copy> Extend<&'a T> for BTreeSet<T> {
780 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
781 self.extend(iter.into_iter().cloned());
785 #[stable(feature = "rust1", since = "1.0.0")]
786 impl<T: Ord> Default for BTreeSet<T> {
787 /// Makes an empty `BTreeSet<T>` with a reasonable choice of B.
788 fn default() -> BTreeSet<T> {
793 #[stable(feature = "rust1", since = "1.0.0")]
794 impl<'a, 'b, T: Ord + Clone> Sub<&'b BTreeSet<T>> for &'a BTreeSet<T> {
795 type Output = BTreeSet<T>;
797 /// Returns the difference of `self` and `rhs` as a new `BTreeSet<T>`.
802 /// use std::collections::BTreeSet;
804 /// let a: BTreeSet<_> = vec![1, 2, 3].into_iter().collect();
805 /// let b: BTreeSet<_> = vec![3, 4, 5].into_iter().collect();
807 /// let result = &a - &b;
808 /// let result_vec: Vec<_> = result.into_iter().collect();
809 /// assert_eq!(result_vec, [1, 2]);
811 fn sub(self, rhs: &BTreeSet<T>) -> BTreeSet<T> {
812 self.difference(rhs).cloned().collect()
816 #[stable(feature = "rust1", since = "1.0.0")]
817 impl<'a, 'b, T: Ord + Clone> BitXor<&'b BTreeSet<T>> for &'a BTreeSet<T> {
818 type Output = BTreeSet<T>;
820 /// Returns the symmetric difference of `self` and `rhs` as a new `BTreeSet<T>`.
825 /// use std::collections::BTreeSet;
827 /// let a: BTreeSet<_> = vec![1, 2, 3].into_iter().collect();
828 /// let b: BTreeSet<_> = vec![2, 3, 4].into_iter().collect();
830 /// let result = &a ^ &b;
831 /// let result_vec: Vec<_> = result.into_iter().collect();
832 /// assert_eq!(result_vec, [1, 4]);
834 fn bitxor(self, rhs: &BTreeSet<T>) -> BTreeSet<T> {
835 self.symmetric_difference(rhs).cloned().collect()
839 #[stable(feature = "rust1", since = "1.0.0")]
840 impl<'a, 'b, T: Ord + Clone> BitAnd<&'b BTreeSet<T>> for &'a BTreeSet<T> {
841 type Output = BTreeSet<T>;
843 /// Returns the intersection of `self` and `rhs` as a new `BTreeSet<T>`.
848 /// use std::collections::BTreeSet;
850 /// let a: BTreeSet<_> = vec![1, 2, 3].into_iter().collect();
851 /// let b: BTreeSet<_> = vec![2, 3, 4].into_iter().collect();
853 /// let result = &a & &b;
854 /// let result_vec: Vec<_> = result.into_iter().collect();
855 /// assert_eq!(result_vec, [2, 3]);
857 fn bitand(self, rhs: &BTreeSet<T>) -> BTreeSet<T> {
858 self.intersection(rhs).cloned().collect()
862 #[stable(feature = "rust1", since = "1.0.0")]
863 impl<'a, 'b, T: Ord + Clone> BitOr<&'b BTreeSet<T>> for &'a BTreeSet<T> {
864 type Output = BTreeSet<T>;
866 /// Returns the union of `self` and `rhs` as a new `BTreeSet<T>`.
871 /// use std::collections::BTreeSet;
873 /// let a: BTreeSet<_> = vec![1, 2, 3].into_iter().collect();
874 /// let b: BTreeSet<_> = vec![3, 4, 5].into_iter().collect();
876 /// let result = &a | &b;
877 /// let result_vec: Vec<_> = result.into_iter().collect();
878 /// assert_eq!(result_vec, [1, 2, 3, 4, 5]);
880 fn bitor(self, rhs: &BTreeSet<T>) -> BTreeSet<T> {
881 self.union(rhs).cloned().collect()
885 #[stable(feature = "rust1", since = "1.0.0")]
886 impl<T: Debug> Debug for BTreeSet<T> {
887 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
888 f.debug_set().entries(self.iter()).finish()
892 #[stable(feature = "rust1", since = "1.0.0")]
893 impl<'a, T> Clone for Iter<'a, T> {
894 fn clone(&self) -> Iter<'a, T> {
895 Iter { iter: self.iter.clone() }
898 #[stable(feature = "rust1", since = "1.0.0")]
899 impl<'a, T> Iterator for Iter<'a, T> {
902 fn next(&mut self) -> Option<&'a T> {
905 fn size_hint(&self) -> (usize, Option<usize>) {
906 self.iter.size_hint()
909 #[stable(feature = "rust1", since = "1.0.0")]
910 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
911 fn next_back(&mut self) -> Option<&'a T> {
912 self.iter.next_back()
915 #[stable(feature = "rust1", since = "1.0.0")]
916 impl<'a, T> ExactSizeIterator for Iter<'a, T> {
917 fn len(&self) -> usize { self.iter.len() }
920 #[unstable(feature = "fused", issue = "35602")]
921 impl<'a, T> FusedIterator for Iter<'a, T> {}
923 #[stable(feature = "rust1", since = "1.0.0")]
924 impl<T> Iterator for IntoIter<T> {
927 fn next(&mut self) -> Option<T> {
928 self.iter.next().map(|(k, _)| k)
930 fn size_hint(&self) -> (usize, Option<usize>) {
931 self.iter.size_hint()
934 #[stable(feature = "rust1", since = "1.0.0")]
935 impl<T> DoubleEndedIterator for IntoIter<T> {
936 fn next_back(&mut self) -> Option<T> {
937 self.iter.next_back().map(|(k, _)| k)
940 #[stable(feature = "rust1", since = "1.0.0")]
941 impl<T> ExactSizeIterator for IntoIter<T> {
942 fn len(&self) -> usize { self.iter.len() }
945 #[unstable(feature = "fused", issue = "35602")]
946 impl<T> FusedIterator for IntoIter<T> {}
948 #[stable(feature = "btree_range", since = "1.17.0")]
949 impl<'a, T> Clone for Range<'a, T> {
950 fn clone(&self) -> Range<'a, T> {
951 Range { iter: self.iter.clone() }
955 #[stable(feature = "btree_range", since = "1.17.0")]
956 impl<'a, T> Iterator for Range<'a, T> {
959 fn next(&mut self) -> Option<&'a T> {
960 self.iter.next().map(|(k, _)| k)
964 #[stable(feature = "btree_range", since = "1.17.0")]
965 impl<'a, T> DoubleEndedIterator for Range<'a, T> {
966 fn next_back(&mut self) -> Option<&'a T> {
967 self.iter.next_back().map(|(k, _)| k)
971 #[unstable(feature = "fused", issue = "35602")]
972 impl<'a, T> FusedIterator for Range<'a, T> {}
974 /// Compare `x` and `y`, but return `short` if x is None and `long` if y is None
975 fn cmp_opt<T: Ord>(x: Option<&T>, y: Option<&T>, short: Ordering, long: Ordering) -> Ordering {
979 (Some(x1), Some(y1)) => x1.cmp(y1),
983 #[stable(feature = "rust1", since = "1.0.0")]
984 impl<'a, T> Clone for Difference<'a, T> {
985 fn clone(&self) -> Difference<'a, T> {
992 #[stable(feature = "rust1", since = "1.0.0")]
993 impl<'a, T: Ord> Iterator for Difference<'a, T> {
996 fn next(&mut self) -> Option<&'a T> {
998 match cmp_opt(self.a.peek(), self.b.peek(), Less, Less) {
999 Less => return self.a.next(),
1011 fn size_hint(&self) -> (usize, Option<usize>) {
1012 let a_len = self.a.len();
1013 let b_len = self.b.len();
1014 (a_len.saturating_sub(b_len), Some(a_len))
1018 #[unstable(feature = "fused", issue = "35602")]
1019 impl<'a, T: Ord> FusedIterator for Difference<'a, T> {}
1021 #[stable(feature = "rust1", since = "1.0.0")]
1022 impl<'a, T> Clone for SymmetricDifference<'a, T> {
1023 fn clone(&self) -> SymmetricDifference<'a, T> {
1024 SymmetricDifference {
1030 #[stable(feature = "rust1", since = "1.0.0")]
1031 impl<'a, T: Ord> Iterator for SymmetricDifference<'a, T> {
1034 fn next(&mut self) -> Option<&'a T> {
1036 match cmp_opt(self.a.peek(), self.b.peek(), Greater, Less) {
1037 Less => return self.a.next(),
1042 Greater => return self.b.next(),
1047 fn size_hint(&self) -> (usize, Option<usize>) {
1048 (0, Some(self.a.len() + self.b.len()))
1052 #[unstable(feature = "fused", issue = "35602")]
1053 impl<'a, T: Ord> FusedIterator for SymmetricDifference<'a, T> {}
1055 #[stable(feature = "rust1", since = "1.0.0")]
1056 impl<'a, T> Clone for Intersection<'a, T> {
1057 fn clone(&self) -> Intersection<'a, T> {
1064 #[stable(feature = "rust1", since = "1.0.0")]
1065 impl<'a, T: Ord> Iterator for Intersection<'a, T> {
1068 fn next(&mut self) -> Option<&'a T> {
1070 let o_cmp = match (self.a.peek(), self.b.peek()) {
1073 (Some(a1), Some(b1)) => Some(a1.cmp(b1)),
1076 None => return None,
1082 return self.a.next();
1091 fn size_hint(&self) -> (usize, Option<usize>) {
1092 (0, Some(min(self.a.len(), self.b.len())))
1096 #[unstable(feature = "fused", issue = "35602")]
1097 impl<'a, T: Ord> FusedIterator for Intersection<'a, T> {}
1099 #[stable(feature = "rust1", since = "1.0.0")]
1100 impl<'a, T> Clone for Union<'a, T> {
1101 fn clone(&self) -> Union<'a, T> {
1108 #[stable(feature = "rust1", since = "1.0.0")]
1109 impl<'a, T: Ord> Iterator for Union<'a, T> {
1112 fn next(&mut self) -> Option<&'a T> {
1114 match cmp_opt(self.a.peek(), self.b.peek(), Greater, Less) {
1115 Less => return self.a.next(),
1118 return self.a.next();
1120 Greater => return self.b.next(),
1125 fn size_hint(&self) -> (usize, Option<usize>) {
1126 let a_len = self.a.len();
1127 let b_len = self.b.len();
1128 (max(a_len, b_len), Some(a_len + b_len))
1132 #[unstable(feature = "fused", issue = "35602")]
1133 impl<'a, T: Ord> FusedIterator for Union<'a, T> {}