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