Skip to main content

alloc/collections/btree/
set.rs

1use core::borrow::Borrow;
2use core::cmp::Ordering::{self, Equal, Greater, Less};
3use core::cmp::{max, min};
4use core::fmt::{self, Debug};
5use core::hash::{Hash, Hasher};
6use core::iter::{FusedIterator, Peekable, TrustedLen};
7use core::mem::ManuallyDrop;
8use core::ops::{BitAnd, BitOr, BitXor, Bound, RangeBounds, Sub};
9
10use super::map::{self, BTreeMap, Keys};
11use super::merge_iter::MergeIterInner;
12use super::set_val::SetValZST;
13use crate::alloc::{Allocator, Global};
14use crate::vec::Vec;
15
16mod entry;
17
18#[unstable(feature = "btree_set_entry", issue = "133549")]
19pub use self::entry::{Entry, OccupiedEntry, VacantEntry};
20
21/// An ordered set based on a B-Tree.
22///
23/// See [`BTreeMap`]'s documentation for a detailed discussion of this collection's performance
24/// benefits and drawbacks.
25///
26/// It is a logic error for an item to be modified in such a way that the item's ordering relative
27/// to any other item, as determined by the [`Ord`] trait, changes while it is in the set. This is
28/// normally only possible through [`Cell`], [`RefCell`], global state, I/O, or unsafe code.
29/// The behavior resulting from such a logic error is not specified, but will be encapsulated to the
30/// `BTreeSet` that observed the logic error and not result in undefined behavior. This could
31/// include panics, incorrect results, aborts, memory leaks, and non-termination.
32///
33/// Iterators returned by [`BTreeSet::iter`] and [`BTreeSet::into_iter`] produce their items in order, and take worst-case
34/// logarithmic and amortized constant time per item returned.
35///
36/// [`Cell`]: core::cell::Cell
37/// [`RefCell`]: core::cell::RefCell
38///
39/// # Examples
40///
41/// ```
42/// use std::collections::BTreeSet;
43///
44/// // Type inference lets us omit an explicit type signature (which
45/// // would be `BTreeSet<&str>` in this example).
46/// let mut books = BTreeSet::new();
47///
48/// // Add some books.
49/// books.insert("A Dance With Dragons");
50/// books.insert("To Kill a Mockingbird");
51/// books.insert("The Odyssey");
52/// books.insert("The Great Gatsby");
53///
54/// // Check for a specific one.
55/// if !books.contains("The Winds of Winter") {
56///     println!("We have {} books, but The Winds of Winter ain't one.",
57///              books.len());
58/// }
59///
60/// // Remove a book.
61/// books.remove("The Odyssey");
62///
63/// // Iterate over everything.
64/// for book in &books {
65///     println!("{book}");
66/// }
67/// ```
68///
69/// A `BTreeSet` with a known list of items can be initialized from an array:
70///
71/// ```
72/// use std::collections::BTreeSet;
73///
74/// let set = BTreeSet::from([1, 2, 3]);
75/// ```
76#[stable(feature = "rust1", since = "1.0.0")]
77#[cfg_attr(not(test), rustc_diagnostic_item = "BTreeSet")]
78pub struct BTreeSet<
79    T,
80    #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator + Clone = Global,
81> {
82    map: BTreeMap<T, SetValZST, A>,
83}
84
85#[stable(feature = "rust1", since = "1.0.0")]
86impl<T: Hash, A: Allocator + Clone> Hash for BTreeSet<T, A> {
87    fn hash<H: Hasher>(&self, state: &mut H) {
88        self.map.hash(state)
89    }
90}
91
92#[stable(feature = "rust1", since = "1.0.0")]
93impl<T: PartialEq, A: Allocator + Clone> PartialEq for BTreeSet<T, A> {
94    fn eq(&self, other: &BTreeSet<T, A>) -> bool {
95        self.map.eq(&other.map)
96    }
97}
98
99#[stable(feature = "rust1", since = "1.0.0")]
100impl<T: Eq, A: Allocator + Clone> Eq for BTreeSet<T, A> {}
101
102#[stable(feature = "rust1", since = "1.0.0")]
103impl<T: PartialOrd, A: Allocator + Clone> PartialOrd for BTreeSet<T, A> {
104    fn partial_cmp(&self, other: &BTreeSet<T, A>) -> Option<Ordering> {
105        self.map.partial_cmp(&other.map)
106    }
107}
108
109#[stable(feature = "rust1", since = "1.0.0")]
110impl<T: Ord, A: Allocator + Clone> Ord for BTreeSet<T, A> {
111    fn cmp(&self, other: &BTreeSet<T, A>) -> Ordering {
112        self.map.cmp(&other.map)
113    }
114}
115
116#[stable(feature = "rust1", since = "1.0.0")]
117impl<T: Clone, A: Allocator + Clone> Clone for BTreeSet<T, A> {
118    fn clone(&self) -> Self {
119        BTreeSet { map: self.map.clone() }
120    }
121
122    fn clone_from(&mut self, source: &Self) {
123        self.map.clone_from(&source.map);
124    }
125}
126
127/// An iterator over the items of a `BTreeSet`.
128///
129/// This `struct` is created by the [`iter`] method on [`BTreeSet`].
130/// See its documentation for more.
131///
132/// [`iter`]: BTreeSet::iter
133#[must_use = "iterators are lazy and do nothing unless consumed"]
134#[stable(feature = "rust1", since = "1.0.0")]
135pub struct Iter<'a, T: 'a> {
136    iter: Keys<'a, T, SetValZST>,
137}
138
139#[stable(feature = "collection_debug", since = "1.17.0")]
140impl<T: fmt::Debug> fmt::Debug for Iter<'_, T> {
141    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
142        f.debug_tuple("Iter").field(&self.iter).finish()
143    }
144}
145
146/// An owning iterator over the items of a `BTreeSet` in ascending order.
147///
148/// This `struct` is created by the [`into_iter`] method on [`BTreeSet`]
149/// (provided by the [`IntoIterator`] trait). See its documentation for more.
150///
151/// [`into_iter`]: BTreeSet#method.into_iter
152#[stable(feature = "rust1", since = "1.0.0")]
153#[derive(Debug)]
154pub struct IntoIter<
155    T,
156    #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator + Clone = Global,
157> {
158    iter: super::map::IntoIter<T, SetValZST, A>,
159}
160
161/// An iterator over a sub-range of items in a `BTreeSet`.
162///
163/// This `struct` is created by the [`range`] method on [`BTreeSet`].
164/// See its documentation for more.
165///
166/// [`range`]: BTreeSet::range
167#[must_use = "iterators are lazy and do nothing unless consumed"]
168#[derive(Debug)]
169#[stable(feature = "btree_range", since = "1.17.0")]
170pub struct Range<'a, T: 'a> {
171    iter: super::map::Range<'a, T, SetValZST>,
172}
173
174/// A lazy iterator producing elements in the difference of `BTreeSet`s.
175///
176/// This `struct` is created by the [`difference`] method on [`BTreeSet`].
177/// See its documentation for more.
178///
179/// [`difference`]: BTreeSet::difference
180#[must_use = "this returns the difference as an iterator, \
181              without modifying either input set"]
182#[stable(feature = "rust1", since = "1.0.0")]
183pub struct Difference<
184    'a,
185    T: 'a,
186    #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator + Clone = Global,
187> {
188    inner: DifferenceInner<'a, T, A>,
189}
190enum DifferenceInner<'a, T: 'a, A: Allocator + Clone> {
191    Stitch {
192        // iterate all of `self` and some of `other`, spotting matches along the way
193        self_iter: Iter<'a, T>,
194        other_iter: Peekable<Iter<'a, T>>,
195    },
196    Search {
197        // iterate `self`, look up in `other`
198        self_iter: Iter<'a, T>,
199        other_set: &'a BTreeSet<T, A>,
200    },
201    Iterate(Iter<'a, T>), // simply produce all elements in `self`
202}
203
204// Explicit Debug impl necessary because of issue #26925
205impl<T: Debug, A: Allocator + Clone> Debug for DifferenceInner<'_, T, A> {
206    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
207        match self {
208            DifferenceInner::Stitch { self_iter, other_iter } => f
209                .debug_struct("Stitch")
210                .field("self_iter", self_iter)
211                .field("other_iter", other_iter)
212                .finish(),
213            DifferenceInner::Search { self_iter, other_set } => f
214                .debug_struct("Search")
215                .field("self_iter", self_iter)
216                .field("other_iter", other_set)
217                .finish(),
218            DifferenceInner::Iterate(x) => f.debug_tuple("Iterate").field(x).finish(),
219        }
220    }
221}
222
223#[stable(feature = "collection_debug", since = "1.17.0")]
224impl<T: fmt::Debug, A: Allocator + Clone> fmt::Debug for Difference<'_, T, A> {
225    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
226        f.debug_tuple("Difference").field(&self.inner).finish()
227    }
228}
229
230/// A lazy iterator producing elements in the symmetric difference of `BTreeSet`s.
231///
232/// This `struct` is created by the [`symmetric_difference`] method on
233/// [`BTreeSet`]. See its documentation for more.
234///
235/// [`symmetric_difference`]: BTreeSet::symmetric_difference
236#[must_use = "this returns the difference as an iterator, \
237              without modifying either input set"]
238#[stable(feature = "rust1", since = "1.0.0")]
239pub struct SymmetricDifference<'a, T: 'a>(MergeIterInner<Iter<'a, T>>);
240
241#[stable(feature = "collection_debug", since = "1.17.0")]
242impl<T: fmt::Debug> fmt::Debug for SymmetricDifference<'_, T> {
243    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
244        f.debug_tuple("SymmetricDifference").field(&self.0).finish()
245    }
246}
247
248/// A lazy iterator producing elements in the intersection of `BTreeSet`s.
249///
250/// This `struct` is created by the [`intersection`] method on [`BTreeSet`].
251/// See its documentation for more.
252///
253/// [`intersection`]: BTreeSet::intersection
254#[must_use = "this returns the intersection as an iterator, \
255              without modifying either input set"]
256#[stable(feature = "rust1", since = "1.0.0")]
257pub struct Intersection<
258    'a,
259    T: 'a,
260    #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator + Clone = Global,
261> {
262    inner: IntersectionInner<'a, T, A>,
263}
264enum IntersectionInner<'a, T: 'a, A: Allocator + Clone> {
265    Stitch {
266        // iterate similarly sized sets jointly, spotting matches along the way
267        a: Iter<'a, T>,
268        b: Iter<'a, T>,
269    },
270    Search {
271        // iterate a small set, look up in the large set
272        small_iter: Iter<'a, T>,
273        large_set: &'a BTreeSet<T, A>,
274    },
275    Answer(Option<&'a T>), // return a specific element or emptiness
276}
277
278// Explicit Debug impl necessary because of issue #26925
279impl<T: Debug, A: Allocator + Clone> Debug for IntersectionInner<'_, T, A> {
280    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
281        match self {
282            IntersectionInner::Stitch { a, b } => {
283                f.debug_struct("Stitch").field("a", a).field("b", b).finish()
284            }
285            IntersectionInner::Search { small_iter, large_set } => f
286                .debug_struct("Search")
287                .field("small_iter", small_iter)
288                .field("large_set", large_set)
289                .finish(),
290            IntersectionInner::Answer(x) => f.debug_tuple("Answer").field(x).finish(),
291        }
292    }
293}
294
295#[stable(feature = "collection_debug", since = "1.17.0")]
296impl<T: Debug, A: Allocator + Clone> Debug for Intersection<'_, T, A> {
297    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
298        f.debug_tuple("Intersection").field(&self.inner).finish()
299    }
300}
301
302/// A lazy iterator producing elements in the union of `BTreeSet`s.
303///
304/// This `struct` is created by the [`union`] method on [`BTreeSet`].
305/// See its documentation for more.
306///
307/// [`union`]: BTreeSet::union
308#[must_use = "this returns the union as an iterator, \
309              without modifying either input set"]
310#[stable(feature = "rust1", since = "1.0.0")]
311pub struct Union<'a, T: 'a>(MergeIterInner<Iter<'a, T>>);
312
313#[stable(feature = "collection_debug", since = "1.17.0")]
314impl<T: fmt::Debug> fmt::Debug for Union<'_, T> {
315    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
316        f.debug_tuple("Union").field(&self.0).finish()
317    }
318}
319
320// This constant is used by functions that compare two sets.
321// It estimates the relative size at which searching performs better
322// than iterating, based on the benchmarks in
323// https://github.com/ssomers/rust_bench_btreeset_intersection.
324// It's used to divide rather than multiply sizes, to rule out overflow,
325// and it's a power of two to make that division cheap.
326const ITER_PERFORMANCE_TIPPING_SIZE_DIFF: usize = 16;
327
328impl<T> BTreeSet<T> {
329    /// Makes a new, empty `BTreeSet`.
330    ///
331    /// Does not allocate anything on its own.
332    ///
333    /// # Examples
334    ///
335    /// ```
336    /// # #![allow(unused_mut)]
337    /// use std::collections::BTreeSet;
338    ///
339    /// let mut set: BTreeSet<i32> = BTreeSet::new();
340    /// ```
341    #[stable(feature = "rust1", since = "1.0.0")]
342    #[rustc_const_stable(feature = "const_btree_new", since = "1.66.0")]
343    #[must_use]
344    pub const fn new() -> BTreeSet<T> {
345        BTreeSet { map: BTreeMap::new() }
346    }
347}
348
349impl<T, A: Allocator + Clone> BTreeSet<T, A> {
350    /// Makes a new `BTreeSet` with a reasonable choice of B.
351    ///
352    /// # Examples
353    ///
354    /// ```
355    /// # #![allow(unused_mut)]
356    /// # #![feature(allocator_api)]
357    /// # #![feature(btreemap_alloc)]
358    /// use std::collections::BTreeSet;
359    /// use std::alloc::Global;
360    ///
361    /// let mut set: BTreeSet<i32> = BTreeSet::new_in(Global);
362    /// ```
363    #[unstable(feature = "btreemap_alloc", issue = "32838")]
364    #[must_use]
365    pub const fn new_in(alloc: A) -> BTreeSet<T, A> {
366        BTreeSet { map: BTreeMap::new_in(alloc) }
367    }
368
369    /// Constructs a double-ended iterator over a sub-range of elements in the set.
370    /// The simplest way is to use the range syntax `min..max`, thus `range(min..max)` will
371    /// yield elements from min (inclusive) to max (exclusive).
372    /// The range may also be entered as `(Bound<T>, Bound<T>)`, so for example
373    /// `range((Excluded(4), Included(10)))` will yield a left-exclusive, right-inclusive
374    /// range from 4 to 10.
375    ///
376    /// # Panics
377    ///
378    /// Panics if range `start > end`.
379    /// Panics if range `start == end` and both bounds are `Excluded`.
380    ///
381    /// # Examples
382    ///
383    /// ```
384    /// use std::collections::BTreeSet;
385    /// use std::ops::Bound::Included;
386    ///
387    /// let mut set = BTreeSet::new();
388    /// set.insert(3);
389    /// set.insert(5);
390    /// set.insert(8);
391    /// for &elem in set.range((Included(&4), Included(&8))) {
392    ///     println!("{elem}");
393    /// }
394    /// assert_eq!(Some(&5), set.range(4..).next());
395    /// ```
396    #[stable(feature = "btree_range", since = "1.17.0")]
397    pub fn range<K: ?Sized, R>(&self, range: R) -> Range<'_, T>
398    where
399        K: Ord,
400        T: Borrow<K> + Ord,
401        R: RangeBounds<K>,
402    {
403        Range { iter: self.map.range(range) }
404    }
405
406    /// Visits the elements representing the difference,
407    /// i.e., the elements that are in `self` but not in `other`,
408    /// in ascending order.
409    ///
410    /// # Examples
411    ///
412    /// ```
413    /// use std::collections::BTreeSet;
414    ///
415    /// let mut a = BTreeSet::new();
416    /// a.insert(1);
417    /// a.insert(2);
418    ///
419    /// let mut b = BTreeSet::new();
420    /// b.insert(2);
421    /// b.insert(3);
422    ///
423    /// let diff: Vec<_> = a.difference(&b).cloned().collect();
424    /// assert_eq!(diff, [1]);
425    /// ```
426    #[stable(feature = "rust1", since = "1.0.0")]
427    pub fn difference<'a>(&'a self, other: &'a BTreeSet<T, A>) -> Difference<'a, T, A>
428    where
429        T: Ord,
430    {
431        if let Some(self_min) = self.first()
432            && let Some(self_max) = self.last()
433            && let Some(other_min) = other.first()
434            && let Some(other_max) = other.last()
435        {
436            Difference {
437                inner: match (self_min.cmp(other_max), self_max.cmp(other_min)) {
438                    (Greater, _) | (_, Less) => DifferenceInner::Iterate(self.iter()),
439                    (Equal, _) => {
440                        let mut self_iter = self.iter();
441                        self_iter.next();
442                        DifferenceInner::Iterate(self_iter)
443                    }
444                    (_, Equal) => {
445                        let mut self_iter = self.iter();
446                        self_iter.next_back();
447                        DifferenceInner::Iterate(self_iter)
448                    }
449                    _ if self.len() <= other.len() / ITER_PERFORMANCE_TIPPING_SIZE_DIFF => {
450                        DifferenceInner::Search { self_iter: self.iter(), other_set: other }
451                    }
452                    _ => DifferenceInner::Stitch {
453                        self_iter: self.iter(),
454                        other_iter: other.iter().peekable(),
455                    },
456                },
457            }
458        } else {
459            Difference { inner: DifferenceInner::Iterate(self.iter()) }
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")]
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")]
515    pub fn intersection<'a>(&'a self, other: &'a BTreeSet<T, A>) -> Intersection<'a, T, A>
516    where
517        T: Ord,
518    {
519        if let Some(self_min) = self.first()
520            && let Some(self_max) = self.last()
521            && let Some(other_min) = other.first()
522            && let Some(other_max) = other.last()
523        {
524            Intersection {
525                inner: match (self_min.cmp(other_max), self_max.cmp(other_min)) {
526                    (Greater, _) | (_, Less) => IntersectionInner::Answer(None),
527                    (Equal, _) => IntersectionInner::Answer(Some(self_min)),
528                    (_, Equal) => IntersectionInner::Answer(Some(self_max)),
529                    _ if self.len() <= other.len() / ITER_PERFORMANCE_TIPPING_SIZE_DIFF => {
530                        IntersectionInner::Search { small_iter: self.iter(), large_set: other }
531                    }
532                    _ if other.len() <= self.len() / ITER_PERFORMANCE_TIPPING_SIZE_DIFF => {
533                        IntersectionInner::Search { small_iter: other.iter(), large_set: self }
534                    }
535                    _ => IntersectionInner::Stitch { a: self.iter(), b: other.iter() },
536                },
537            }
538        } else {
539            Intersection { inner: IntersectionInner::Answer(None) }
540        }
541    }
542
543    /// Visits the elements representing the union,
544    /// i.e., all the elements in `self` or `other`, without duplicates,
545    /// in ascending order.
546    ///
547    /// # Examples
548    ///
549    /// ```
550    /// use std::collections::BTreeSet;
551    ///
552    /// let mut a = BTreeSet::new();
553    /// a.insert(1);
554    ///
555    /// let mut b = BTreeSet::new();
556    /// b.insert(2);
557    ///
558    /// let union: Vec<_> = a.union(&b).cloned().collect();
559    /// assert_eq!(union, [1, 2]);
560    /// ```
561    #[stable(feature = "rust1", since = "1.0.0")]
562    pub fn union<'a>(&'a self, other: &'a BTreeSet<T, A>) -> Union<'a, T>
563    where
564        T: Ord,
565    {
566        Union(MergeIterInner::new(self.iter(), other.iter()))
567    }
568
569    /// Clears the set, removing all elements.
570    ///
571    /// # Examples
572    ///
573    /// ```
574    /// use std::collections::BTreeSet;
575    ///
576    /// let mut v = BTreeSet::new();
577    /// v.insert(1);
578    /// v.clear();
579    /// assert!(v.is_empty());
580    /// ```
581    #[stable(feature = "rust1", since = "1.0.0")]
582    pub fn clear(&mut self)
583    where
584        A: Clone,
585    {
586        self.map.clear()
587    }
588
589    /// Returns `true` if the set contains an element equal to the value.
590    ///
591    /// The value may be any borrowed form of the set's element type,
592    /// but the ordering on the borrowed form *must* match the
593    /// ordering on the element type.
594    ///
595    /// # Examples
596    ///
597    /// ```
598    /// use std::collections::BTreeSet;
599    ///
600    /// let set = BTreeSet::from([1, 2, 3]);
601    /// assert_eq!(set.contains(&1), true);
602    /// assert_eq!(set.contains(&4), false);
603    /// ```
604    #[stable(feature = "rust1", since = "1.0.0")]
605    pub fn contains<Q: ?Sized>(&self, value: &Q) -> bool
606    where
607        T: Borrow<Q> + Ord,
608        Q: Ord,
609    {
610        self.map.contains_key(value)
611    }
612
613    /// Returns a reference to the element in the set, if any, that is equal to
614    /// the value.
615    ///
616    /// The value may be any borrowed form of the set's element type,
617    /// but the ordering on the borrowed form *must* match the
618    /// ordering on the element type.
619    ///
620    /// # Examples
621    ///
622    /// ```
623    /// use std::collections::BTreeSet;
624    ///
625    /// let set = BTreeSet::from([1, 2, 3]);
626    /// assert_eq!(set.get(&2), Some(&2));
627    /// assert_eq!(set.get(&4), None);
628    /// ```
629    #[stable(feature = "set_recovery", since = "1.9.0")]
630    pub fn get<Q: ?Sized>(&self, value: &Q) -> Option<&T>
631    where
632        T: Borrow<Q> + Ord,
633        Q: Ord,
634    {
635        self.map.get_key_value(value).map(|(k, _)| k)
636    }
637
638    /// Returns `true` if `self` has no elements in common with `other`.
639    /// This is equivalent to checking for an empty intersection.
640    ///
641    /// # Examples
642    ///
643    /// ```
644    /// use std::collections::BTreeSet;
645    ///
646    /// let a = BTreeSet::from([1, 2, 3]);
647    /// let mut b = BTreeSet::new();
648    ///
649    /// assert_eq!(a.is_disjoint(&b), true);
650    /// b.insert(4);
651    /// assert_eq!(a.is_disjoint(&b), true);
652    /// b.insert(1);
653    /// assert_eq!(a.is_disjoint(&b), false);
654    /// ```
655    #[must_use]
656    #[stable(feature = "rust1", since = "1.0.0")]
657    pub fn is_disjoint(&self, other: &BTreeSet<T, A>) -> bool
658    where
659        T: Ord,
660    {
661        self.intersection(other).next().is_none()
662    }
663
664    /// Returns `true` if the set is a subset of another,
665    /// i.e., `other` contains at least all the elements in `self`.
666    ///
667    /// # Examples
668    ///
669    /// ```
670    /// use std::collections::BTreeSet;
671    ///
672    /// let sup = BTreeSet::from([1, 2, 3]);
673    /// let mut set = BTreeSet::new();
674    ///
675    /// assert_eq!(set.is_subset(&sup), true);
676    /// set.insert(2);
677    /// assert_eq!(set.is_subset(&sup), true);
678    /// set.insert(4);
679    /// assert_eq!(set.is_subset(&sup), false);
680    /// ```
681    #[must_use]
682    #[stable(feature = "rust1", since = "1.0.0")]
683    pub fn is_subset(&self, other: &BTreeSet<T, A>) -> bool
684    where
685        T: Ord,
686    {
687        // Same result as self.difference(other).next().is_none()
688        // but the code below is faster (hugely in some cases).
689        if self.len() > other.len() {
690            return false; // self has more elements than other
691        }
692        let (Some(self_min), Some(self_max)) = (self.first(), self.last()) else {
693            return true; // self is empty
694        };
695        let (Some(other_min), Some(other_max)) = (other.first(), other.last()) else {
696            return false; // other is empty
697        };
698        let mut self_iter = self.iter();
699        match self_min.cmp(other_min) {
700            Less => return false, // other does not contain self_min
701            Equal => {
702                self_iter.next(); // self_min is contained in other, so remove it from consideration
703                // other_min is now not in self_iter (used below)
704            }
705            Greater => {} // other_min is not in self_iter (used below)
706        };
707
708        match self_max.cmp(other_max) {
709            Greater => return false, // other does not contain self_max
710            Equal => {
711                self_iter.next_back(); // self_max is contained in other, so remove it from consideration
712                // other_max is now not in self_iter (used below)
713            }
714            Less => {} // other_max is not in self_iter (used below)
715        };
716        if self_iter.len() <= other.len() / ITER_PERFORMANCE_TIPPING_SIZE_DIFF {
717            self_iter.all(|e| other.contains(e))
718        } else {
719            let mut other_iter = other.iter();
720            {
721                // remove other_min and other_max as they are not in self_iter (see above)
722                other_iter.next();
723                other_iter.next_back();
724            }
725            // custom `self_iter.all(|e| other.contains(e))`
726            self_iter.all(|self1| {
727                while let Some(other1) = other_iter.next() {
728                    match other1.cmp(self1) {
729                        // happens up to `ITER_PERFORMANCE_TIPPING_SIZE_DIFF * self.len() - 1` times
730                        Less => continue, // skip over elements that are smaller
731                        // happens `self.len()` times
732                        Equal => return true, // self1 is in other
733                        // happens only once
734                        Greater => return false, // self1 is not in other
735                    }
736                }
737                false
738            })
739        }
740    }
741
742    /// Returns `true` if the set is a superset of another,
743    /// i.e., `self` contains at least all the elements in `other`.
744    ///
745    /// # Examples
746    ///
747    /// ```
748    /// use std::collections::BTreeSet;
749    ///
750    /// let sub = BTreeSet::from([1, 2]);
751    /// let mut set = BTreeSet::new();
752    ///
753    /// assert_eq!(set.is_superset(&sub), false);
754    ///
755    /// set.insert(0);
756    /// set.insert(1);
757    /// assert_eq!(set.is_superset(&sub), false);
758    ///
759    /// set.insert(2);
760    /// assert_eq!(set.is_superset(&sub), true);
761    /// ```
762    #[must_use]
763    #[stable(feature = "rust1", since = "1.0.0")]
764    pub fn is_superset(&self, other: &BTreeSet<T, A>) -> bool
765    where
766        T: Ord,
767    {
768        other.is_subset(self)
769    }
770
771    /// Returns a reference to the first element in the set, if any.
772    /// This element is always the minimum of all elements in the set.
773    ///
774    /// # Examples
775    ///
776    /// Basic usage:
777    ///
778    /// ```
779    /// use std::collections::BTreeSet;
780    ///
781    /// let mut set = BTreeSet::new();
782    /// assert_eq!(set.first(), None);
783    /// set.insert(1);
784    /// assert_eq!(set.first(), Some(&1));
785    /// set.insert(2);
786    /// assert_eq!(set.first(), Some(&1));
787    /// ```
788    #[must_use]
789    #[stable(feature = "map_first_last", since = "1.66.0")]
790    #[rustc_confusables("front")]
791    pub fn first(&self) -> Option<&T>
792    where
793        T: Ord,
794    {
795        self.map.first_key_value().map(|(k, _)| k)
796    }
797
798    /// Returns a reference to the last element in the set, if any.
799    /// This element is always the maximum of all elements in the set.
800    ///
801    /// # Examples
802    ///
803    /// Basic usage:
804    ///
805    /// ```
806    /// use std::collections::BTreeSet;
807    ///
808    /// let mut set = BTreeSet::new();
809    /// assert_eq!(set.last(), None);
810    /// set.insert(1);
811    /// assert_eq!(set.last(), Some(&1));
812    /// set.insert(2);
813    /// assert_eq!(set.last(), Some(&2));
814    /// ```
815    #[must_use]
816    #[stable(feature = "map_first_last", since = "1.66.0")]
817    #[rustc_confusables("back")]
818    pub fn last(&self) -> Option<&T>
819    where
820        T: Ord,
821    {
822        self.map.last_key_value().map(|(k, _)| k)
823    }
824
825    /// Removes the first element from the set and returns it, if any.
826    /// The first element is always the minimum element in the set.
827    ///
828    /// # Examples
829    ///
830    /// ```
831    /// use std::collections::BTreeSet;
832    ///
833    /// let mut set = BTreeSet::new();
834    ///
835    /// set.insert(1);
836    /// while let Some(n) = set.pop_first() {
837    ///     assert_eq!(n, 1);
838    /// }
839    /// assert!(set.is_empty());
840    /// ```
841    #[stable(feature = "map_first_last", since = "1.66.0")]
842    pub fn pop_first(&mut self) -> Option<T>
843    where
844        T: Ord,
845    {
846        self.map.pop_first().map(|kv| kv.0)
847    }
848
849    /// Removes the last element from the set and returns it, if any.
850    /// The last element is always the maximum element in the set.
851    ///
852    /// # Examples
853    ///
854    /// ```
855    /// use std::collections::BTreeSet;
856    ///
857    /// let mut set = BTreeSet::new();
858    ///
859    /// set.insert(1);
860    /// while let Some(n) = set.pop_last() {
861    ///     assert_eq!(n, 1);
862    /// }
863    /// assert!(set.is_empty());
864    /// ```
865    #[stable(feature = "map_first_last", since = "1.66.0")]
866    pub fn pop_last(&mut self) -> Option<T>
867    where
868        T: Ord,
869    {
870        self.map.pop_last().map(|kv| kv.0)
871    }
872
873    /// Adds a value to the set.
874    ///
875    /// Returns whether the value was newly inserted. That is:
876    ///
877    /// - If the set did not previously contain an equal value, `true` is
878    ///   returned.
879    /// - If the set already contained an equal value, `false` is returned, and
880    ///   the entry is not updated.
881    ///
882    /// See the [module-level documentation] for more.
883    ///
884    /// [module-level documentation]: index.html#insert-and-complex-keys
885    ///
886    /// # Examples
887    ///
888    /// ```
889    /// use std::collections::BTreeSet;
890    ///
891    /// let mut set = BTreeSet::new();
892    ///
893    /// assert_eq!(set.insert(2), true);
894    /// assert_eq!(set.insert(2), false);
895    /// assert_eq!(set.len(), 1);
896    /// ```
897    #[stable(feature = "rust1", since = "1.0.0")]
898    #[rustc_confusables("push", "put")]
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")]
922    #[rustc_confusables("swap")]
923    pub fn replace(&mut self, value: T) -> Option<T>
924    where
925        T: Ord,
926    {
927        self.map.replace(value)
928    }
929
930    /// Inserts the given `value` into the set if it is not present, then
931    /// returns a reference to the value in the set.
932    ///
933    /// # Examples
934    ///
935    /// ```
936    /// #![feature(btree_set_entry)]
937    ///
938    /// use std::collections::BTreeSet;
939    ///
940    /// let mut set = BTreeSet::from([1, 2, 3]);
941    /// assert_eq!(set.len(), 3);
942    /// assert_eq!(set.get_or_insert(2), &2);
943    /// assert_eq!(set.get_or_insert(100), &100);
944    /// assert_eq!(set.len(), 4); // 100 was inserted
945    /// ```
946    #[inline]
947    #[unstable(feature = "btree_set_entry", issue = "133549")]
948    pub fn get_or_insert(&mut self, value: T) -> &T
949    where
950        T: Ord,
951    {
952        self.map.entry(value).insert_entry(SetValZST).into_key()
953    }
954
955    /// Inserts a value computed from `f` into the set if the given `value` is
956    /// not present, then returns a reference to the value in the set.
957    ///
958    /// # Examples
959    ///
960    /// ```
961    /// #![feature(btree_set_entry)]
962    ///
963    /// use std::collections::BTreeSet;
964    ///
965    /// let mut set: BTreeSet<String> = ["cat", "dog", "horse"]
966    ///     .iter().map(|&pet| pet.to_owned()).collect();
967    ///
968    /// assert_eq!(set.len(), 3);
969    /// for &pet in &["cat", "dog", "fish"] {
970    ///     let value = set.get_or_insert_with(pet, str::to_owned);
971    ///     assert_eq!(value, pet);
972    /// }
973    /// assert_eq!(set.len(), 4); // a new "fish" was inserted
974    /// ```
975    #[inline]
976    #[unstable(feature = "btree_set_entry", issue = "133549")]
977    pub fn get_or_insert_with<Q: ?Sized, F>(&mut self, value: &Q, f: F) -> &T
978    where
979        T: Borrow<Q> + Ord,
980        Q: Ord,
981        F: FnOnce(&Q) -> T,
982    {
983        self.map.get_or_insert_with(value, f)
984    }
985
986    /// Gets the given value's corresponding entry in the set for in-place manipulation.
987    ///
988    /// # Examples
989    ///
990    /// ```
991    /// #![feature(btree_set_entry)]
992    ///
993    /// use std::collections::BTreeSet;
994    /// use std::collections::btree_set::Entry::*;
995    ///
996    /// let mut singles = BTreeSet::new();
997    /// let mut dupes = BTreeSet::new();
998    ///
999    /// for ch in "a short treatise on fungi".chars() {
1000    ///     if let Vacant(dupe_entry) = dupes.entry(ch) {
1001    ///         // We haven't already seen a duplicate, so
1002    ///         // check if we've at least seen it once.
1003    ///         match singles.entry(ch) {
1004    ///             Vacant(single_entry) => {
1005    ///                 // We found a new character for the first time.
1006    ///                 single_entry.insert()
1007    ///             }
1008    ///             Occupied(single_entry) => {
1009    ///                 // We've already seen this once, "move" it to dupes.
1010    ///                 single_entry.remove();
1011    ///                 dupe_entry.insert();
1012    ///             }
1013    ///         }
1014    ///     }
1015    /// }
1016    ///
1017    /// assert!(!singles.contains(&'t') && dupes.contains(&'t'));
1018    /// assert!(singles.contains(&'u') && !dupes.contains(&'u'));
1019    /// assert!(!singles.contains(&'v') && !dupes.contains(&'v'));
1020    /// ```
1021    #[inline]
1022    #[unstable(feature = "btree_set_entry", issue = "133549")]
1023    pub fn entry(&mut self, value: T) -> Entry<'_, T, A>
1024    where
1025        T: Ord,
1026    {
1027        match self.map.entry(value) {
1028            map::Entry::Occupied(entry) => Entry::Occupied(OccupiedEntry { inner: entry }),
1029            map::Entry::Vacant(entry) => Entry::Vacant(VacantEntry { inner: entry }),
1030        }
1031    }
1032
1033    /// If the set contains an element equal to the value, removes it from the
1034    /// set and drops it. Returns whether such an element was present.
1035    ///
1036    /// The value may be any borrowed form of the set's element type,
1037    /// but the ordering on the borrowed form *must* match the
1038    /// ordering on the element type.
1039    ///
1040    /// # Examples
1041    ///
1042    /// ```
1043    /// use std::collections::BTreeSet;
1044    ///
1045    /// let mut set = BTreeSet::new();
1046    ///
1047    /// set.insert(2);
1048    /// assert_eq!(set.remove(&2), true);
1049    /// assert_eq!(set.remove(&2), false);
1050    /// ```
1051    #[stable(feature = "rust1", since = "1.0.0")]
1052    pub fn remove<Q: ?Sized>(&mut self, value: &Q) -> bool
1053    where
1054        T: Borrow<Q> + Ord,
1055        Q: Ord,
1056    {
1057        self.map.remove(value).is_some()
1058    }
1059
1060    /// Removes and returns the element in the set, if any, that is equal to
1061    /// the value.
1062    ///
1063    /// The value may be any borrowed form of the set's element type,
1064    /// but the ordering on the borrowed form *must* match the
1065    /// ordering on the element type.
1066    ///
1067    /// # Examples
1068    ///
1069    /// ```
1070    /// use std::collections::BTreeSet;
1071    ///
1072    /// let mut set = BTreeSet::from([1, 2, 3]);
1073    /// assert_eq!(set.take(&2), Some(2));
1074    /// assert_eq!(set.take(&2), None);
1075    /// ```
1076    #[stable(feature = "set_recovery", since = "1.9.0")]
1077    pub fn take<Q: ?Sized>(&mut self, value: &Q) -> Option<T>
1078    where
1079        T: Borrow<Q> + Ord,
1080        Q: Ord,
1081    {
1082        self.map.remove_entry(value).map(|(k, _)| k)
1083    }
1084
1085    /// Retains only the elements specified by the predicate.
1086    ///
1087    /// In other words, remove all elements `e` for which `f(&e)` returns `false`.
1088    /// The elements are visited in ascending order.
1089    ///
1090    /// # Examples
1091    ///
1092    /// ```
1093    /// use std::collections::BTreeSet;
1094    ///
1095    /// let mut set = BTreeSet::from([1, 2, 3, 4, 5, 6]);
1096    /// // Keep only the even numbers.
1097    /// set.retain(|&k| k % 2 == 0);
1098    /// assert!(set.iter().eq([2, 4, 6].iter()));
1099    /// ```
1100    #[stable(feature = "btree_retain", since = "1.53.0")]
1101    pub fn retain<F>(&mut self, mut f: F)
1102    where
1103        T: Ord,
1104        F: FnMut(&T) -> bool,
1105    {
1106        self.extract_if(.., |v| !f(v)).for_each(drop);
1107    }
1108
1109    /// Moves all elements from `other` into `self`, leaving `other` empty.
1110    ///
1111    /// # Examples
1112    ///
1113    /// ```
1114    /// use std::collections::BTreeSet;
1115    ///
1116    /// let mut a = BTreeSet::new();
1117    /// a.insert(1);
1118    /// a.insert(2);
1119    /// a.insert(3);
1120    ///
1121    /// let mut b = BTreeSet::new();
1122    /// b.insert(3);
1123    /// b.insert(4);
1124    /// b.insert(5);
1125    ///
1126    /// a.append(&mut b);
1127    ///
1128    /// assert_eq!(a.len(), 5);
1129    /// assert_eq!(b.len(), 0);
1130    ///
1131    /// assert!(a.contains(&1));
1132    /// assert!(a.contains(&2));
1133    /// assert!(a.contains(&3));
1134    /// assert!(a.contains(&4));
1135    /// assert!(a.contains(&5));
1136    /// ```
1137    #[stable(feature = "btree_append", since = "1.11.0")]
1138    pub fn append(&mut self, other: &mut Self)
1139    where
1140        T: Ord,
1141        A: Clone,
1142    {
1143        self.map.append(&mut other.map);
1144    }
1145
1146    /// Splits the collection into two at the value. Returns a new collection
1147    /// with all elements greater than or equal to the value.
1148    ///
1149    /// # Examples
1150    ///
1151    /// Basic usage:
1152    ///
1153    /// ```
1154    /// use std::collections::BTreeSet;
1155    ///
1156    /// let mut a = BTreeSet::new();
1157    /// a.insert(1);
1158    /// a.insert(2);
1159    /// a.insert(3);
1160    /// a.insert(17);
1161    /// a.insert(41);
1162    ///
1163    /// let b = a.split_off(&3);
1164    ///
1165    /// assert_eq!(a.len(), 2);
1166    /// assert_eq!(b.len(), 3);
1167    ///
1168    /// assert!(a.contains(&1));
1169    /// assert!(a.contains(&2));
1170    ///
1171    /// assert!(b.contains(&3));
1172    /// assert!(b.contains(&17));
1173    /// assert!(b.contains(&41));
1174    /// ```
1175    #[stable(feature = "btree_split_off", since = "1.11.0")]
1176    pub fn split_off<Q: ?Sized + Ord>(&mut self, value: &Q) -> Self
1177    where
1178        T: Borrow<Q> + Ord,
1179        A: Clone,
1180    {
1181        BTreeSet { map: self.map.split_off(value) }
1182    }
1183
1184    /// Creates an iterator that visits elements in the specified range in ascending order and
1185    /// uses a closure to determine if an element should be removed.
1186    ///
1187    /// If the closure returns `true`, the element is removed from the set and
1188    /// yielded. If the closure returns `false`, or panics, the element remains
1189    /// in the set and will not be yielded.
1190    ///
1191    /// If the returned `ExtractIf` is not exhausted, e.g. because it is dropped without iterating
1192    /// or the iteration short-circuits, then the remaining elements will be retained.
1193    /// Use `extract_if().for_each(drop)` if you do not need the returned iterator,
1194    /// or [`retain`] with a negated predicate if you also do not need to restrict the range.
1195    ///
1196    /// [`retain`]: BTreeSet::retain
1197    /// # Examples
1198    ///
1199    /// ```
1200    /// use std::collections::BTreeSet;
1201    ///
1202    /// // Splitting a set into even and odd values, reusing the original set:
1203    /// let mut set: BTreeSet<i32> = (0..8).collect();
1204    /// let evens: BTreeSet<_> = set.extract_if(.., |v| v % 2 == 0).collect();
1205    /// let odds = set;
1206    /// assert_eq!(evens.into_iter().collect::<Vec<_>>(), vec![0, 2, 4, 6]);
1207    /// assert_eq!(odds.into_iter().collect::<Vec<_>>(), vec![1, 3, 5, 7]);
1208    ///
1209    /// // Splitting a set into low and high halves, reusing the original set:
1210    /// let mut set: BTreeSet<i32> = (0..8).collect();
1211    /// let low: BTreeSet<_> = set.extract_if(0..4, |_v| true).collect();
1212    /// let high = set;
1213    /// assert_eq!(low.into_iter().collect::<Vec<_>>(), [0, 1, 2, 3]);
1214    /// assert_eq!(high.into_iter().collect::<Vec<_>>(), [4, 5, 6, 7]);
1215    /// ```
1216    #[stable(feature = "btree_extract_if", since = "1.91.0")]
1217    pub fn extract_if<F, R>(&mut self, range: R, pred: F) -> ExtractIf<'_, T, R, F, A>
1218    where
1219        T: Ord,
1220        R: RangeBounds<T>,
1221        F: FnMut(&T) -> bool,
1222    {
1223        let (inner, alloc) = self.map.extract_if_inner(range);
1224        ExtractIf { pred, inner, alloc }
1225    }
1226
1227    /// Gets an iterator that visits the elements in the `BTreeSet` in ascending
1228    /// order.
1229    ///
1230    /// # Examples
1231    ///
1232    /// ```
1233    /// use std::collections::BTreeSet;
1234    ///
1235    /// let set = BTreeSet::from([3, 1, 2]);
1236    /// let mut set_iter = set.iter();
1237    /// assert_eq!(set_iter.next(), Some(&1));
1238    /// assert_eq!(set_iter.next(), Some(&2));
1239    /// assert_eq!(set_iter.next(), Some(&3));
1240    /// assert_eq!(set_iter.next(), None);
1241    /// ```
1242    #[stable(feature = "rust1", since = "1.0.0")]
1243    #[cfg_attr(not(test), rustc_diagnostic_item = "btreeset_iter")]
1244    pub fn iter(&self) -> Iter<'_, T> {
1245        Iter { iter: self.map.keys() }
1246    }
1247
1248    /// Returns the number of elements in the set.
1249    ///
1250    /// # Examples
1251    ///
1252    /// ```
1253    /// use std::collections::BTreeSet;
1254    ///
1255    /// let mut v = BTreeSet::new();
1256    /// assert_eq!(v.len(), 0);
1257    /// v.insert(1);
1258    /// assert_eq!(v.len(), 1);
1259    /// ```
1260    #[must_use]
1261    #[stable(feature = "rust1", since = "1.0.0")]
1262    #[rustc_const_unstable(
1263        feature = "const_btree_len",
1264        issue = "71835",
1265        implied_by = "const_btree_new"
1266    )]
1267    #[rustc_confusables("length", "size")]
1268    pub const fn len(&self) -> usize {
1269        self.map.len()
1270    }
1271
1272    /// Returns `true` if the set contains no elements.
1273    ///
1274    /// # Examples
1275    ///
1276    /// ```
1277    /// use std::collections::BTreeSet;
1278    ///
1279    /// let mut v = BTreeSet::new();
1280    /// assert!(v.is_empty());
1281    /// v.insert(1);
1282    /// assert!(!v.is_empty());
1283    /// ```
1284    #[must_use]
1285    #[stable(feature = "rust1", since = "1.0.0")]
1286    #[rustc_const_unstable(
1287        feature = "const_btree_len",
1288        issue = "71835",
1289        implied_by = "const_btree_new"
1290    )]
1291    pub const fn is_empty(&self) -> bool {
1292        self.len() == 0
1293    }
1294
1295    /// Returns a [`Cursor`] pointing at the gap before the smallest element
1296    /// greater than the given bound.
1297    ///
1298    /// Passing `Bound::Included(x)` will return a cursor pointing to the
1299    /// gap before the smallest element greater than or equal to `x`.
1300    ///
1301    /// Passing `Bound::Excluded(x)` will return a cursor pointing to the
1302    /// gap before the smallest element greater than `x`.
1303    ///
1304    /// Passing `Bound::Unbounded` will return a cursor pointing to the
1305    /// gap before the smallest element in the set.
1306    ///
1307    /// # Examples
1308    ///
1309    /// ```
1310    /// #![feature(btree_cursors)]
1311    ///
1312    /// use std::collections::BTreeSet;
1313    /// use std::ops::Bound;
1314    ///
1315    /// let set = BTreeSet::from([1, 2, 3, 4]);
1316    ///
1317    /// let cursor = set.lower_bound(Bound::Included(&2));
1318    /// assert_eq!(cursor.peek_prev(), Some(&1));
1319    /// assert_eq!(cursor.peek_next(), Some(&2));
1320    ///
1321    /// let cursor = set.lower_bound(Bound::Excluded(&2));
1322    /// assert_eq!(cursor.peek_prev(), Some(&2));
1323    /// assert_eq!(cursor.peek_next(), Some(&3));
1324    ///
1325    /// let cursor = set.lower_bound(Bound::Unbounded);
1326    /// assert_eq!(cursor.peek_prev(), None);
1327    /// assert_eq!(cursor.peek_next(), Some(&1));
1328    /// ```
1329    #[unstable(feature = "btree_cursors", issue = "107540")]
1330    pub fn lower_bound<Q: ?Sized>(&self, bound: Bound<&Q>) -> Cursor<'_, T>
1331    where
1332        T: Borrow<Q> + Ord,
1333        Q: Ord,
1334    {
1335        Cursor { inner: self.map.lower_bound(bound) }
1336    }
1337
1338    /// Returns a [`CursorMut`] pointing at the gap before the smallest element
1339    /// greater than the given bound.
1340    ///
1341    /// Passing `Bound::Included(x)` will return a cursor pointing to the
1342    /// gap before the smallest element greater than or equal to `x`.
1343    ///
1344    /// Passing `Bound::Excluded(x)` will return a cursor pointing to the
1345    /// gap before the smallest element greater than `x`.
1346    ///
1347    /// Passing `Bound::Unbounded` will return a cursor pointing to the
1348    /// gap before the smallest element in the set.
1349    ///
1350    /// # Examples
1351    ///
1352    /// ```
1353    /// #![feature(btree_cursors)]
1354    ///
1355    /// use std::collections::BTreeSet;
1356    /// use std::ops::Bound;
1357    ///
1358    /// let mut set = BTreeSet::from([1, 2, 3, 4]);
1359    ///
1360    /// let mut cursor = set.lower_bound_mut(Bound::Included(&2));
1361    /// assert_eq!(cursor.peek_prev(), Some(&1));
1362    /// assert_eq!(cursor.peek_next(), Some(&2));
1363    ///
1364    /// let mut cursor = set.lower_bound_mut(Bound::Excluded(&2));
1365    /// assert_eq!(cursor.peek_prev(), Some(&2));
1366    /// assert_eq!(cursor.peek_next(), Some(&3));
1367    ///
1368    /// let mut cursor = set.lower_bound_mut(Bound::Unbounded);
1369    /// assert_eq!(cursor.peek_prev(), None);
1370    /// assert_eq!(cursor.peek_next(), Some(&1));
1371    /// ```
1372    #[unstable(feature = "btree_cursors", issue = "107540")]
1373    pub fn lower_bound_mut<Q: ?Sized>(&mut self, bound: Bound<&Q>) -> CursorMut<'_, T, A>
1374    where
1375        T: Borrow<Q> + Ord,
1376        Q: Ord,
1377    {
1378        CursorMut { inner: self.map.lower_bound_mut(bound) }
1379    }
1380
1381    /// Returns a [`Cursor`] pointing at the gap after the greatest element
1382    /// smaller than the given bound.
1383    ///
1384    /// Passing `Bound::Included(x)` will return a cursor pointing to the
1385    /// gap after the greatest element smaller than or equal to `x`.
1386    ///
1387    /// Passing `Bound::Excluded(x)` will return a cursor pointing to the
1388    /// gap after the greatest element smaller than `x`.
1389    ///
1390    /// Passing `Bound::Unbounded` will return a cursor pointing to the
1391    /// gap after the greatest element in the set.
1392    ///
1393    /// # Examples
1394    ///
1395    /// ```
1396    /// #![feature(btree_cursors)]
1397    ///
1398    /// use std::collections::BTreeSet;
1399    /// use std::ops::Bound;
1400    ///
1401    /// let set = BTreeSet::from([1, 2, 3, 4]);
1402    ///
1403    /// let cursor = set.upper_bound(Bound::Included(&3));
1404    /// assert_eq!(cursor.peek_prev(), Some(&3));
1405    /// assert_eq!(cursor.peek_next(), Some(&4));
1406    ///
1407    /// let cursor = set.upper_bound(Bound::Excluded(&3));
1408    /// assert_eq!(cursor.peek_prev(), Some(&2));
1409    /// assert_eq!(cursor.peek_next(), Some(&3));
1410    ///
1411    /// let cursor = set.upper_bound(Bound::Unbounded);
1412    /// assert_eq!(cursor.peek_prev(), Some(&4));
1413    /// assert_eq!(cursor.peek_next(), None);
1414    /// ```
1415    #[unstable(feature = "btree_cursors", issue = "107540")]
1416    pub fn upper_bound<Q: ?Sized>(&self, bound: Bound<&Q>) -> Cursor<'_, T>
1417    where
1418        T: Borrow<Q> + Ord,
1419        Q: Ord,
1420    {
1421        Cursor { inner: self.map.upper_bound(bound) }
1422    }
1423
1424    /// Returns a [`CursorMut`] pointing at the gap after the greatest element
1425    /// smaller than the given bound.
1426    ///
1427    /// Passing `Bound::Included(x)` will return a cursor pointing to the
1428    /// gap after the greatest element smaller than or equal to `x`.
1429    ///
1430    /// Passing `Bound::Excluded(x)` will return a cursor pointing to the
1431    /// gap after the greatest element smaller than `x`.
1432    ///
1433    /// Passing `Bound::Unbounded` will return a cursor pointing to the
1434    /// gap after the greatest element in the set.
1435    ///
1436    /// # Examples
1437    ///
1438    /// ```
1439    /// #![feature(btree_cursors)]
1440    ///
1441    /// use std::collections::BTreeSet;
1442    /// use std::ops::Bound;
1443    ///
1444    /// let mut set = BTreeSet::from([1, 2, 3, 4]);
1445    ///
1446    /// let mut cursor = set.upper_bound_mut(Bound::Included(&3));
1447    /// assert_eq!(cursor.peek_prev(), Some(&3));
1448    /// assert_eq!(cursor.peek_next(), Some(&4));
1449    ///
1450    /// let mut cursor = set.upper_bound_mut(Bound::Excluded(&3));
1451    /// assert_eq!(cursor.peek_prev(), Some(&2));
1452    /// assert_eq!(cursor.peek_next(), Some(&3));
1453    ///
1454    /// let mut cursor = set.upper_bound_mut(Bound::Unbounded);
1455    /// assert_eq!(cursor.peek_prev(), Some(&4));
1456    /// assert_eq!(cursor.peek_next(), None);
1457    /// ```
1458    #[unstable(feature = "btree_cursors", issue = "107540")]
1459    pub fn upper_bound_mut<Q: ?Sized>(&mut self, bound: Bound<&Q>) -> CursorMut<'_, T, A>
1460    where
1461        T: Borrow<Q> + Ord,
1462        Q: Ord,
1463    {
1464        CursorMut { inner: self.map.upper_bound_mut(bound) }
1465    }
1466}
1467
1468#[stable(feature = "rust1", since = "1.0.0")]
1469impl<T: Ord> FromIterator<T> for BTreeSet<T> {
1470    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> BTreeSet<T> {
1471        let mut inputs: Vec<_> = iter.into_iter().collect();
1472
1473        if inputs.is_empty() {
1474            return BTreeSet::new();
1475        }
1476
1477        // use stable sort to preserve the insertion order.
1478        inputs.sort();
1479        BTreeSet::from_sorted_iter(inputs.into_iter(), Global)
1480    }
1481}
1482
1483impl<T: Ord, A: Allocator + Clone> BTreeSet<T, A> {
1484    fn from_sorted_iter<I: Iterator<Item = T>>(iter: I, alloc: A) -> BTreeSet<T, A> {
1485        let iter = iter.map(|k| (k, SetValZST::default()));
1486        let map = BTreeMap::bulk_build_from_sorted_iter(iter, alloc);
1487        BTreeSet { map }
1488    }
1489}
1490
1491#[stable(feature = "std_collections_from_array", since = "1.56.0")]
1492impl<T: Ord, const N: usize> From<[T; N]> for BTreeSet<T> {
1493    /// Converts a `[T; N]` into a `BTreeSet<T>`.
1494    ///
1495    /// If the array contains any equal values,
1496    /// all but one will be dropped.
1497    ///
1498    /// # Examples
1499    ///
1500    /// ```
1501    /// use std::collections::BTreeSet;
1502    ///
1503    /// let set1 = BTreeSet::from([1, 2, 3, 4]);
1504    /// let set2: BTreeSet<_> = [1, 2, 3, 4].into();
1505    /// assert_eq!(set1, set2);
1506    /// ```
1507    fn from(mut arr: [T; N]) -> Self {
1508        if N == 0 {
1509            return BTreeSet::new();
1510        }
1511
1512        // use stable sort to preserve the insertion order.
1513        arr.sort();
1514        BTreeSet::from_sorted_iter(IntoIterator::into_iter(arr), Global)
1515    }
1516}
1517
1518#[stable(feature = "rust1", since = "1.0.0")]
1519impl<T, A: Allocator + Clone> IntoIterator for BTreeSet<T, A> {
1520    type Item = T;
1521    type IntoIter = IntoIter<T, A>;
1522
1523    /// Gets an iterator for moving out the `BTreeSet`'s contents in ascending order.
1524    ///
1525    /// # Examples
1526    ///
1527    /// ```
1528    /// use std::collections::BTreeSet;
1529    ///
1530    /// let set = BTreeSet::from([1, 2, 3, 4]);
1531    ///
1532    /// let v: Vec<_> = set.into_iter().collect();
1533    /// assert_eq!(v, [1, 2, 3, 4]);
1534    /// ```
1535    fn into_iter(self) -> IntoIter<T, A> {
1536        IntoIter { iter: self.map.into_iter() }
1537    }
1538}
1539
1540#[stable(feature = "rust1", since = "1.0.0")]
1541impl<'a, T, A: Allocator + Clone> IntoIterator for &'a BTreeSet<T, A> {
1542    type Item = &'a T;
1543    type IntoIter = Iter<'a, T>;
1544
1545    fn into_iter(self) -> Iter<'a, T> {
1546        self.iter()
1547    }
1548}
1549
1550/// An iterator produced by calling `extract_if` on BTreeSet.
1551#[stable(feature = "btree_extract_if", since = "1.91.0")]
1552#[must_use = "iterators are lazy and do nothing unless consumed; \
1553    use `retain` or `extract_if().for_each(drop)` to remove and discard elements"]
1554pub struct ExtractIf<
1555    'a,
1556    T,
1557    R,
1558    F,
1559    #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator + Clone = Global,
1560> {
1561    pred: F,
1562    inner: super::map::ExtractIfInner<'a, T, SetValZST, R>,
1563    /// The BTreeMap will outlive this IntoIter so we don't care about drop order for `alloc`.
1564    alloc: A,
1565}
1566
1567#[stable(feature = "btree_extract_if", since = "1.91.0")]
1568impl<T, R, F, A> fmt::Debug for ExtractIf<'_, T, R, F, A>
1569where
1570    T: fmt::Debug,
1571    A: Allocator + Clone,
1572{
1573    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1574        f.debug_struct("ExtractIf")
1575            .field("peek", &self.inner.peek().map(|(k, _)| k))
1576            .finish_non_exhaustive()
1577    }
1578}
1579
1580#[stable(feature = "btree_extract_if", since = "1.91.0")]
1581impl<T, R, F, A: Allocator + Clone> Iterator for ExtractIf<'_, T, R, F, A>
1582where
1583    T: PartialOrd,
1584    R: RangeBounds<T>,
1585    F: FnMut(&T) -> bool,
1586{
1587    type Item = T;
1588
1589    fn next(&mut self) -> Option<T> {
1590        let pred = &mut self.pred;
1591        let mut mapped_pred = |k: &T, _v: &mut SetValZST| pred(k);
1592        self.inner.next(&mut mapped_pred, self.alloc.clone()).map(|(k, _)| k)
1593    }
1594
1595    fn size_hint(&self) -> (usize, Option<usize>) {
1596        self.inner.size_hint()
1597    }
1598}
1599
1600#[stable(feature = "btree_extract_if", since = "1.91.0")]
1601impl<T, R, F, A: Allocator + Clone> FusedIterator for ExtractIf<'_, T, R, F, A>
1602where
1603    T: PartialOrd,
1604    R: RangeBounds<T>,
1605    F: FnMut(&T) -> bool,
1606{
1607}
1608
1609#[stable(feature = "rust1", since = "1.0.0")]
1610impl<T: Ord, A: Allocator + Clone> Extend<T> for BTreeSet<T, A> {
1611    #[inline]
1612    fn extend<Iter: IntoIterator<Item = T>>(&mut self, iter: Iter) {
1613        iter.into_iter().for_each(move |elem| {
1614            self.insert(elem);
1615        });
1616    }
1617
1618    #[inline]
1619    fn extend_one(&mut self, elem: T) {
1620        self.insert(elem);
1621    }
1622}
1623
1624#[stable(feature = "extend_ref", since = "1.2.0")]
1625impl<'a, T: 'a + Ord + Copy, A: Allocator + Clone> Extend<&'a T> for BTreeSet<T, A> {
1626    fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
1627        self.extend(iter.into_iter().cloned());
1628    }
1629
1630    #[inline]
1631    fn extend_one(&mut self, &elem: &'a T) {
1632        self.insert(elem);
1633    }
1634}
1635
1636#[stable(feature = "rust1", since = "1.0.0")]
1637impl<T> Default for BTreeSet<T> {
1638    /// Creates an empty `BTreeSet`.
1639    fn default() -> BTreeSet<T> {
1640        BTreeSet::new()
1641    }
1642}
1643
1644#[stable(feature = "rust1", since = "1.0.0")]
1645impl<T: Ord + Clone, A: Allocator + Clone> Sub<&BTreeSet<T, A>> for &BTreeSet<T, A> {
1646    type Output = BTreeSet<T, A>;
1647
1648    /// Returns the difference of `self` and `rhs` as a new `BTreeSet<T>`.
1649    ///
1650    /// # Examples
1651    ///
1652    /// ```
1653    /// use std::collections::BTreeSet;
1654    ///
1655    /// let a = BTreeSet::from([1, 2, 3]);
1656    /// let b = BTreeSet::from([3, 4, 5]);
1657    ///
1658    /// let result = &a - &b;
1659    /// assert_eq!(result, BTreeSet::from([1, 2]));
1660    /// ```
1661    fn sub(self, rhs: &BTreeSet<T, A>) -> BTreeSet<T, A> {
1662        BTreeSet::from_sorted_iter(
1663            self.difference(rhs).cloned(),
1664            ManuallyDrop::into_inner(self.map.alloc.clone()),
1665        )
1666    }
1667}
1668
1669#[stable(feature = "rust1", since = "1.0.0")]
1670impl<T: Ord + Clone, A: Allocator + Clone> BitXor<&BTreeSet<T, A>> for &BTreeSet<T, A> {
1671    type Output = BTreeSet<T, A>;
1672
1673    /// Returns the symmetric difference of `self` and `rhs` as a new `BTreeSet<T>`.
1674    ///
1675    /// # Examples
1676    ///
1677    /// ```
1678    /// use std::collections::BTreeSet;
1679    ///
1680    /// let a = BTreeSet::from([1, 2, 3]);
1681    /// let b = BTreeSet::from([2, 3, 4]);
1682    ///
1683    /// let result = &a ^ &b;
1684    /// assert_eq!(result, BTreeSet::from([1, 4]));
1685    /// ```
1686    fn bitxor(self, rhs: &BTreeSet<T, A>) -> BTreeSet<T, A> {
1687        BTreeSet::from_sorted_iter(
1688            self.symmetric_difference(rhs).cloned(),
1689            ManuallyDrop::into_inner(self.map.alloc.clone()),
1690        )
1691    }
1692}
1693
1694#[stable(feature = "rust1", since = "1.0.0")]
1695impl<T: Ord + Clone, A: Allocator + Clone> BitAnd<&BTreeSet<T, A>> for &BTreeSet<T, A> {
1696    type Output = BTreeSet<T, A>;
1697
1698    /// Returns the intersection of `self` and `rhs` as a new `BTreeSet<T>`.
1699    ///
1700    /// # Examples
1701    ///
1702    /// ```
1703    /// use std::collections::BTreeSet;
1704    ///
1705    /// let a = BTreeSet::from([1, 2, 3]);
1706    /// let b = BTreeSet::from([2, 3, 4]);
1707    ///
1708    /// let result = &a & &b;
1709    /// assert_eq!(result, BTreeSet::from([2, 3]));
1710    /// ```
1711    fn bitand(self, rhs: &BTreeSet<T, A>) -> BTreeSet<T, A> {
1712        BTreeSet::from_sorted_iter(
1713            self.intersection(rhs).cloned(),
1714            ManuallyDrop::into_inner(self.map.alloc.clone()),
1715        )
1716    }
1717}
1718
1719#[stable(feature = "rust1", since = "1.0.0")]
1720impl<T: Ord + Clone, A: Allocator + Clone> BitOr<&BTreeSet<T, A>> for &BTreeSet<T, A> {
1721    type Output = BTreeSet<T, A>;
1722
1723    /// Returns the union of `self` and `rhs` as a new `BTreeSet<T>`.
1724    ///
1725    /// # Examples
1726    ///
1727    /// ```
1728    /// use std::collections::BTreeSet;
1729    ///
1730    /// let a = BTreeSet::from([1, 2, 3]);
1731    /// let b = BTreeSet::from([3, 4, 5]);
1732    ///
1733    /// let result = &a | &b;
1734    /// assert_eq!(result, BTreeSet::from([1, 2, 3, 4, 5]));
1735    /// ```
1736    fn bitor(self, rhs: &BTreeSet<T, A>) -> BTreeSet<T, A> {
1737        BTreeSet::from_sorted_iter(
1738            self.union(rhs).cloned(),
1739            ManuallyDrop::into_inner(self.map.alloc.clone()),
1740        )
1741    }
1742}
1743
1744#[stable(feature = "rust1", since = "1.0.0")]
1745impl<T: Debug, A: Allocator + Clone> Debug for BTreeSet<T, A> {
1746    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1747        f.debug_set().entries(self.iter()).finish()
1748    }
1749}
1750
1751#[stable(feature = "rust1", since = "1.0.0")]
1752impl<T> Clone for Iter<'_, T> {
1753    fn clone(&self) -> Self {
1754        Iter { iter: self.iter.clone() }
1755    }
1756}
1757
1758#[stable(feature = "rust1", since = "1.0.0")]
1759impl<'a, T> Iterator for Iter<'a, T> {
1760    type Item = &'a T;
1761
1762    fn next(&mut self) -> Option<&'a T> {
1763        self.iter.next()
1764    }
1765
1766    fn size_hint(&self) -> (usize, Option<usize>) {
1767        self.iter.size_hint()
1768    }
1769
1770    fn last(mut self) -> Option<&'a T> {
1771        self.next_back()
1772    }
1773
1774    fn min(mut self) -> Option<&'a T>
1775    where
1776        &'a T: Ord,
1777    {
1778        self.next()
1779    }
1780
1781    fn max(mut self) -> Option<&'a T>
1782    where
1783        &'a T: Ord,
1784    {
1785        self.next_back()
1786    }
1787}
1788
1789#[stable(feature = "rust1", since = "1.0.0")]
1790impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
1791    fn next_back(&mut self) -> Option<&'a T> {
1792        self.iter.next_back()
1793    }
1794}
1795
1796#[stable(feature = "rust1", since = "1.0.0")]
1797impl<T> ExactSizeIterator for Iter<'_, T> {
1798    fn len(&self) -> usize {
1799        self.iter.len()
1800    }
1801}
1802
1803#[unstable(feature = "trusted_len", issue = "37572")]
1804unsafe impl<T> TrustedLen for Iter<'_, T> {}
1805
1806#[stable(feature = "fused", since = "1.26.0")]
1807impl<T> FusedIterator for Iter<'_, T> {}
1808
1809#[stable(feature = "rust1", since = "1.0.0")]
1810impl<T, A: Allocator + Clone> Iterator for IntoIter<T, A> {
1811    type Item = T;
1812
1813    fn next(&mut self) -> Option<T> {
1814        self.iter.next().map(|(k, _)| k)
1815    }
1816
1817    fn size_hint(&self) -> (usize, Option<usize>) {
1818        self.iter.size_hint()
1819    }
1820}
1821
1822#[stable(feature = "default_iters", since = "1.70.0")]
1823impl<T> Default for Iter<'_, T> {
1824    /// Creates an empty `btree_set::Iter`.
1825    ///
1826    /// ```
1827    /// # use std::collections::btree_set;
1828    /// let iter: btree_set::Iter<'_, u8> = Default::default();
1829    /// assert_eq!(iter.len(), 0);
1830    /// ```
1831    fn default() -> Self {
1832        Iter { iter: Default::default() }
1833    }
1834}
1835
1836#[stable(feature = "rust1", since = "1.0.0")]
1837impl<T, A: Allocator + Clone> DoubleEndedIterator for IntoIter<T, A> {
1838    fn next_back(&mut self) -> Option<T> {
1839        self.iter.next_back().map(|(k, _)| k)
1840    }
1841}
1842
1843#[stable(feature = "rust1", since = "1.0.0")]
1844impl<T, A: Allocator + Clone> ExactSizeIterator for IntoIter<T, A> {
1845    fn len(&self) -> usize {
1846        self.iter.len()
1847    }
1848}
1849
1850#[unstable(feature = "trusted_len", issue = "37572")]
1851unsafe impl<T, A: Allocator + Clone> TrustedLen for IntoIter<T, A> {}
1852
1853#[stable(feature = "fused", since = "1.26.0")]
1854impl<T, A: Allocator + Clone> FusedIterator for IntoIter<T, A> {}
1855
1856#[stable(feature = "default_iters", since = "1.70.0")]
1857impl<T, A> Default for IntoIter<T, A>
1858where
1859    A: Allocator + Default + Clone,
1860{
1861    /// Creates an empty `btree_set::IntoIter`.
1862    ///
1863    /// ```
1864    /// # use std::collections::btree_set;
1865    /// let iter: btree_set::IntoIter<u8> = Default::default();
1866    /// assert_eq!(iter.len(), 0);
1867    /// ```
1868    fn default() -> Self {
1869        IntoIter { iter: Default::default() }
1870    }
1871}
1872
1873#[stable(feature = "btree_range", since = "1.17.0")]
1874impl<T> Clone for Range<'_, T> {
1875    fn clone(&self) -> Self {
1876        Range { iter: self.iter.clone() }
1877    }
1878}
1879
1880#[stable(feature = "btree_range", since = "1.17.0")]
1881impl<'a, T> Iterator for Range<'a, T> {
1882    type Item = &'a T;
1883
1884    fn next(&mut self) -> Option<&'a T> {
1885        self.iter.next().map(|(k, _)| k)
1886    }
1887
1888    fn last(mut self) -> Option<&'a T> {
1889        self.next_back()
1890    }
1891
1892    fn min(mut self) -> Option<&'a T>
1893    where
1894        &'a T: Ord,
1895    {
1896        self.next()
1897    }
1898
1899    fn max(mut self) -> Option<&'a T>
1900    where
1901        &'a T: Ord,
1902    {
1903        self.next_back()
1904    }
1905}
1906
1907#[stable(feature = "btree_range", since = "1.17.0")]
1908impl<'a, T> DoubleEndedIterator for Range<'a, T> {
1909    fn next_back(&mut self) -> Option<&'a T> {
1910        self.iter.next_back().map(|(k, _)| k)
1911    }
1912}
1913
1914#[stable(feature = "fused", since = "1.26.0")]
1915impl<T> FusedIterator for Range<'_, T> {}
1916
1917#[stable(feature = "default_iters", since = "1.70.0")]
1918impl<T> Default for Range<'_, T> {
1919    /// Creates an empty `btree_set::Range`.
1920    ///
1921    /// ```
1922    /// # use std::collections::btree_set;
1923    /// let iter: btree_set::Range<'_, u8> = Default::default();
1924    /// assert_eq!(iter.count(), 0);
1925    /// ```
1926    fn default() -> Self {
1927        Range { iter: Default::default() }
1928    }
1929}
1930
1931#[stable(feature = "rust1", since = "1.0.0")]
1932impl<T, A: Allocator + Clone> Clone for Difference<'_, T, A> {
1933    fn clone(&self) -> Self {
1934        Difference {
1935            inner: match &self.inner {
1936                DifferenceInner::Stitch { self_iter, other_iter } => DifferenceInner::Stitch {
1937                    self_iter: self_iter.clone(),
1938                    other_iter: other_iter.clone(),
1939                },
1940                DifferenceInner::Search { self_iter, other_set } => {
1941                    DifferenceInner::Search { self_iter: self_iter.clone(), other_set }
1942                }
1943                DifferenceInner::Iterate(iter) => DifferenceInner::Iterate(iter.clone()),
1944            },
1945        }
1946    }
1947}
1948#[stable(feature = "rust1", since = "1.0.0")]
1949impl<'a, T: Ord, A: Allocator + Clone> Iterator for Difference<'a, T, A> {
1950    type Item = &'a T;
1951
1952    fn next(&mut self) -> Option<&'a T> {
1953        match &mut self.inner {
1954            DifferenceInner::Stitch { self_iter, other_iter } => {
1955                let mut self_next = self_iter.next()?;
1956                loop {
1957                    match other_iter.peek().map_or(Less, |other_next| self_next.cmp(other_next)) {
1958                        Less => return Some(self_next),
1959                        Equal => {
1960                            self_next = self_iter.next()?;
1961                            other_iter.next();
1962                        }
1963                        Greater => {
1964                            other_iter.next();
1965                        }
1966                    }
1967                }
1968            }
1969            DifferenceInner::Search { self_iter, other_set } => loop {
1970                let self_next = self_iter.next()?;
1971                if !other_set.contains(&self_next) {
1972                    return Some(self_next);
1973                }
1974            },
1975            DifferenceInner::Iterate(iter) => iter.next(),
1976        }
1977    }
1978
1979    fn size_hint(&self) -> (usize, Option<usize>) {
1980        let (self_len, other_len) = match &self.inner {
1981            DifferenceInner::Stitch { self_iter, other_iter } => {
1982                (self_iter.len(), other_iter.len())
1983            }
1984            DifferenceInner::Search { self_iter, other_set } => (self_iter.len(), other_set.len()),
1985            DifferenceInner::Iterate(iter) => (iter.len(), 0),
1986        };
1987        (self_len.saturating_sub(other_len), Some(self_len))
1988    }
1989
1990    fn min(mut self) -> Option<&'a T> {
1991        self.next()
1992    }
1993}
1994
1995#[stable(feature = "fused", since = "1.26.0")]
1996impl<T: Ord, A: Allocator + Clone> FusedIterator for Difference<'_, T, A> {}
1997
1998#[stable(feature = "rust1", since = "1.0.0")]
1999impl<T> Clone for SymmetricDifference<'_, T> {
2000    fn clone(&self) -> Self {
2001        SymmetricDifference(self.0.clone())
2002    }
2003}
2004#[stable(feature = "rust1", since = "1.0.0")]
2005impl<'a, T: Ord> Iterator for SymmetricDifference<'a, T> {
2006    type Item = &'a T;
2007
2008    fn next(&mut self) -> Option<&'a T> {
2009        loop {
2010            let (a_next, b_next) = self.0.nexts(Self::Item::cmp);
2011            if a_next.and(b_next).is_none() {
2012                return a_next.or(b_next);
2013            }
2014        }
2015    }
2016
2017    fn size_hint(&self) -> (usize, Option<usize>) {
2018        let (a_len, b_len) = self.0.lens();
2019        // No checked_add, because even if a and b refer to the same set,
2020        // and T is a zero-sized type, the storage overhead of sets limits
2021        // the number of elements to less than half the range of usize.
2022        (0, Some(a_len + b_len))
2023    }
2024
2025    fn min(mut self) -> Option<&'a T> {
2026        self.next()
2027    }
2028}
2029
2030#[stable(feature = "fused", since = "1.26.0")]
2031impl<T: Ord> FusedIterator for SymmetricDifference<'_, T> {}
2032
2033#[stable(feature = "rust1", since = "1.0.0")]
2034impl<T, A: Allocator + Clone> Clone for Intersection<'_, T, A> {
2035    fn clone(&self) -> Self {
2036        Intersection {
2037            inner: match &self.inner {
2038                IntersectionInner::Stitch { a, b } => {
2039                    IntersectionInner::Stitch { a: a.clone(), b: b.clone() }
2040                }
2041                IntersectionInner::Search { small_iter, large_set } => {
2042                    IntersectionInner::Search { small_iter: small_iter.clone(), large_set }
2043                }
2044                IntersectionInner::Answer(answer) => IntersectionInner::Answer(*answer),
2045            },
2046        }
2047    }
2048}
2049#[stable(feature = "rust1", since = "1.0.0")]
2050impl<'a, T: Ord, A: Allocator + Clone> Iterator for Intersection<'a, T, A> {
2051    type Item = &'a T;
2052
2053    fn next(&mut self) -> Option<&'a T> {
2054        match &mut self.inner {
2055            IntersectionInner::Stitch { a, b } => {
2056                let mut a_next = a.next()?;
2057                let mut b_next = b.next()?;
2058                loop {
2059                    match a_next.cmp(b_next) {
2060                        Less => a_next = a.next()?,
2061                        Greater => b_next = b.next()?,
2062                        Equal => return Some(a_next),
2063                    }
2064                }
2065            }
2066            IntersectionInner::Search { small_iter, large_set } => loop {
2067                let small_next = small_iter.next()?;
2068                if large_set.contains(&small_next) {
2069                    return Some(small_next);
2070                }
2071            },
2072            IntersectionInner::Answer(answer) => answer.take(),
2073        }
2074    }
2075
2076    fn size_hint(&self) -> (usize, Option<usize>) {
2077        match &self.inner {
2078            IntersectionInner::Stitch { a, b } => (0, Some(min(a.len(), b.len()))),
2079            IntersectionInner::Search { small_iter, .. } => (0, Some(small_iter.len())),
2080            IntersectionInner::Answer(None) => (0, Some(0)),
2081            IntersectionInner::Answer(Some(_)) => (1, Some(1)),
2082        }
2083    }
2084
2085    fn min(mut self) -> Option<&'a T> {
2086        self.next()
2087    }
2088}
2089
2090#[stable(feature = "fused", since = "1.26.0")]
2091impl<T: Ord, A: Allocator + Clone> FusedIterator for Intersection<'_, T, A> {}
2092
2093#[stable(feature = "rust1", since = "1.0.0")]
2094impl<T> Clone for Union<'_, T> {
2095    fn clone(&self) -> Self {
2096        Union(self.0.clone())
2097    }
2098}
2099#[stable(feature = "rust1", since = "1.0.0")]
2100impl<'a, T: Ord> Iterator for Union<'a, T> {
2101    type Item = &'a T;
2102
2103    fn next(&mut self) -> Option<&'a T> {
2104        let (a_next, b_next) = self.0.nexts(Self::Item::cmp);
2105        a_next.or(b_next)
2106    }
2107
2108    fn size_hint(&self) -> (usize, Option<usize>) {
2109        let (a_len, b_len) = self.0.lens();
2110        // No checked_add - see SymmetricDifference::size_hint.
2111        (max(a_len, b_len), Some(a_len + b_len))
2112    }
2113
2114    fn min(mut self) -> Option<&'a T> {
2115        self.next()
2116    }
2117}
2118
2119#[stable(feature = "fused", since = "1.26.0")]
2120impl<T: Ord> FusedIterator for Union<'_, T> {}
2121
2122/// A cursor over a `BTreeSet`.
2123///
2124/// A `Cursor` is like an iterator, except that it can freely seek back-and-forth.
2125///
2126/// Cursors always point to a gap between two elements in the set, and can
2127/// operate on the two immediately adjacent elements.
2128///
2129/// A `Cursor` is created with the [`BTreeSet::lower_bound`] and [`BTreeSet::upper_bound`] methods.
2130#[derive(Clone)]
2131#[unstable(feature = "btree_cursors", issue = "107540")]
2132pub struct Cursor<'a, K: 'a> {
2133    inner: super::map::Cursor<'a, K, SetValZST>,
2134}
2135
2136#[unstable(feature = "btree_cursors", issue = "107540")]
2137impl<K: Debug> Debug for Cursor<'_, K> {
2138    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2139        f.write_str("Cursor")
2140    }
2141}
2142
2143/// A cursor over a `BTreeSet` with editing operations.
2144///
2145/// A `Cursor` is like an iterator, except that it can freely seek back-and-forth, and can
2146/// safely mutate the set during iteration. This is because the lifetime of its yielded
2147/// references is tied to its own lifetime, instead of just the underlying map. This means
2148/// cursors cannot yield multiple elements at once.
2149///
2150/// Cursors always point to a gap between two elements in the set, and can
2151/// operate on the two immediately adjacent elements.
2152///
2153/// A `CursorMut` is created with the [`BTreeSet::lower_bound_mut`] and [`BTreeSet::upper_bound_mut`]
2154/// methods.
2155#[unstable(feature = "btree_cursors", issue = "107540")]
2156pub struct CursorMut<'a, K: 'a, #[unstable(feature = "allocator_api", issue = "32838")] A = Global>
2157{
2158    inner: super::map::CursorMut<'a, K, SetValZST, A>,
2159}
2160
2161#[unstable(feature = "btree_cursors", issue = "107540")]
2162impl<K: Debug, A> Debug for CursorMut<'_, K, A> {
2163    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2164        f.write_str("CursorMut")
2165    }
2166}
2167
2168/// A cursor over a `BTreeSet` with editing operations, and which allows
2169/// mutating elements.
2170///
2171/// A `Cursor` is like an iterator, except that it can freely seek back-and-forth, and can
2172/// safely mutate the set during iteration. This is because the lifetime of its yielded
2173/// references is tied to its own lifetime, instead of just the underlying set. This means
2174/// cursors cannot yield multiple elements at once.
2175///
2176/// Cursors always point to a gap between two elements in the set, and can
2177/// operate on the two immediately adjacent elements.
2178///
2179/// A `CursorMutKey` is created from a [`CursorMut`] with the
2180/// [`CursorMut::with_mutable_key`] method.
2181///
2182/// # Safety
2183///
2184/// Since this cursor allows mutating elements, you must ensure that the
2185/// `BTreeSet` invariants are maintained. Specifically:
2186///
2187/// * The newly inserted element must be unique in the tree.
2188/// * All elements in the tree must remain in sorted order.
2189#[unstable(feature = "btree_cursors", issue = "107540")]
2190pub struct CursorMutKey<
2191    'a,
2192    K: 'a,
2193    #[unstable(feature = "allocator_api", issue = "32838")] A = Global,
2194> {
2195    inner: super::map::CursorMutKey<'a, K, SetValZST, A>,
2196}
2197
2198#[unstable(feature = "btree_cursors", issue = "107540")]
2199impl<K: Debug, A> Debug for CursorMutKey<'_, K, A> {
2200    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2201        f.write_str("CursorMutKey")
2202    }
2203}
2204
2205impl<'a, K> Cursor<'a, K> {
2206    /// Advances the cursor to the next gap, returning the element that it
2207    /// moved over.
2208    ///
2209    /// If the cursor is already at the end of the set then `None` is returned
2210    /// and the cursor is not moved.
2211    #[unstable(feature = "btree_cursors", issue = "107540")]
2212    pub fn next(&mut self) -> Option<&'a K> {
2213        self.inner.next().map(|(k, _)| k)
2214    }
2215
2216    /// Advances the cursor to the previous gap, returning the element that it
2217    /// moved over.
2218    ///
2219    /// If the cursor is already at the start of the set then `None` is returned
2220    /// and the cursor is not moved.
2221    #[unstable(feature = "btree_cursors", issue = "107540")]
2222    pub fn prev(&mut self) -> Option<&'a K> {
2223        self.inner.prev().map(|(k, _)| k)
2224    }
2225
2226    /// Returns a reference to next element without moving the cursor.
2227    ///
2228    /// If the cursor is at the end of the set then `None` is returned
2229    #[unstable(feature = "btree_cursors", issue = "107540")]
2230    pub fn peek_next(&self) -> Option<&'a K> {
2231        self.inner.peek_next().map(|(k, _)| k)
2232    }
2233
2234    /// Returns a reference to the previous element without moving the cursor.
2235    ///
2236    /// If the cursor is at the start of the set then `None` is returned.
2237    #[unstable(feature = "btree_cursors", issue = "107540")]
2238    pub fn peek_prev(&self) -> Option<&'a K> {
2239        self.inner.peek_prev().map(|(k, _)| k)
2240    }
2241}
2242
2243impl<'a, T, A> CursorMut<'a, T, A> {
2244    /// Advances the cursor to the next gap, returning the element that it
2245    /// moved over.
2246    ///
2247    /// If the cursor is already at the end of the set then `None` is returned
2248    /// and the cursor is not moved.
2249    #[unstable(feature = "btree_cursors", issue = "107540")]
2250    pub fn next(&mut self) -> Option<&T> {
2251        self.inner.next().map(|(k, _)| k)
2252    }
2253
2254    /// Advances the cursor to the previous gap, returning the element that it
2255    /// moved over.
2256    ///
2257    /// If the cursor is already at the start of the set then `None` is returned
2258    /// and the cursor is not moved.
2259    #[unstable(feature = "btree_cursors", issue = "107540")]
2260    pub fn prev(&mut self) -> Option<&T> {
2261        self.inner.prev().map(|(k, _)| k)
2262    }
2263
2264    /// Returns a reference to the next element without moving the cursor.
2265    ///
2266    /// If the cursor is at the end of the set then `None` is returned.
2267    #[unstable(feature = "btree_cursors", issue = "107540")]
2268    pub fn peek_next(&mut self) -> Option<&T> {
2269        self.inner.peek_next().map(|(k, _)| k)
2270    }
2271
2272    /// Returns a reference to the previous element without moving the cursor.
2273    ///
2274    /// If the cursor is at the start of the set then `None` is returned.
2275    #[unstable(feature = "btree_cursors", issue = "107540")]
2276    pub fn peek_prev(&mut self) -> Option<&T> {
2277        self.inner.peek_prev().map(|(k, _)| k)
2278    }
2279
2280    /// Returns a read-only cursor pointing to the same location as the
2281    /// `CursorMut`.
2282    ///
2283    /// The lifetime of the returned `Cursor` is bound to that of the
2284    /// `CursorMut`, which means it cannot outlive the `CursorMut` and that the
2285    /// `CursorMut` is frozen for the lifetime of the `Cursor`.
2286    #[unstable(feature = "btree_cursors", issue = "107540")]
2287    pub fn as_cursor(&self) -> Cursor<'_, T> {
2288        Cursor { inner: self.inner.as_cursor() }
2289    }
2290
2291    /// Converts the cursor into a [`CursorMutKey`], which allows mutating
2292    /// elements in the tree.
2293    ///
2294    /// # Safety
2295    ///
2296    /// Since this cursor allows mutating elements, you must ensure that the
2297    /// `BTreeSet` invariants are maintained. Specifically:
2298    ///
2299    /// * The newly inserted element must be unique in the tree.
2300    /// * All elements in the tree must remain in sorted order.
2301    #[unstable(feature = "btree_cursors", issue = "107540")]
2302    pub unsafe fn with_mutable_key(self) -> CursorMutKey<'a, T, A> {
2303        CursorMutKey { inner: unsafe { self.inner.with_mutable_key() } }
2304    }
2305}
2306
2307impl<'a, T, A> CursorMutKey<'a, T, A> {
2308    /// Advances the cursor to the next gap, returning the  element that it
2309    /// moved over.
2310    ///
2311    /// If the cursor is already at the end of the set then `None` is returned
2312    /// and the cursor is not moved.
2313    #[unstable(feature = "btree_cursors", issue = "107540")]
2314    pub fn next(&mut self) -> Option<&mut T> {
2315        self.inner.next().map(|(k, _)| k)
2316    }
2317
2318    /// Advances the cursor to the previous gap, returning the element that it
2319    /// moved over.
2320    ///
2321    /// If the cursor is already at the start of the set then `None` is returned
2322    /// and the cursor is not moved.
2323    #[unstable(feature = "btree_cursors", issue = "107540")]
2324    pub fn prev(&mut self) -> Option<&mut T> {
2325        self.inner.prev().map(|(k, _)| k)
2326    }
2327
2328    /// Returns a reference to the next element without moving the cursor.
2329    ///
2330    /// If the cursor is at the end of the set then `None` is returned
2331    #[unstable(feature = "btree_cursors", issue = "107540")]
2332    pub fn peek_next(&mut self) -> Option<&mut T> {
2333        self.inner.peek_next().map(|(k, _)| k)
2334    }
2335
2336    /// Returns a reference to the previous element without moving the cursor.
2337    ///
2338    /// If the cursor is at the start of the set then `None` is returned.
2339    #[unstable(feature = "btree_cursors", issue = "107540")]
2340    pub fn peek_prev(&mut self) -> Option<&mut T> {
2341        self.inner.peek_prev().map(|(k, _)| k)
2342    }
2343
2344    /// Returns a read-only cursor pointing to the same location as the
2345    /// `CursorMutKey`.
2346    ///
2347    /// The lifetime of the returned `Cursor` is bound to that of the
2348    /// `CursorMutKey`, which means it cannot outlive the `CursorMutKey` and that the
2349    /// `CursorMutKey` is frozen for the lifetime of the `Cursor`.
2350    #[unstable(feature = "btree_cursors", issue = "107540")]
2351    pub fn as_cursor(&self) -> Cursor<'_, T> {
2352        Cursor { inner: self.inner.as_cursor() }
2353    }
2354}
2355
2356impl<'a, T: Ord, A: Allocator + Clone> CursorMut<'a, T, A> {
2357    /// Inserts a new element into the set in the gap that the
2358    /// cursor is currently pointing to.
2359    ///
2360    /// After the insertion the cursor will be pointing at the gap before the
2361    /// newly inserted element.
2362    ///
2363    /// # Safety
2364    ///
2365    /// You must ensure that the `BTreeSet` invariants are maintained.
2366    /// Specifically:
2367    ///
2368    /// * The newly inserted element must be unique in the tree.
2369    /// * All elements in the tree must remain in sorted order.
2370    #[unstable(feature = "btree_cursors", issue = "107540")]
2371    pub unsafe fn insert_after_unchecked(&mut self, value: T) {
2372        unsafe { self.inner.insert_after_unchecked(value, SetValZST) }
2373    }
2374
2375    /// Inserts a new element into the set in the gap that the
2376    /// cursor is currently pointing to.
2377    ///
2378    /// After the insertion the cursor will be pointing at the gap after the
2379    /// newly inserted element.
2380    ///
2381    /// # Safety
2382    ///
2383    /// You must ensure that the `BTreeSet` invariants are maintained.
2384    /// Specifically:
2385    ///
2386    /// * The newly inserted element must be unique in the tree.
2387    /// * All elements in the tree must remain in sorted order.
2388    #[unstable(feature = "btree_cursors", issue = "107540")]
2389    pub unsafe fn insert_before_unchecked(&mut self, value: T) {
2390        unsafe { self.inner.insert_before_unchecked(value, SetValZST) }
2391    }
2392
2393    /// Inserts a new element into the set in the gap that the
2394    /// cursor is currently pointing to.
2395    ///
2396    /// After the insertion the cursor will be pointing at the gap before the
2397    /// newly inserted element.
2398    ///
2399    /// If the inserted element is not greater than the element before the
2400    /// cursor (if any), or if it not less than the element after the cursor (if
2401    /// any), then an [`UnorderedKeyError`] is returned since this would
2402    /// invalidate the [`Ord`] invariant between the elements of the set.
2403    #[unstable(feature = "btree_cursors", issue = "107540")]
2404    pub fn insert_after(&mut self, value: T) -> Result<(), UnorderedKeyError> {
2405        self.inner.insert_after(value, SetValZST)
2406    }
2407
2408    /// Inserts a new element into the set in the gap that the
2409    /// cursor is currently pointing to.
2410    ///
2411    /// After the insertion the cursor will be pointing at the gap after the
2412    /// newly inserted element.
2413    ///
2414    /// If the inserted element is not greater than the element before the
2415    /// cursor (if any), or if it not less than the element after the cursor (if
2416    /// any), then an [`UnorderedKeyError`] is returned since this would
2417    /// invalidate the [`Ord`] invariant between the elements of the set.
2418    #[unstable(feature = "btree_cursors", issue = "107540")]
2419    pub fn insert_before(&mut self, value: T) -> Result<(), UnorderedKeyError> {
2420        self.inner.insert_before(value, SetValZST)
2421    }
2422
2423    /// Removes the next element from the `BTreeSet`.
2424    ///
2425    /// The element that was removed is returned. The cursor position is
2426    /// unchanged (before the removed element).
2427    #[unstable(feature = "btree_cursors", issue = "107540")]
2428    pub fn remove_next(&mut self) -> Option<T> {
2429        self.inner.remove_next().map(|(k, _)| k)
2430    }
2431
2432    /// Removes the preceding element from the `BTreeSet`.
2433    ///
2434    /// The element that was removed is returned. The cursor position is
2435    /// unchanged (after the removed element).
2436    #[unstable(feature = "btree_cursors", issue = "107540")]
2437    pub fn remove_prev(&mut self) -> Option<T> {
2438        self.inner.remove_prev().map(|(k, _)| k)
2439    }
2440}
2441
2442impl<'a, T: Ord, A: Allocator + Clone> CursorMutKey<'a, T, A> {
2443    /// Inserts a new element into the set in the gap that the
2444    /// cursor is currently pointing to.
2445    ///
2446    /// After the insertion the cursor will be pointing at the gap before the
2447    /// newly inserted element.
2448    ///
2449    /// # Safety
2450    ///
2451    /// You must ensure that the `BTreeSet` invariants are maintained.
2452    /// Specifically:
2453    ///
2454    /// * The key of the newly inserted element must be unique in the tree.
2455    /// * All elements in the tree must remain in sorted order.
2456    #[unstable(feature = "btree_cursors", issue = "107540")]
2457    pub unsafe fn insert_after_unchecked(&mut self, value: T) {
2458        unsafe { self.inner.insert_after_unchecked(value, SetValZST) }
2459    }
2460
2461    /// Inserts a new element into the set in the gap that the
2462    /// cursor is currently pointing to.
2463    ///
2464    /// After the insertion the cursor will be pointing at the gap after the
2465    /// newly inserted element.
2466    ///
2467    /// # Safety
2468    ///
2469    /// You must ensure that the `BTreeSet` invariants are maintained.
2470    /// Specifically:
2471    ///
2472    /// * The newly inserted element must be unique in the tree.
2473    /// * All elements in the tree must remain in sorted order.
2474    #[unstable(feature = "btree_cursors", issue = "107540")]
2475    pub unsafe fn insert_before_unchecked(&mut self, value: T) {
2476        unsafe { self.inner.insert_before_unchecked(value, SetValZST) }
2477    }
2478
2479    /// Inserts a new element into the set in the gap that the
2480    /// cursor is currently pointing to.
2481    ///
2482    /// After the insertion the cursor will be pointing at the gap before the
2483    /// newly inserted element.
2484    ///
2485    /// If the inserted element is not greater than the element before the
2486    /// cursor (if any), or if it not less than the element after the cursor (if
2487    /// any), then an [`UnorderedKeyError`] is returned since this would
2488    /// invalidate the [`Ord`] invariant between the elements of the set.
2489    #[unstable(feature = "btree_cursors", issue = "107540")]
2490    pub fn insert_after(&mut self, value: T) -> Result<(), UnorderedKeyError> {
2491        self.inner.insert_after(value, SetValZST)
2492    }
2493
2494    /// Inserts a new element into the set in the gap that the
2495    /// cursor is currently pointing to.
2496    ///
2497    /// After the insertion the cursor will be pointing at the gap after the
2498    /// newly inserted element.
2499    ///
2500    /// If the inserted element is not greater than the element before the
2501    /// cursor (if any), or if it not less than the element after the cursor (if
2502    /// any), then an [`UnorderedKeyError`] is returned since this would
2503    /// invalidate the [`Ord`] invariant between the elements of the set.
2504    #[unstable(feature = "btree_cursors", issue = "107540")]
2505    pub fn insert_before(&mut self, value: T) -> Result<(), UnorderedKeyError> {
2506        self.inner.insert_before(value, SetValZST)
2507    }
2508
2509    /// Removes the next element from the `BTreeSet`.
2510    ///
2511    /// The element that was removed is returned. The cursor position is
2512    /// unchanged (before the removed element).
2513    #[unstable(feature = "btree_cursors", issue = "107540")]
2514    pub fn remove_next(&mut self) -> Option<T> {
2515        self.inner.remove_next().map(|(k, _)| k)
2516    }
2517
2518    /// Removes the preceding element from the `BTreeSet`.
2519    ///
2520    /// The element that was removed is returned. The cursor position is
2521    /// unchanged (after the removed element).
2522    #[unstable(feature = "btree_cursors", issue = "107540")]
2523    pub fn remove_prev(&mut self) -> Option<T> {
2524        self.inner.remove_prev().map(|(k, _)| k)
2525    }
2526}
2527
2528#[unstable(feature = "btree_cursors", issue = "107540")]
2529pub use super::map::UnorderedKeyError;
2530
2531#[cfg(test)]
2532mod tests;