]> git.lizzy.rs Git - rust.git/blob - library/alloc/src/collections/btree/set.rs
31655c118072def708c70b2172ab3003b78cd3c0
[rust.git] / library / alloc / src / collections / btree / set.rs
1 // This is pretty much entirely stolen from TreeSet, since BTreeMap has an identical interface
2 // to TreeMap
3
4 use crate::vec::Vec;
5 use core::borrow::Borrow;
6 use core::cmp::Ordering::{Equal, Greater, Less};
7 use core::cmp::{max, min};
8 use core::fmt::{self, Debug};
9 use core::iter::{FromIterator, FusedIterator, Peekable};
10 use core::ops::{BitAnd, BitOr, BitXor, RangeBounds, Sub};
11
12 use super::map::{BTreeMap, Keys};
13 use super::merge_iter::MergeIterInner;
14 use super::Recover;
15
16 // FIXME(conventions): implement bounded iterators
17
18 /// An ordered set based on a B-Tree.
19 ///
20 /// See [`BTreeMap`]'s documentation for a detailed discussion of this collection's performance
21 /// benefits and drawbacks.
22 ///
23 /// It is a logic error for an item to be modified in such a way that the item's ordering relative
24 /// to any other item, as determined by the [`Ord`] trait, changes while it is in the set. This is
25 /// normally only possible through [`Cell`], [`RefCell`], global state, I/O, or unsafe code.
26 /// The behavior resulting from such a logic error is not specified, but will be encapsulated to the
27 /// `BTreeSet` that observed the logic error and not result in undefined behavior. This could
28 /// include panics, incorrect results, aborts, memory leaks, and non-termination.
29 ///
30 /// Iterators returned by [`BTreeSet::iter`] produce their items in order, and take worst-case
31 /// logarithmic and amortized constant time per item returned.
32 ///
33 /// [`Ord`]: core::cmp::Ord
34 /// [`Cell`]: core::cell::Cell
35 /// [`RefCell`]: core::cell::RefCell
36 ///
37 /// # Examples
38 ///
39 /// ```
40 /// use std::collections::BTreeSet;
41 ///
42 /// // Type inference lets us omit an explicit type signature (which
43 /// // would be `BTreeSet<&str>` in this example).
44 /// let mut books = BTreeSet::new();
45 ///
46 /// // Add some books.
47 /// books.insert("A Dance With Dragons");
48 /// books.insert("To Kill a Mockingbird");
49 /// books.insert("The Odyssey");
50 /// books.insert("The Great Gatsby");
51 ///
52 /// // Check for a specific one.
53 /// if !books.contains("The Winds of Winter") {
54 ///     println!("We have {} books, but The Winds of Winter ain't one.",
55 ///              books.len());
56 /// }
57 ///
58 /// // Remove a book.
59 /// books.remove("The Odyssey");
60 ///
61 /// // Iterate over everything.
62 /// for book in &books {
63 ///     println!("{book}");
64 /// }
65 /// ```
66 ///
67 /// A `BTreeSet` with a known list of items can be initialized from an array:
68 ///
69 /// ```
70 /// use std::collections::BTreeSet;
71 ///
72 /// let set = BTreeSet::from([1, 2, 3]);
73 /// ```
74 #[derive(Hash, PartialEq, Eq, Ord, PartialOrd)]
75 #[stable(feature = "rust1", since = "1.0.0")]
76 #[cfg_attr(not(test), rustc_diagnostic_item = "BTreeSet")]
77 pub struct BTreeSet<T> {
78     map: BTreeMap<T, ()>,
79 }
80
81 #[stable(feature = "rust1", since = "1.0.0")]
82 impl<T: Clone> Clone for BTreeSet<T> {
83     fn clone(&self) -> Self {
84         BTreeSet { map: self.map.clone() }
85     }
86
87     fn clone_from(&mut self, other: &Self) {
88         self.map.clone_from(&other.map);
89     }
90 }
91
92 /// An iterator over the items of a `BTreeSet`.
93 ///
94 /// This `struct` is created by the [`iter`] method on [`BTreeSet`].
95 /// See its documentation for more.
96 ///
97 /// [`iter`]: BTreeSet::iter
98 #[must_use = "iterators are lazy and do nothing unless consumed"]
99 #[stable(feature = "rust1", since = "1.0.0")]
100 pub struct Iter<'a, T: 'a> {
101     iter: Keys<'a, T, ()>,
102 }
103
104 #[stable(feature = "collection_debug", since = "1.17.0")]
105 impl<T: fmt::Debug> fmt::Debug for Iter<'_, T> {
106     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
107         f.debug_tuple("Iter").field(&self.iter.clone()).finish()
108     }
109 }
110
111 /// An owning iterator over the items of a `BTreeSet`.
112 ///
113 /// This `struct` is created by the [`into_iter`] method on [`BTreeSet`]
114 /// (provided by the [`IntoIterator`] trait). See its documentation for more.
115 ///
116 /// [`into_iter`]: BTreeSet#method.into_iter
117 /// [`IntoIterator`]: core::iter::IntoIterator
118 #[stable(feature = "rust1", since = "1.0.0")]
119 #[derive(Debug)]
120 pub struct IntoIter<T> {
121     iter: super::map::IntoIter<T, ()>,
122 }
123
124 /// An iterator over a sub-range of items in a `BTreeSet`.
125 ///
126 /// This `struct` is created by the [`range`] method on [`BTreeSet`].
127 /// See its documentation for more.
128 ///
129 /// [`range`]: BTreeSet::range
130 #[must_use = "iterators are lazy and do nothing unless consumed"]
131 #[derive(Debug)]
132 #[stable(feature = "btree_range", since = "1.17.0")]
133 pub struct Range<'a, T: 'a> {
134     iter: super::map::Range<'a, T, ()>,
135 }
136
137 /// A lazy iterator producing elements in the difference of `BTreeSet`s.
138 ///
139 /// This `struct` is created by the [`difference`] method on [`BTreeSet`].
140 /// See its documentation for more.
141 ///
142 /// [`difference`]: BTreeSet::difference
143 #[must_use = "this returns the difference as an iterator, \
144               without modifying either input set"]
145 #[stable(feature = "rust1", since = "1.0.0")]
146 pub struct Difference<'a, T: 'a> {
147     inner: DifferenceInner<'a, T>,
148 }
149 #[derive(Debug)]
150 enum DifferenceInner<'a, T: 'a> {
151     Stitch {
152         // iterate all of `self` and some of `other`, spotting matches along the way
153         self_iter: Iter<'a, T>,
154         other_iter: Peekable<Iter<'a, T>>,
155     },
156     Search {
157         // iterate `self`, look up in `other`
158         self_iter: Iter<'a, T>,
159         other_set: &'a BTreeSet<T>,
160     },
161     Iterate(Iter<'a, T>), // simply produce all elements in `self`
162 }
163
164 #[stable(feature = "collection_debug", since = "1.17.0")]
165 impl<T: fmt::Debug> fmt::Debug for Difference<'_, T> {
166     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
167         f.debug_tuple("Difference").field(&self.inner).finish()
168     }
169 }
170
171 /// A lazy iterator producing elements in the symmetric difference of `BTreeSet`s.
172 ///
173 /// This `struct` is created by the [`symmetric_difference`] method on
174 /// [`BTreeSet`]. See its documentation for more.
175 ///
176 /// [`symmetric_difference`]: BTreeSet::symmetric_difference
177 #[must_use = "this returns the difference as an iterator, \
178               without modifying either input set"]
179 #[stable(feature = "rust1", since = "1.0.0")]
180 pub struct SymmetricDifference<'a, T: 'a>(MergeIterInner<Iter<'a, T>>);
181
182 #[stable(feature = "collection_debug", since = "1.17.0")]
183 impl<T: fmt::Debug> fmt::Debug for SymmetricDifference<'_, T> {
184     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
185         f.debug_tuple("SymmetricDifference").field(&self.0).finish()
186     }
187 }
188
189 /// A lazy iterator producing elements in the intersection of `BTreeSet`s.
190 ///
191 /// This `struct` is created by the [`intersection`] method on [`BTreeSet`].
192 /// See its documentation for more.
193 ///
194 /// [`intersection`]: BTreeSet::intersection
195 #[must_use = "this returns the intersection as an iterator, \
196               without modifying either input set"]
197 #[stable(feature = "rust1", since = "1.0.0")]
198 pub struct Intersection<'a, T: 'a> {
199     inner: IntersectionInner<'a, T>,
200 }
201 #[derive(Debug)]
202 enum IntersectionInner<'a, T: 'a> {
203     Stitch {
204         // iterate similarly sized sets jointly, spotting matches along the way
205         a: Iter<'a, T>,
206         b: Iter<'a, T>,
207     },
208     Search {
209         // iterate a small set, look up in the large set
210         small_iter: Iter<'a, T>,
211         large_set: &'a BTreeSet<T>,
212     },
213     Answer(Option<&'a T>), // return a specific element or emptiness
214 }
215
216 #[stable(feature = "collection_debug", since = "1.17.0")]
217 impl<T: fmt::Debug> fmt::Debug for Intersection<'_, T> {
218     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
219         f.debug_tuple("Intersection").field(&self.inner).finish()
220     }
221 }
222
223 /// A lazy iterator producing elements in the union of `BTreeSet`s.
224 ///
225 /// This `struct` is created by the [`union`] method on [`BTreeSet`].
226 /// See its documentation for more.
227 ///
228 /// [`union`]: BTreeSet::union
229 #[must_use = "this returns the union as an iterator, \
230               without modifying either input set"]
231 #[stable(feature = "rust1", since = "1.0.0")]
232 pub struct Union<'a, T: 'a>(MergeIterInner<Iter<'a, T>>);
233
234 #[stable(feature = "collection_debug", since = "1.17.0")]
235 impl<T: fmt::Debug> fmt::Debug for Union<'_, T> {
236     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
237         f.debug_tuple("Union").field(&self.0).finish()
238     }
239 }
240
241 // This constant is used by functions that compare two sets.
242 // It estimates the relative size at which searching performs better
243 // than iterating, based on the benchmarks in
244 // https://github.com/ssomers/rust_bench_btreeset_intersection.
245 // It's used to divide rather than multiply sizes, to rule out overflow,
246 // and it's a power of two to make that division cheap.
247 const ITER_PERFORMANCE_TIPPING_SIZE_DIFF: usize = 16;
248
249 impl<T> BTreeSet<T> {
250     /// Makes a new, empty `BTreeSet`.
251     ///
252     /// Does not allocate anything on its own.
253     ///
254     /// # Examples
255     ///
256     /// ```
257     /// # #![allow(unused_mut)]
258     /// use std::collections::BTreeSet;
259     ///
260     /// let mut set: BTreeSet<i32> = BTreeSet::new();
261     /// ```
262     #[stable(feature = "rust1", since = "1.0.0")]
263     #[rustc_const_unstable(feature = "const_btree_new", issue = "71835")]
264     #[must_use]
265     pub const fn new() -> BTreeSet<T> {
266         BTreeSet { map: BTreeMap::new() }
267     }
268
269     /// Constructs a double-ended iterator over a sub-range of elements in the set.
270     /// The simplest way is to use the range syntax `min..max`, thus `range(min..max)` will
271     /// yield elements from min (inclusive) to max (exclusive).
272     /// The range may also be entered as `(Bound<T>, Bound<T>)`, so for example
273     /// `range((Excluded(4), Included(10)))` will yield a left-exclusive, right-inclusive
274     /// range from 4 to 10.
275     ///
276     /// # Examples
277     ///
278     /// ```
279     /// use std::collections::BTreeSet;
280     /// use std::ops::Bound::Included;
281     ///
282     /// let mut set = BTreeSet::new();
283     /// set.insert(3);
284     /// set.insert(5);
285     /// set.insert(8);
286     /// for &elem in set.range((Included(&4), Included(&8))) {
287     ///     println!("{elem}");
288     /// }
289     /// assert_eq!(Some(&5), set.range(4..).next());
290     /// ```
291     #[stable(feature = "btree_range", since = "1.17.0")]
292     pub fn range<K: ?Sized, R>(&self, range: R) -> Range<'_, T>
293     where
294         K: Ord,
295         T: Borrow<K> + Ord,
296         R: RangeBounds<K>,
297     {
298         Range { iter: self.map.range(range) }
299     }
300
301     /// Visits the elements representing the difference,
302     /// i.e., the elements that are in `self` but not in `other`,
303     /// in ascending order.
304     ///
305     /// # Examples
306     ///
307     /// ```
308     /// use std::collections::BTreeSet;
309     ///
310     /// let mut a = BTreeSet::new();
311     /// a.insert(1);
312     /// a.insert(2);
313     ///
314     /// let mut b = BTreeSet::new();
315     /// b.insert(2);
316     /// b.insert(3);
317     ///
318     /// let diff: Vec<_> = a.difference(&b).cloned().collect();
319     /// assert_eq!(diff, [1]);
320     /// ```
321     #[stable(feature = "rust1", since = "1.0.0")]
322     pub fn difference<'a>(&'a self, other: &'a BTreeSet<T>) -> Difference<'a, T>
323     where
324         T: Ord,
325     {
326         let (self_min, self_max) =
327             if let (Some(self_min), Some(self_max)) = (self.first(), self.last()) {
328                 (self_min, self_max)
329             } else {
330                 return Difference { inner: DifferenceInner::Iterate(self.iter()) };
331             };
332         let (other_min, other_max) =
333             if let (Some(other_min), Some(other_max)) = (other.first(), other.last()) {
334                 (other_min, other_max)
335             } else {
336                 return Difference { inner: DifferenceInner::Iterate(self.iter()) };
337             };
338         Difference {
339             inner: match (self_min.cmp(other_max), self_max.cmp(other_min)) {
340                 (Greater, _) | (_, Less) => DifferenceInner::Iterate(self.iter()),
341                 (Equal, _) => {
342                     let mut self_iter = self.iter();
343                     self_iter.next();
344                     DifferenceInner::Iterate(self_iter)
345                 }
346                 (_, Equal) => {
347                     let mut self_iter = self.iter();
348                     self_iter.next_back();
349                     DifferenceInner::Iterate(self_iter)
350                 }
351                 _ if self.len() <= other.len() / ITER_PERFORMANCE_TIPPING_SIZE_DIFF => {
352                     DifferenceInner::Search { self_iter: self.iter(), other_set: other }
353                 }
354                 _ => DifferenceInner::Stitch {
355                     self_iter: self.iter(),
356                     other_iter: other.iter().peekable(),
357                 },
358             },
359         }
360     }
361
362     /// Visits the elements representing the symmetric difference,
363     /// i.e., the elements that are in `self` or in `other` but not in both,
364     /// in ascending order.
365     ///
366     /// # Examples
367     ///
368     /// ```
369     /// use std::collections::BTreeSet;
370     ///
371     /// let mut a = BTreeSet::new();
372     /// a.insert(1);
373     /// a.insert(2);
374     ///
375     /// let mut b = BTreeSet::new();
376     /// b.insert(2);
377     /// b.insert(3);
378     ///
379     /// let sym_diff: Vec<_> = a.symmetric_difference(&b).cloned().collect();
380     /// assert_eq!(sym_diff, [1, 3]);
381     /// ```
382     #[stable(feature = "rust1", since = "1.0.0")]
383     pub fn symmetric_difference<'a>(&'a self, other: &'a BTreeSet<T>) -> SymmetricDifference<'a, T>
384     where
385         T: Ord,
386     {
387         SymmetricDifference(MergeIterInner::new(self.iter(), other.iter()))
388     }
389
390     /// Visits the elements representing the intersection,
391     /// i.e., the elements that are both in `self` and `other`,
392     /// in ascending order.
393     ///
394     /// # Examples
395     ///
396     /// ```
397     /// use std::collections::BTreeSet;
398     ///
399     /// let mut a = BTreeSet::new();
400     /// a.insert(1);
401     /// a.insert(2);
402     ///
403     /// let mut b = BTreeSet::new();
404     /// b.insert(2);
405     /// b.insert(3);
406     ///
407     /// let intersection: Vec<_> = a.intersection(&b).cloned().collect();
408     /// assert_eq!(intersection, [2]);
409     /// ```
410     #[stable(feature = "rust1", since = "1.0.0")]
411     pub fn intersection<'a>(&'a self, other: &'a BTreeSet<T>) -> Intersection<'a, T>
412     where
413         T: Ord,
414     {
415         let (self_min, self_max) =
416             if let (Some(self_min), Some(self_max)) = (self.first(), self.last()) {
417                 (self_min, self_max)
418             } else {
419                 return Intersection { inner: IntersectionInner::Answer(None) };
420             };
421         let (other_min, other_max) =
422             if let (Some(other_min), Some(other_max)) = (other.first(), other.last()) {
423                 (other_min, other_max)
424             } else {
425                 return Intersection { inner: IntersectionInner::Answer(None) };
426             };
427         Intersection {
428             inner: match (self_min.cmp(other_max), self_max.cmp(other_min)) {
429                 (Greater, _) | (_, Less) => IntersectionInner::Answer(None),
430                 (Equal, _) => IntersectionInner::Answer(Some(self_min)),
431                 (_, Equal) => IntersectionInner::Answer(Some(self_max)),
432                 _ if self.len() <= other.len() / ITER_PERFORMANCE_TIPPING_SIZE_DIFF => {
433                     IntersectionInner::Search { small_iter: self.iter(), large_set: other }
434                 }
435                 _ if other.len() <= self.len() / ITER_PERFORMANCE_TIPPING_SIZE_DIFF => {
436                     IntersectionInner::Search { small_iter: other.iter(), large_set: self }
437                 }
438                 _ => IntersectionInner::Stitch { a: self.iter(), b: other.iter() },
439             },
440         }
441     }
442
443     /// Visits the elements representing the union,
444     /// i.e., all the elements in `self` or `other`, without duplicates,
445     /// in ascending order.
446     ///
447     /// # Examples
448     ///
449     /// ```
450     /// use std::collections::BTreeSet;
451     ///
452     /// let mut a = BTreeSet::new();
453     /// a.insert(1);
454     ///
455     /// let mut b = BTreeSet::new();
456     /// b.insert(2);
457     ///
458     /// let union: Vec<_> = a.union(&b).cloned().collect();
459     /// assert_eq!(union, [1, 2]);
460     /// ```
461     #[stable(feature = "rust1", since = "1.0.0")]
462     pub fn union<'a>(&'a self, other: &'a BTreeSet<T>) -> Union<'a, T>
463     where
464         T: Ord,
465     {
466         Union(MergeIterInner::new(self.iter(), other.iter()))
467     }
468
469     /// Clears the set, removing all elements.
470     ///
471     /// # Examples
472     ///
473     /// ```
474     /// use std::collections::BTreeSet;
475     ///
476     /// let mut v = BTreeSet::new();
477     /// v.insert(1);
478     /// v.clear();
479     /// assert!(v.is_empty());
480     /// ```
481     #[stable(feature = "rust1", since = "1.0.0")]
482     pub fn clear(&mut self) {
483         self.map.clear()
484     }
485
486     /// Returns `true` if the set contains an element equal to the value.
487     ///
488     /// The value may be any borrowed form of the set's element type,
489     /// but the ordering on the borrowed form *must* match the
490     /// ordering on the element type.
491     ///
492     /// # Examples
493     ///
494     /// ```
495     /// use std::collections::BTreeSet;
496     ///
497     /// let set = BTreeSet::from([1, 2, 3]);
498     /// assert_eq!(set.contains(&1), true);
499     /// assert_eq!(set.contains(&4), false);
500     /// ```
501     #[stable(feature = "rust1", since = "1.0.0")]
502     pub fn contains<Q: ?Sized>(&self, value: &Q) -> bool
503     where
504         T: Borrow<Q> + Ord,
505         Q: Ord,
506     {
507         self.map.contains_key(value)
508     }
509
510     /// Returns a reference to the element in the set, if any, that is equal to
511     /// the value.
512     ///
513     /// The value may be any borrowed form of the set's element type,
514     /// but the ordering on the borrowed form *must* match the
515     /// ordering on the element type.
516     ///
517     /// # Examples
518     ///
519     /// ```
520     /// use std::collections::BTreeSet;
521     ///
522     /// let set = BTreeSet::from([1, 2, 3]);
523     /// assert_eq!(set.get(&2), Some(&2));
524     /// assert_eq!(set.get(&4), None);
525     /// ```
526     #[stable(feature = "set_recovery", since = "1.9.0")]
527     pub fn get<Q: ?Sized>(&self, value: &Q) -> Option<&T>
528     where
529         T: Borrow<Q> + Ord,
530         Q: Ord,
531     {
532         Recover::get(&self.map, value)
533     }
534
535     /// Returns `true` if `self` has no elements in common with `other`.
536     /// This is equivalent to checking for an empty intersection.
537     ///
538     /// # Examples
539     ///
540     /// ```
541     /// use std::collections::BTreeSet;
542     ///
543     /// let a = BTreeSet::from([1, 2, 3]);
544     /// let mut b = BTreeSet::new();
545     ///
546     /// assert_eq!(a.is_disjoint(&b), true);
547     /// b.insert(4);
548     /// assert_eq!(a.is_disjoint(&b), true);
549     /// b.insert(1);
550     /// assert_eq!(a.is_disjoint(&b), false);
551     /// ```
552     #[must_use]
553     #[stable(feature = "rust1", since = "1.0.0")]
554     pub fn is_disjoint(&self, other: &BTreeSet<T>) -> bool
555     where
556         T: Ord,
557     {
558         self.intersection(other).next().is_none()
559     }
560
561     /// Returns `true` if the set is a subset of another,
562     /// i.e., `other` contains at least all the elements in `self`.
563     ///
564     /// # Examples
565     ///
566     /// ```
567     /// use std::collections::BTreeSet;
568     ///
569     /// let sup = BTreeSet::from([1, 2, 3]);
570     /// let mut set = BTreeSet::new();
571     ///
572     /// assert_eq!(set.is_subset(&sup), true);
573     /// set.insert(2);
574     /// assert_eq!(set.is_subset(&sup), true);
575     /// set.insert(4);
576     /// assert_eq!(set.is_subset(&sup), false);
577     /// ```
578     #[must_use]
579     #[stable(feature = "rust1", since = "1.0.0")]
580     pub fn is_subset(&self, other: &BTreeSet<T>) -> bool
581     where
582         T: Ord,
583     {
584         // Same result as self.difference(other).next().is_none()
585         // but the code below is faster (hugely in some cases).
586         if self.len() > other.len() {
587             return false;
588         }
589         let (self_min, self_max) =
590             if let (Some(self_min), Some(self_max)) = (self.first(), self.last()) {
591                 (self_min, self_max)
592             } else {
593                 return true; // self is empty
594             };
595         let (other_min, other_max) =
596             if let (Some(other_min), Some(other_max)) = (other.first(), other.last()) {
597                 (other_min, other_max)
598             } else {
599                 return false; // other is empty
600             };
601         let mut self_iter = self.iter();
602         match self_min.cmp(other_min) {
603             Less => return false,
604             Equal => {
605                 self_iter.next();
606             }
607             Greater => (),
608         }
609         match self_max.cmp(other_max) {
610             Greater => return false,
611             Equal => {
612                 self_iter.next_back();
613             }
614             Less => (),
615         }
616         if self_iter.len() <= other.len() / ITER_PERFORMANCE_TIPPING_SIZE_DIFF {
617             for next in self_iter {
618                 if !other.contains(next) {
619                     return false;
620                 }
621             }
622         } else {
623             let mut other_iter = other.iter();
624             other_iter.next();
625             other_iter.next_back();
626             let mut self_next = self_iter.next();
627             while let Some(self1) = self_next {
628                 match other_iter.next().map_or(Less, |other1| self1.cmp(other1)) {
629                     Less => return false,
630                     Equal => self_next = self_iter.next(),
631                     Greater => (),
632                 }
633             }
634         }
635         true
636     }
637
638     /// Returns `true` if the set is a superset of another,
639     /// i.e., `self` contains at least all the elements in `other`.
640     ///
641     /// # Examples
642     ///
643     /// ```
644     /// use std::collections::BTreeSet;
645     ///
646     /// let sub = BTreeSet::from([1, 2]);
647     /// let mut set = BTreeSet::new();
648     ///
649     /// assert_eq!(set.is_superset(&sub), false);
650     ///
651     /// set.insert(0);
652     /// set.insert(1);
653     /// assert_eq!(set.is_superset(&sub), false);
654     ///
655     /// set.insert(2);
656     /// assert_eq!(set.is_superset(&sub), true);
657     /// ```
658     #[must_use]
659     #[stable(feature = "rust1", since = "1.0.0")]
660     pub fn is_superset(&self, other: &BTreeSet<T>) -> bool
661     where
662         T: Ord,
663     {
664         other.is_subset(self)
665     }
666
667     /// Returns a reference to the first element in the set, if any.
668     /// This element is always the minimum of all elements in the set.
669     ///
670     /// # Examples
671     ///
672     /// Basic usage:
673     ///
674     /// ```
675     /// #![feature(map_first_last)]
676     /// use std::collections::BTreeSet;
677     ///
678     /// let mut set = BTreeSet::new();
679     /// assert_eq!(set.first(), None);
680     /// set.insert(1);
681     /// assert_eq!(set.first(), Some(&1));
682     /// set.insert(2);
683     /// assert_eq!(set.first(), Some(&1));
684     /// ```
685     #[must_use]
686     #[unstable(feature = "map_first_last", issue = "62924")]
687     pub fn first(&self) -> Option<&T>
688     where
689         T: Ord,
690     {
691         self.map.first_key_value().map(|(k, _)| k)
692     }
693
694     /// Returns a reference to the last element in the set, if any.
695     /// This element is always the maximum of all elements in the set.
696     ///
697     /// # Examples
698     ///
699     /// Basic usage:
700     ///
701     /// ```
702     /// #![feature(map_first_last)]
703     /// use std::collections::BTreeSet;
704     ///
705     /// let mut set = BTreeSet::new();
706     /// assert_eq!(set.last(), None);
707     /// set.insert(1);
708     /// assert_eq!(set.last(), Some(&1));
709     /// set.insert(2);
710     /// assert_eq!(set.last(), Some(&2));
711     /// ```
712     #[must_use]
713     #[unstable(feature = "map_first_last", issue = "62924")]
714     pub fn last(&self) -> Option<&T>
715     where
716         T: Ord,
717     {
718         self.map.last_key_value().map(|(k, _)| k)
719     }
720
721     /// Removes the first element from the set and returns it, if any.
722     /// The first element is always the minimum element in the set.
723     ///
724     /// # Examples
725     ///
726     /// ```
727     /// #![feature(map_first_last)]
728     /// use std::collections::BTreeSet;
729     ///
730     /// let mut set = BTreeSet::new();
731     ///
732     /// set.insert(1);
733     /// while let Some(n) = set.pop_first() {
734     ///     assert_eq!(n, 1);
735     /// }
736     /// assert!(set.is_empty());
737     /// ```
738     #[unstable(feature = "map_first_last", issue = "62924")]
739     pub fn pop_first(&mut self) -> Option<T>
740     where
741         T: Ord,
742     {
743         self.map.pop_first().map(|kv| kv.0)
744     }
745
746     /// Removes the last element from the set and returns it, if any.
747     /// The last element is always the maximum element in the set.
748     ///
749     /// # Examples
750     ///
751     /// ```
752     /// #![feature(map_first_last)]
753     /// use std::collections::BTreeSet;
754     ///
755     /// let mut set = BTreeSet::new();
756     ///
757     /// set.insert(1);
758     /// while let Some(n) = set.pop_last() {
759     ///     assert_eq!(n, 1);
760     /// }
761     /// assert!(set.is_empty());
762     /// ```
763     #[unstable(feature = "map_first_last", issue = "62924")]
764     pub fn pop_last(&mut self) -> Option<T>
765     where
766         T: Ord,
767     {
768         self.map.pop_last().map(|kv| kv.0)
769     }
770
771     /// Adds a value to the set.
772     ///
773     /// Returns whether the value was newly inserted. That is:
774     ///
775     /// - If the set did not previously contain an equal value, `true` is
776     ///   returned.
777     /// - If the set already contained an equal value, `false` is returned, and
778     ///   the entry is not updated.
779     ///
780     /// See the [module-level documentation] for more.
781     ///
782     /// [module-level documentation]: index.html#insert-and-complex-keys
783     ///
784     /// # Examples
785     ///
786     /// ```
787     /// use std::collections::BTreeSet;
788     ///
789     /// let mut set = BTreeSet::new();
790     ///
791     /// assert_eq!(set.insert(2), true);
792     /// assert_eq!(set.insert(2), false);
793     /// assert_eq!(set.len(), 1);
794     /// ```
795     #[stable(feature = "rust1", since = "1.0.0")]
796     pub fn insert(&mut self, value: T) -> bool
797     where
798         T: Ord,
799     {
800         self.map.insert(value, ()).is_none()
801     }
802
803     /// Adds a value to the set, replacing the existing element, if any, that is
804     /// equal to the value. Returns the replaced element.
805     ///
806     /// # Examples
807     ///
808     /// ```
809     /// use std::collections::BTreeSet;
810     ///
811     /// let mut set = BTreeSet::new();
812     /// set.insert(Vec::<i32>::new());
813     ///
814     /// assert_eq!(set.get(&[][..]).unwrap().capacity(), 0);
815     /// set.replace(Vec::with_capacity(10));
816     /// assert_eq!(set.get(&[][..]).unwrap().capacity(), 10);
817     /// ```
818     #[stable(feature = "set_recovery", since = "1.9.0")]
819     pub fn replace(&mut self, value: T) -> Option<T>
820     where
821         T: Ord,
822     {
823         Recover::replace(&mut self.map, value)
824     }
825
826     /// If the set contains an element equal to the value, removes it from the
827     /// set and drops it. Returns whether such an element was present.
828     ///
829     /// The value may be any borrowed form of the set's element type,
830     /// but the ordering on the borrowed form *must* match the
831     /// ordering on the element type.
832     ///
833     /// # Examples
834     ///
835     /// ```
836     /// use std::collections::BTreeSet;
837     ///
838     /// let mut set = BTreeSet::new();
839     ///
840     /// set.insert(2);
841     /// assert_eq!(set.remove(&2), true);
842     /// assert_eq!(set.remove(&2), false);
843     /// ```
844     #[stable(feature = "rust1", since = "1.0.0")]
845     pub fn remove<Q: ?Sized>(&mut self, value: &Q) -> bool
846     where
847         T: Borrow<Q> + Ord,
848         Q: Ord,
849     {
850         self.map.remove(value).is_some()
851     }
852
853     /// Removes and returns the element in the set, if any, that is equal to
854     /// the value.
855     ///
856     /// The value may be any borrowed form of the set's element type,
857     /// but the ordering on the borrowed form *must* match the
858     /// ordering on the element type.
859     ///
860     /// # Examples
861     ///
862     /// ```
863     /// use std::collections::BTreeSet;
864     ///
865     /// let mut set = BTreeSet::from([1, 2, 3]);
866     /// assert_eq!(set.take(&2), Some(2));
867     /// assert_eq!(set.take(&2), None);
868     /// ```
869     #[stable(feature = "set_recovery", since = "1.9.0")]
870     pub fn take<Q: ?Sized>(&mut self, value: &Q) -> Option<T>
871     where
872         T: Borrow<Q> + Ord,
873         Q: Ord,
874     {
875         Recover::take(&mut self.map, value)
876     }
877
878     /// Retains only the elements specified by the predicate.
879     ///
880     /// In other words, remove all elements `e` for which `f(&e)` returns `false`.
881     /// The elements are visited in ascending order.
882     ///
883     /// # Examples
884     ///
885     /// ```
886     /// use std::collections::BTreeSet;
887     ///
888     /// let mut set = BTreeSet::from([1, 2, 3, 4, 5, 6]);
889     /// // Keep only the even numbers.
890     /// set.retain(|&k| k % 2 == 0);
891     /// assert!(set.iter().eq([2, 4, 6].iter()));
892     /// ```
893     #[stable(feature = "btree_retain", since = "1.53.0")]
894     pub fn retain<F>(&mut self, mut f: F)
895     where
896         T: Ord,
897         F: FnMut(&T) -> bool,
898     {
899         self.drain_filter(|v| !f(v));
900     }
901
902     /// Moves all elements from `other` into `self`, leaving `other` empty.
903     ///
904     /// # Examples
905     ///
906     /// ```
907     /// use std::collections::BTreeSet;
908     ///
909     /// let mut a = BTreeSet::new();
910     /// a.insert(1);
911     /// a.insert(2);
912     /// a.insert(3);
913     ///
914     /// let mut b = BTreeSet::new();
915     /// b.insert(3);
916     /// b.insert(4);
917     /// b.insert(5);
918     ///
919     /// a.append(&mut b);
920     ///
921     /// assert_eq!(a.len(), 5);
922     /// assert_eq!(b.len(), 0);
923     ///
924     /// assert!(a.contains(&1));
925     /// assert!(a.contains(&2));
926     /// assert!(a.contains(&3));
927     /// assert!(a.contains(&4));
928     /// assert!(a.contains(&5));
929     /// ```
930     #[stable(feature = "btree_append", since = "1.11.0")]
931     pub fn append(&mut self, other: &mut Self)
932     where
933         T: Ord,
934     {
935         self.map.append(&mut other.map);
936     }
937
938     /// Splits the collection into two at the value. Returns a new collection
939     /// with all elements greater than or equal to the value.
940     ///
941     /// # Examples
942     ///
943     /// Basic usage:
944     ///
945     /// ```
946     /// use std::collections::BTreeSet;
947     ///
948     /// let mut a = BTreeSet::new();
949     /// a.insert(1);
950     /// a.insert(2);
951     /// a.insert(3);
952     /// a.insert(17);
953     /// a.insert(41);
954     ///
955     /// let b = a.split_off(&3);
956     ///
957     /// assert_eq!(a.len(), 2);
958     /// assert_eq!(b.len(), 3);
959     ///
960     /// assert!(a.contains(&1));
961     /// assert!(a.contains(&2));
962     ///
963     /// assert!(b.contains(&3));
964     /// assert!(b.contains(&17));
965     /// assert!(b.contains(&41));
966     /// ```
967     #[stable(feature = "btree_split_off", since = "1.11.0")]
968     pub fn split_off<Q: ?Sized + Ord>(&mut self, value: &Q) -> Self
969     where
970         T: Borrow<Q> + Ord,
971     {
972         BTreeSet { map: self.map.split_off(value) }
973     }
974
975     /// Creates an iterator that visits all elements in ascending order and
976     /// uses a closure to determine if an element should be removed.
977     ///
978     /// If the closure returns `true`, the element is removed from the set and
979     /// yielded. If the closure returns `false`, or panics, the element remains
980     /// in the set and will not be yielded.
981     ///
982     /// If the iterator is only partially consumed or not consumed at all, each
983     /// of the remaining elements is still subjected to the closure and removed
984     /// and dropped if it returns `true`.
985     ///
986     /// It is unspecified how many more elements will be subjected to the
987     /// closure if a panic occurs in the closure, or if a panic occurs while
988     /// dropping an element, or if the `DrainFilter` itself is leaked.
989     ///
990     /// # Examples
991     ///
992     /// Splitting a set into even and odd values, reusing the original set:
993     ///
994     /// ```
995     /// #![feature(btree_drain_filter)]
996     /// use std::collections::BTreeSet;
997     ///
998     /// let mut set: BTreeSet<i32> = (0..8).collect();
999     /// let evens: BTreeSet<_> = set.drain_filter(|v| v % 2 == 0).collect();
1000     /// let odds = set;
1001     /// assert_eq!(evens.into_iter().collect::<Vec<_>>(), vec![0, 2, 4, 6]);
1002     /// assert_eq!(odds.into_iter().collect::<Vec<_>>(), vec![1, 3, 5, 7]);
1003     /// ```
1004     #[unstable(feature = "btree_drain_filter", issue = "70530")]
1005     pub fn drain_filter<'a, F>(&'a mut self, pred: F) -> DrainFilter<'a, T, F>
1006     where
1007         T: Ord,
1008         F: 'a + FnMut(&T) -> bool,
1009     {
1010         DrainFilter { pred, inner: self.map.drain_filter_inner() }
1011     }
1012
1013     /// Gets an iterator that visits the elements in the `BTreeSet` in ascending
1014     /// order.
1015     ///
1016     /// # Examples
1017     ///
1018     /// ```
1019     /// use std::collections::BTreeSet;
1020     ///
1021     /// let set = BTreeSet::from([1, 2, 3]);
1022     /// let mut set_iter = set.iter();
1023     /// assert_eq!(set_iter.next(), Some(&1));
1024     /// assert_eq!(set_iter.next(), Some(&2));
1025     /// assert_eq!(set_iter.next(), Some(&3));
1026     /// assert_eq!(set_iter.next(), None);
1027     /// ```
1028     ///
1029     /// Values returned by the iterator are returned in ascending order:
1030     ///
1031     /// ```
1032     /// use std::collections::BTreeSet;
1033     ///
1034     /// let set = BTreeSet::from([3, 1, 2]);
1035     /// let mut set_iter = set.iter();
1036     /// assert_eq!(set_iter.next(), Some(&1));
1037     /// assert_eq!(set_iter.next(), Some(&2));
1038     /// assert_eq!(set_iter.next(), Some(&3));
1039     /// assert_eq!(set_iter.next(), None);
1040     /// ```
1041     #[stable(feature = "rust1", since = "1.0.0")]
1042     pub fn iter(&self) -> Iter<'_, T> {
1043         Iter { iter: self.map.keys() }
1044     }
1045
1046     /// Returns the number of elements in the set.
1047     ///
1048     /// # Examples
1049     ///
1050     /// ```
1051     /// use std::collections::BTreeSet;
1052     ///
1053     /// let mut v = BTreeSet::new();
1054     /// assert_eq!(v.len(), 0);
1055     /// v.insert(1);
1056     /// assert_eq!(v.len(), 1);
1057     /// ```
1058     #[must_use]
1059     #[stable(feature = "rust1", since = "1.0.0")]
1060     #[rustc_const_unstable(feature = "const_btree_new", issue = "71835")]
1061     pub const fn len(&self) -> usize {
1062         self.map.len()
1063     }
1064
1065     /// Returns `true` if the set contains no elements.
1066     ///
1067     /// # Examples
1068     ///
1069     /// ```
1070     /// use std::collections::BTreeSet;
1071     ///
1072     /// let mut v = BTreeSet::new();
1073     /// assert!(v.is_empty());
1074     /// v.insert(1);
1075     /// assert!(!v.is_empty());
1076     /// ```
1077     #[must_use]
1078     #[stable(feature = "rust1", since = "1.0.0")]
1079     #[rustc_const_unstable(feature = "const_btree_new", issue = "71835")]
1080     pub const fn is_empty(&self) -> bool {
1081         self.len() == 0
1082     }
1083 }
1084
1085 #[stable(feature = "rust1", since = "1.0.0")]
1086 impl<T: Ord> FromIterator<T> for BTreeSet<T> {
1087     fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> BTreeSet<T> {
1088         let mut inputs: Vec<_> = iter.into_iter().collect();
1089
1090         if inputs.is_empty() {
1091             return BTreeSet::new();
1092         }
1093
1094         // use stable sort to preserve the insertion order.
1095         inputs.sort();
1096         BTreeSet::from_sorted_iter(inputs.into_iter())
1097     }
1098 }
1099
1100 impl<T: Ord> BTreeSet<T> {
1101     fn from_sorted_iter<I: Iterator<Item = T>>(iter: I) -> BTreeSet<T> {
1102         let iter = iter.map(|k| (k, ()));
1103         let map = BTreeMap::bulk_build_from_sorted_iter(iter);
1104         BTreeSet { map }
1105     }
1106 }
1107
1108 #[stable(feature = "std_collections_from_array", since = "1.56.0")]
1109 impl<T: Ord, const N: usize> From<[T; N]> for BTreeSet<T> {
1110     /// Converts a `[T; N]` into a `BTreeSet<T>`.
1111     ///
1112     /// ```
1113     /// use std::collections::BTreeSet;
1114     ///
1115     /// let set1 = BTreeSet::from([1, 2, 3, 4]);
1116     /// let set2: BTreeSet<_> = [1, 2, 3, 4].into();
1117     /// assert_eq!(set1, set2);
1118     /// ```
1119     fn from(mut arr: [T; N]) -> Self {
1120         if N == 0 {
1121             return BTreeSet::new();
1122         }
1123
1124         // use stable sort to preserve the insertion order.
1125         arr.sort();
1126         let iter = IntoIterator::into_iter(arr).map(|k| (k, ()));
1127         let map = BTreeMap::bulk_build_from_sorted_iter(iter);
1128         BTreeSet { map }
1129     }
1130 }
1131
1132 #[stable(feature = "rust1", since = "1.0.0")]
1133 impl<T> IntoIterator for BTreeSet<T> {
1134     type Item = T;
1135     type IntoIter = IntoIter<T>;
1136
1137     /// Gets an iterator for moving out the `BTreeSet`'s contents.
1138     ///
1139     /// # Examples
1140     ///
1141     /// ```
1142     /// use std::collections::BTreeSet;
1143     ///
1144     /// let set = BTreeSet::from([1, 2, 3, 4]);
1145     ///
1146     /// let v: Vec<_> = set.into_iter().collect();
1147     /// assert_eq!(v, [1, 2, 3, 4]);
1148     /// ```
1149     fn into_iter(self) -> IntoIter<T> {
1150         IntoIter { iter: self.map.into_iter() }
1151     }
1152 }
1153
1154 #[stable(feature = "rust1", since = "1.0.0")]
1155 impl<'a, T> IntoIterator for &'a BTreeSet<T> {
1156     type Item = &'a T;
1157     type IntoIter = Iter<'a, T>;
1158
1159     fn into_iter(self) -> Iter<'a, T> {
1160         self.iter()
1161     }
1162 }
1163
1164 /// An iterator produced by calling `drain_filter` on BTreeSet.
1165 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1166 pub struct DrainFilter<'a, T, F>
1167 where
1168     T: 'a,
1169     F: 'a + FnMut(&T) -> bool,
1170 {
1171     pred: F,
1172     inner: super::map::DrainFilterInner<'a, T, ()>,
1173 }
1174
1175 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1176 impl<T, F> Drop for DrainFilter<'_, T, F>
1177 where
1178     F: FnMut(&T) -> bool,
1179 {
1180     fn drop(&mut self) {
1181         self.for_each(drop);
1182     }
1183 }
1184
1185 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1186 impl<T, F> fmt::Debug for DrainFilter<'_, T, F>
1187 where
1188     T: fmt::Debug,
1189     F: FnMut(&T) -> bool,
1190 {
1191     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1192         f.debug_tuple("DrainFilter").field(&self.inner.peek().map(|(k, _)| k)).finish()
1193     }
1194 }
1195
1196 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1197 impl<'a, T, F> Iterator for DrainFilter<'_, T, F>
1198 where
1199     F: 'a + FnMut(&T) -> bool,
1200 {
1201     type Item = T;
1202
1203     fn next(&mut self) -> Option<T> {
1204         let pred = &mut self.pred;
1205         let mut mapped_pred = |k: &T, _v: &mut ()| pred(k);
1206         self.inner.next(&mut mapped_pred).map(|(k, _)| k)
1207     }
1208
1209     fn size_hint(&self) -> (usize, Option<usize>) {
1210         self.inner.size_hint()
1211     }
1212 }
1213
1214 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1215 impl<T, F> FusedIterator for DrainFilter<'_, T, F> where F: FnMut(&T) -> bool {}
1216
1217 #[stable(feature = "rust1", since = "1.0.0")]
1218 impl<T: Ord> Extend<T> for BTreeSet<T> {
1219     #[inline]
1220     fn extend<Iter: IntoIterator<Item = T>>(&mut self, iter: Iter) {
1221         iter.into_iter().for_each(move |elem| {
1222             self.insert(elem);
1223         });
1224     }
1225
1226     #[inline]
1227     fn extend_one(&mut self, elem: T) {
1228         self.insert(elem);
1229     }
1230 }
1231
1232 #[stable(feature = "extend_ref", since = "1.2.0")]
1233 impl<'a, T: 'a + Ord + Copy> Extend<&'a T> for BTreeSet<T> {
1234     fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
1235         self.extend(iter.into_iter().cloned());
1236     }
1237
1238     #[inline]
1239     fn extend_one(&mut self, &elem: &'a T) {
1240         self.insert(elem);
1241     }
1242 }
1243
1244 #[stable(feature = "rust1", since = "1.0.0")]
1245 impl<T> Default for BTreeSet<T> {
1246     /// Creates an empty `BTreeSet`.
1247     fn default() -> BTreeSet<T> {
1248         BTreeSet::new()
1249     }
1250 }
1251
1252 #[stable(feature = "rust1", since = "1.0.0")]
1253 impl<T: Ord + Clone> Sub<&BTreeSet<T>> for &BTreeSet<T> {
1254     type Output = BTreeSet<T>;
1255
1256     /// Returns the difference of `self` and `rhs` as a new `BTreeSet<T>`.
1257     ///
1258     /// # Examples
1259     ///
1260     /// ```
1261     /// use std::collections::BTreeSet;
1262     ///
1263     /// let a = BTreeSet::from([1, 2, 3]);
1264     /// let b = BTreeSet::from([3, 4, 5]);
1265     ///
1266     /// let result = &a - &b;
1267     /// assert_eq!(result, BTreeSet::from([1, 2]));
1268     /// ```
1269     fn sub(self, rhs: &BTreeSet<T>) -> BTreeSet<T> {
1270         BTreeSet::from_sorted_iter(self.difference(rhs).cloned())
1271     }
1272 }
1273
1274 #[stable(feature = "rust1", since = "1.0.0")]
1275 impl<T: Ord + Clone> BitXor<&BTreeSet<T>> for &BTreeSet<T> {
1276     type Output = BTreeSet<T>;
1277
1278     /// Returns the symmetric difference of `self` and `rhs` as a new `BTreeSet<T>`.
1279     ///
1280     /// # Examples
1281     ///
1282     /// ```
1283     /// use std::collections::BTreeSet;
1284     ///
1285     /// let a = BTreeSet::from([1, 2, 3]);
1286     /// let b = BTreeSet::from([2, 3, 4]);
1287     ///
1288     /// let result = &a ^ &b;
1289     /// assert_eq!(result, BTreeSet::from([1, 4]));
1290     /// ```
1291     fn bitxor(self, rhs: &BTreeSet<T>) -> BTreeSet<T> {
1292         BTreeSet::from_sorted_iter(self.symmetric_difference(rhs).cloned())
1293     }
1294 }
1295
1296 #[stable(feature = "rust1", since = "1.0.0")]
1297 impl<T: Ord + Clone> BitAnd<&BTreeSet<T>> for &BTreeSet<T> {
1298     type Output = BTreeSet<T>;
1299
1300     /// Returns the intersection of `self` and `rhs` as a new `BTreeSet<T>`.
1301     ///
1302     /// # Examples
1303     ///
1304     /// ```
1305     /// use std::collections::BTreeSet;
1306     ///
1307     /// let a = BTreeSet::from([1, 2, 3]);
1308     /// let b = BTreeSet::from([2, 3, 4]);
1309     ///
1310     /// let result = &a & &b;
1311     /// assert_eq!(result, BTreeSet::from([2, 3]));
1312     /// ```
1313     fn bitand(self, rhs: &BTreeSet<T>) -> BTreeSet<T> {
1314         BTreeSet::from_sorted_iter(self.intersection(rhs).cloned())
1315     }
1316 }
1317
1318 #[stable(feature = "rust1", since = "1.0.0")]
1319 impl<T: Ord + Clone> BitOr<&BTreeSet<T>> for &BTreeSet<T> {
1320     type Output = BTreeSet<T>;
1321
1322     /// Returns the union of `self` and `rhs` as a new `BTreeSet<T>`.
1323     ///
1324     /// # Examples
1325     ///
1326     /// ```
1327     /// use std::collections::BTreeSet;
1328     ///
1329     /// let a = BTreeSet::from([1, 2, 3]);
1330     /// let b = BTreeSet::from([3, 4, 5]);
1331     ///
1332     /// let result = &a | &b;
1333     /// assert_eq!(result, BTreeSet::from([1, 2, 3, 4, 5]));
1334     /// ```
1335     fn bitor(self, rhs: &BTreeSet<T>) -> BTreeSet<T> {
1336         BTreeSet::from_sorted_iter(self.union(rhs).cloned())
1337     }
1338 }
1339
1340 #[stable(feature = "rust1", since = "1.0.0")]
1341 impl<T: Debug> Debug for BTreeSet<T> {
1342     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1343         f.debug_set().entries(self.iter()).finish()
1344     }
1345 }
1346
1347 #[stable(feature = "rust1", since = "1.0.0")]
1348 impl<T> Clone for Iter<'_, T> {
1349     fn clone(&self) -> Self {
1350         Iter { iter: self.iter.clone() }
1351     }
1352 }
1353 #[stable(feature = "rust1", since = "1.0.0")]
1354 impl<'a, T> Iterator for Iter<'a, T> {
1355     type Item = &'a T;
1356
1357     fn next(&mut self) -> Option<&'a T> {
1358         self.iter.next()
1359     }
1360
1361     fn size_hint(&self) -> (usize, Option<usize>) {
1362         self.iter.size_hint()
1363     }
1364
1365     fn last(mut self) -> Option<&'a T> {
1366         self.next_back()
1367     }
1368
1369     fn min(mut self) -> Option<&'a T> {
1370         self.next()
1371     }
1372
1373     fn max(mut self) -> Option<&'a T> {
1374         self.next_back()
1375     }
1376 }
1377 #[stable(feature = "rust1", since = "1.0.0")]
1378 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
1379     fn next_back(&mut self) -> Option<&'a T> {
1380         self.iter.next_back()
1381     }
1382 }
1383 #[stable(feature = "rust1", since = "1.0.0")]
1384 impl<T> ExactSizeIterator for Iter<'_, T> {
1385     fn len(&self) -> usize {
1386         self.iter.len()
1387     }
1388 }
1389
1390 #[stable(feature = "fused", since = "1.26.0")]
1391 impl<T> FusedIterator for Iter<'_, T> {}
1392
1393 #[stable(feature = "rust1", since = "1.0.0")]
1394 impl<T> Iterator for IntoIter<T> {
1395     type Item = T;
1396
1397     fn next(&mut self) -> Option<T> {
1398         self.iter.next().map(|(k, _)| k)
1399     }
1400
1401     fn size_hint(&self) -> (usize, Option<usize>) {
1402         self.iter.size_hint()
1403     }
1404 }
1405 #[stable(feature = "rust1", since = "1.0.0")]
1406 impl<T> DoubleEndedIterator for IntoIter<T> {
1407     fn next_back(&mut self) -> Option<T> {
1408         self.iter.next_back().map(|(k, _)| k)
1409     }
1410 }
1411 #[stable(feature = "rust1", since = "1.0.0")]
1412 impl<T> ExactSizeIterator for IntoIter<T> {
1413     fn len(&self) -> usize {
1414         self.iter.len()
1415     }
1416 }
1417
1418 #[stable(feature = "fused", since = "1.26.0")]
1419 impl<T> FusedIterator for IntoIter<T> {}
1420
1421 #[stable(feature = "btree_range", since = "1.17.0")]
1422 impl<T> Clone for Range<'_, T> {
1423     fn clone(&self) -> Self {
1424         Range { iter: self.iter.clone() }
1425     }
1426 }
1427
1428 #[stable(feature = "btree_range", since = "1.17.0")]
1429 impl<'a, T> Iterator for Range<'a, T> {
1430     type Item = &'a T;
1431
1432     fn next(&mut self) -> Option<&'a T> {
1433         self.iter.next().map(|(k, _)| k)
1434     }
1435
1436     fn last(mut self) -> Option<&'a T> {
1437         self.next_back()
1438     }
1439
1440     fn min(mut self) -> Option<&'a T> {
1441         self.next()
1442     }
1443
1444     fn max(mut self) -> Option<&'a T> {
1445         self.next_back()
1446     }
1447 }
1448
1449 #[stable(feature = "btree_range", since = "1.17.0")]
1450 impl<'a, T> DoubleEndedIterator for Range<'a, T> {
1451     fn next_back(&mut self) -> Option<&'a T> {
1452         self.iter.next_back().map(|(k, _)| k)
1453     }
1454 }
1455
1456 #[stable(feature = "fused", since = "1.26.0")]
1457 impl<T> FusedIterator for Range<'_, T> {}
1458
1459 #[stable(feature = "rust1", since = "1.0.0")]
1460 impl<T> Clone for Difference<'_, T> {
1461     fn clone(&self) -> Self {
1462         Difference {
1463             inner: match &self.inner {
1464                 DifferenceInner::Stitch { self_iter, other_iter } => DifferenceInner::Stitch {
1465                     self_iter: self_iter.clone(),
1466                     other_iter: other_iter.clone(),
1467                 },
1468                 DifferenceInner::Search { self_iter, other_set } => {
1469                     DifferenceInner::Search { self_iter: self_iter.clone(), other_set }
1470                 }
1471                 DifferenceInner::Iterate(iter) => DifferenceInner::Iterate(iter.clone()),
1472             },
1473         }
1474     }
1475 }
1476 #[stable(feature = "rust1", since = "1.0.0")]
1477 impl<'a, T: Ord> Iterator for Difference<'a, T> {
1478     type Item = &'a T;
1479
1480     fn next(&mut self) -> Option<&'a T> {
1481         match &mut self.inner {
1482             DifferenceInner::Stitch { self_iter, other_iter } => {
1483                 let mut self_next = self_iter.next()?;
1484                 loop {
1485                     match other_iter.peek().map_or(Less, |other_next| self_next.cmp(other_next)) {
1486                         Less => return Some(self_next),
1487                         Equal => {
1488                             self_next = self_iter.next()?;
1489                             other_iter.next();
1490                         }
1491                         Greater => {
1492                             other_iter.next();
1493                         }
1494                     }
1495                 }
1496             }
1497             DifferenceInner::Search { self_iter, other_set } => loop {
1498                 let self_next = self_iter.next()?;
1499                 if !other_set.contains(&self_next) {
1500                     return Some(self_next);
1501                 }
1502             },
1503             DifferenceInner::Iterate(iter) => iter.next(),
1504         }
1505     }
1506
1507     fn size_hint(&self) -> (usize, Option<usize>) {
1508         let (self_len, other_len) = match &self.inner {
1509             DifferenceInner::Stitch { self_iter, other_iter } => {
1510                 (self_iter.len(), other_iter.len())
1511             }
1512             DifferenceInner::Search { self_iter, other_set } => (self_iter.len(), other_set.len()),
1513             DifferenceInner::Iterate(iter) => (iter.len(), 0),
1514         };
1515         (self_len.saturating_sub(other_len), Some(self_len))
1516     }
1517
1518     fn min(mut self) -> Option<&'a T> {
1519         self.next()
1520     }
1521 }
1522
1523 #[stable(feature = "fused", since = "1.26.0")]
1524 impl<T: Ord> FusedIterator for Difference<'_, T> {}
1525
1526 #[stable(feature = "rust1", since = "1.0.0")]
1527 impl<T> Clone for SymmetricDifference<'_, T> {
1528     fn clone(&self) -> Self {
1529         SymmetricDifference(self.0.clone())
1530     }
1531 }
1532 #[stable(feature = "rust1", since = "1.0.0")]
1533 impl<'a, T: Ord> Iterator for SymmetricDifference<'a, T> {
1534     type Item = &'a T;
1535
1536     fn next(&mut self) -> Option<&'a T> {
1537         loop {
1538             let (a_next, b_next) = self.0.nexts(Self::Item::cmp);
1539             if a_next.and(b_next).is_none() {
1540                 return a_next.or(b_next);
1541             }
1542         }
1543     }
1544
1545     fn size_hint(&self) -> (usize, Option<usize>) {
1546         let (a_len, b_len) = self.0.lens();
1547         // No checked_add, because even if a and b refer to the same set,
1548         // and T is a zero-sized type, the storage overhead of sets limits
1549         // the number of elements to less than half the range of usize.
1550         (0, Some(a_len + b_len))
1551     }
1552
1553     fn min(mut self) -> Option<&'a T> {
1554         self.next()
1555     }
1556 }
1557
1558 #[stable(feature = "fused", since = "1.26.0")]
1559 impl<T: Ord> FusedIterator for SymmetricDifference<'_, T> {}
1560
1561 #[stable(feature = "rust1", since = "1.0.0")]
1562 impl<T> Clone for Intersection<'_, T> {
1563     fn clone(&self) -> Self {
1564         Intersection {
1565             inner: match &self.inner {
1566                 IntersectionInner::Stitch { a, b } => {
1567                     IntersectionInner::Stitch { a: a.clone(), b: b.clone() }
1568                 }
1569                 IntersectionInner::Search { small_iter, large_set } => {
1570                     IntersectionInner::Search { small_iter: small_iter.clone(), large_set }
1571                 }
1572                 IntersectionInner::Answer(answer) => IntersectionInner::Answer(*answer),
1573             },
1574         }
1575     }
1576 }
1577 #[stable(feature = "rust1", since = "1.0.0")]
1578 impl<'a, T: Ord> Iterator for Intersection<'a, T> {
1579     type Item = &'a T;
1580
1581     fn next(&mut self) -> Option<&'a T> {
1582         match &mut self.inner {
1583             IntersectionInner::Stitch { a, b } => {
1584                 let mut a_next = a.next()?;
1585                 let mut b_next = b.next()?;
1586                 loop {
1587                     match a_next.cmp(b_next) {
1588                         Less => a_next = a.next()?,
1589                         Greater => b_next = b.next()?,
1590                         Equal => return Some(a_next),
1591                     }
1592                 }
1593             }
1594             IntersectionInner::Search { small_iter, large_set } => loop {
1595                 let small_next = small_iter.next()?;
1596                 if large_set.contains(&small_next) {
1597                     return Some(small_next);
1598                 }
1599             },
1600             IntersectionInner::Answer(answer) => answer.take(),
1601         }
1602     }
1603
1604     fn size_hint(&self) -> (usize, Option<usize>) {
1605         match &self.inner {
1606             IntersectionInner::Stitch { a, b } => (0, Some(min(a.len(), b.len()))),
1607             IntersectionInner::Search { small_iter, .. } => (0, Some(small_iter.len())),
1608             IntersectionInner::Answer(None) => (0, Some(0)),
1609             IntersectionInner::Answer(Some(_)) => (1, Some(1)),
1610         }
1611     }
1612
1613     fn min(mut self) -> Option<&'a T> {
1614         self.next()
1615     }
1616 }
1617
1618 #[stable(feature = "fused", since = "1.26.0")]
1619 impl<T: Ord> FusedIterator for Intersection<'_, T> {}
1620
1621 #[stable(feature = "rust1", since = "1.0.0")]
1622 impl<T> Clone for Union<'_, T> {
1623     fn clone(&self) -> Self {
1624         Union(self.0.clone())
1625     }
1626 }
1627 #[stable(feature = "rust1", since = "1.0.0")]
1628 impl<'a, T: Ord> Iterator for Union<'a, T> {
1629     type Item = &'a T;
1630
1631     fn next(&mut self) -> Option<&'a T> {
1632         let (a_next, b_next) = self.0.nexts(Self::Item::cmp);
1633         a_next.or(b_next)
1634     }
1635
1636     fn size_hint(&self) -> (usize, Option<usize>) {
1637         let (a_len, b_len) = self.0.lens();
1638         // No checked_add - see SymmetricDifference::size_hint.
1639         (max(a_len, b_len), Some(a_len + b_len))
1640     }
1641
1642     fn min(mut self) -> Option<&'a T> {
1643         self.next()
1644     }
1645 }
1646
1647 #[stable(feature = "fused", since = "1.26.0")]
1648 impl<T: Ord> FusedIterator for Union<'_, T> {}
1649
1650 #[cfg(test)]
1651 mod tests;