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::{AllocatorClone, 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_ext", issue = "163177", implied_by = "allocator_api")] A: AllocatorClone = Global,
81> {
82    map: BTreeMap<T, SetValZST, A>,
83}
84
85#[stable(feature = "rust1", since = "1.0.0")]
86impl<T: Hash, A: AllocatorClone> 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: AllocatorClone> 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: AllocatorClone> Eq for BTreeSet<T, A> {}
101
102#[stable(feature = "rust1", since = "1.0.0")]
103impl<T: PartialOrd, A: AllocatorClone> 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: AllocatorClone> 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: AllocatorClone> 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_ext", issue = "163177", implied_by = "allocator_api")] A: AllocatorClone = 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_ext", issue = "163177", implied_by = "allocator_api")] A: AllocatorClone = Global,
187> {
188    inner: DifferenceInner<'a, T, A>,
189}
190enum DifferenceInner<'a, T: 'a, A: AllocatorClone> {
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: AllocatorClone> 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: AllocatorClone> 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_ext", issue = "163177", implied_by = "allocator_api")] A: AllocatorClone = Global,
261> {
262    inner: IntersectionInner<'a, T, A>,
263}
264enum IntersectionInner<'a, T: 'a, A: AllocatorClone> {
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: AllocatorClone> 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: AllocatorClone> 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: AllocatorClone> 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(btreemap_alloc)]
357    ///
358    /// use std::collections::BTreeSet;
359    /// use std::alloc::Global;
360    ///
361    /// let set: BTreeSet<i32> = BTreeSet::new_in(Global);
362    /// ```
363    #[unstable(feature = "btreemap_alloc", issue = "163177")]
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).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_stable(feature = "const_btree_len", since = "CURRENT_RUSTC_VERSION")]
1263    #[rustc_confusables("length", "size")]
1264    pub const fn len(&self) -> usize {
1265        self.map.len()
1266    }
1267
1268    /// Returns `true` if the set contains no elements.
1269    ///
1270    /// # Examples
1271    ///
1272    /// ```
1273    /// use std::collections::BTreeSet;
1274    ///
1275    /// let mut v = BTreeSet::new();
1276    /// assert!(v.is_empty());
1277    /// v.insert(1);
1278    /// assert!(!v.is_empty());
1279    /// ```
1280    #[must_use]
1281    #[stable(feature = "rust1", since = "1.0.0")]
1282    #[rustc_const_stable(feature = "const_btree_len", since = "CURRENT_RUSTC_VERSION")]
1283    pub const fn is_empty(&self) -> bool {
1284        self.len() == 0
1285    }
1286
1287    /// Returns a [`Cursor`] pointing at the gap before the smallest element
1288    /// greater than the given bound.
1289    ///
1290    /// Passing `Bound::Included(x)` will return a cursor pointing to the
1291    /// gap before the smallest element greater than or equal to `x`.
1292    ///
1293    /// Passing `Bound::Excluded(x)` will return a cursor pointing to the
1294    /// gap before the smallest element greater than `x`.
1295    ///
1296    /// Passing `Bound::Unbounded` will return a cursor pointing to the
1297    /// gap before the smallest element in the set.
1298    ///
1299    /// # Examples
1300    ///
1301    /// ```
1302    /// #![feature(btree_cursors)]
1303    ///
1304    /// use std::collections::BTreeSet;
1305    /// use std::ops::Bound;
1306    ///
1307    /// let set = BTreeSet::from([1, 2, 3, 4]);
1308    ///
1309    /// let cursor = set.lower_bound(Bound::Included(&2));
1310    /// assert_eq!(cursor.peek_prev(), Some(&1));
1311    /// assert_eq!(cursor.peek_next(), Some(&2));
1312    ///
1313    /// let cursor = set.lower_bound(Bound::Excluded(&2));
1314    /// assert_eq!(cursor.peek_prev(), Some(&2));
1315    /// assert_eq!(cursor.peek_next(), Some(&3));
1316    ///
1317    /// let cursor = set.lower_bound(Bound::Unbounded);
1318    /// assert_eq!(cursor.peek_prev(), None);
1319    /// assert_eq!(cursor.peek_next(), Some(&1));
1320    /// ```
1321    #[unstable(feature = "btree_cursors", issue = "107540")]
1322    pub fn lower_bound<Q: ?Sized>(&self, bound: Bound<&Q>) -> Cursor<'_, T>
1323    where
1324        T: Borrow<Q> + Ord,
1325        Q: Ord,
1326    {
1327        Cursor { inner: self.map.lower_bound(bound) }
1328    }
1329
1330    /// Returns a [`CursorMut`] pointing at the gap before the smallest element
1331    /// greater than the given bound.
1332    ///
1333    /// Passing `Bound::Included(x)` will return a cursor pointing to the
1334    /// gap before the smallest element greater than or equal to `x`.
1335    ///
1336    /// Passing `Bound::Excluded(x)` will return a cursor pointing to the
1337    /// gap before the smallest element greater than `x`.
1338    ///
1339    /// Passing `Bound::Unbounded` will return a cursor pointing to the
1340    /// gap before the smallest element in the set.
1341    ///
1342    /// # Examples
1343    ///
1344    /// ```
1345    /// #![feature(btree_cursors)]
1346    ///
1347    /// use std::collections::BTreeSet;
1348    /// use std::ops::Bound;
1349    ///
1350    /// let mut set = BTreeSet::from([1, 2, 3, 4]);
1351    ///
1352    /// let mut cursor = set.lower_bound_mut(Bound::Included(&2));
1353    /// assert_eq!(cursor.peek_prev(), Some(&1));
1354    /// assert_eq!(cursor.peek_next(), Some(&2));
1355    ///
1356    /// let mut cursor = set.lower_bound_mut(Bound::Excluded(&2));
1357    /// assert_eq!(cursor.peek_prev(), Some(&2));
1358    /// assert_eq!(cursor.peek_next(), Some(&3));
1359    ///
1360    /// let mut cursor = set.lower_bound_mut(Bound::Unbounded);
1361    /// assert_eq!(cursor.peek_prev(), None);
1362    /// assert_eq!(cursor.peek_next(), Some(&1));
1363    /// ```
1364    #[unstable(feature = "btree_cursors", issue = "107540")]
1365    pub fn lower_bound_mut<Q: ?Sized>(&mut self, bound: Bound<&Q>) -> CursorMut<'_, T, A>
1366    where
1367        T: Borrow<Q> + Ord,
1368        Q: Ord,
1369    {
1370        CursorMut { inner: self.map.lower_bound_mut(bound) }
1371    }
1372
1373    /// Returns a [`Cursor`] pointing at the gap after the greatest element
1374    /// smaller than the given bound.
1375    ///
1376    /// Passing `Bound::Included(x)` will return a cursor pointing to the
1377    /// gap after the greatest element smaller than or equal to `x`.
1378    ///
1379    /// Passing `Bound::Excluded(x)` will return a cursor pointing to the
1380    /// gap after the greatest element smaller than `x`.
1381    ///
1382    /// Passing `Bound::Unbounded` will return a cursor pointing to the
1383    /// gap after the greatest element in the set.
1384    ///
1385    /// # Examples
1386    ///
1387    /// ```
1388    /// #![feature(btree_cursors)]
1389    ///
1390    /// use std::collections::BTreeSet;
1391    /// use std::ops::Bound;
1392    ///
1393    /// let set = BTreeSet::from([1, 2, 3, 4]);
1394    ///
1395    /// let cursor = set.upper_bound(Bound::Included(&3));
1396    /// assert_eq!(cursor.peek_prev(), Some(&3));
1397    /// assert_eq!(cursor.peek_next(), Some(&4));
1398    ///
1399    /// let cursor = set.upper_bound(Bound::Excluded(&3));
1400    /// assert_eq!(cursor.peek_prev(), Some(&2));
1401    /// assert_eq!(cursor.peek_next(), Some(&3));
1402    ///
1403    /// let cursor = set.upper_bound(Bound::Unbounded);
1404    /// assert_eq!(cursor.peek_prev(), Some(&4));
1405    /// assert_eq!(cursor.peek_next(), None);
1406    /// ```
1407    #[unstable(feature = "btree_cursors", issue = "107540")]
1408    pub fn upper_bound<Q: ?Sized>(&self, bound: Bound<&Q>) -> Cursor<'_, T>
1409    where
1410        T: Borrow<Q> + Ord,
1411        Q: Ord,
1412    {
1413        Cursor { inner: self.map.upper_bound(bound) }
1414    }
1415
1416    /// Returns a [`CursorMut`] pointing at the gap after the greatest element
1417    /// smaller than the given bound.
1418    ///
1419    /// Passing `Bound::Included(x)` will return a cursor pointing to the
1420    /// gap after the greatest element smaller than or equal to `x`.
1421    ///
1422    /// Passing `Bound::Excluded(x)` will return a cursor pointing to the
1423    /// gap after the greatest element smaller than `x`.
1424    ///
1425    /// Passing `Bound::Unbounded` will return a cursor pointing to the
1426    /// gap after the greatest element in the set.
1427    ///
1428    /// # Examples
1429    ///
1430    /// ```
1431    /// #![feature(btree_cursors)]
1432    ///
1433    /// use std::collections::BTreeSet;
1434    /// use std::ops::Bound;
1435    ///
1436    /// let mut set = BTreeSet::from([1, 2, 3, 4]);
1437    ///
1438    /// let mut cursor = set.upper_bound_mut(Bound::Included(&3));
1439    /// assert_eq!(cursor.peek_prev(), Some(&3));
1440    /// assert_eq!(cursor.peek_next(), Some(&4));
1441    ///
1442    /// let mut cursor = set.upper_bound_mut(Bound::Excluded(&3));
1443    /// assert_eq!(cursor.peek_prev(), Some(&2));
1444    /// assert_eq!(cursor.peek_next(), Some(&3));
1445    ///
1446    /// let mut cursor = set.upper_bound_mut(Bound::Unbounded);
1447    /// assert_eq!(cursor.peek_prev(), Some(&4));
1448    /// assert_eq!(cursor.peek_next(), None);
1449    /// ```
1450    #[unstable(feature = "btree_cursors", issue = "107540")]
1451    pub fn upper_bound_mut<Q: ?Sized>(&mut self, bound: Bound<&Q>) -> CursorMut<'_, T, A>
1452    where
1453        T: Borrow<Q> + Ord,
1454        Q: Ord,
1455    {
1456        CursorMut { inner: self.map.upper_bound_mut(bound) }
1457    }
1458}
1459
1460#[stable(feature = "rust1", since = "1.0.0")]
1461impl<T: Ord> FromIterator<T> for BTreeSet<T> {
1462    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> BTreeSet<T> {
1463        let mut inputs: Vec<_> = iter.into_iter().collect();
1464
1465        if inputs.is_empty() {
1466            return BTreeSet::new();
1467        }
1468
1469        // use stable sort to preserve the insertion order.
1470        inputs.sort();
1471        BTreeSet::from_sorted_iter(inputs.into_iter(), Global)
1472    }
1473}
1474
1475impl<T: Ord, A: AllocatorClone> BTreeSet<T, A> {
1476    fn from_sorted_iter<I: Iterator<Item = T>>(iter: I, alloc: A) -> BTreeSet<T, A> {
1477        let iter = iter.map(|k| (k, SetValZST));
1478        let map = BTreeMap::bulk_build_from_sorted_iter(iter, alloc);
1479        BTreeSet { map }
1480    }
1481}
1482
1483#[stable(feature = "std_collections_from_array", since = "1.56.0")]
1484impl<T: Ord, const N: usize> From<[T; N]> for BTreeSet<T> {
1485    /// Converts a `[T; N]` into a `BTreeSet<T>`.
1486    ///
1487    /// If the array contains any equal values,
1488    /// all but one will be dropped.
1489    ///
1490    /// # Examples
1491    ///
1492    /// ```
1493    /// use std::collections::BTreeSet;
1494    ///
1495    /// let set1 = BTreeSet::from([1, 2, 3, 4]);
1496    /// let set2: BTreeSet<_> = [1, 2, 3, 4].into();
1497    /// assert_eq!(set1, set2);
1498    /// ```
1499    fn from(mut arr: [T; N]) -> Self {
1500        if N == 0 {
1501            return BTreeSet::new();
1502        }
1503
1504        // use stable sort to preserve the insertion order.
1505        arr.sort();
1506        BTreeSet::from_sorted_iter(IntoIterator::into_iter(arr), Global)
1507    }
1508}
1509
1510#[stable(feature = "rust1", since = "1.0.0")]
1511impl<T, A: AllocatorClone> IntoIterator for BTreeSet<T, A> {
1512    type Item = T;
1513    type IntoIter = IntoIter<T, A>;
1514
1515    /// Gets an iterator for moving out the `BTreeSet`'s contents in ascending order.
1516    ///
1517    /// # Examples
1518    ///
1519    /// ```
1520    /// use std::collections::BTreeSet;
1521    ///
1522    /// let set = BTreeSet::from([1, 2, 3, 4]);
1523    ///
1524    /// let v: Vec<_> = set.into_iter().collect();
1525    /// assert_eq!(v, [1, 2, 3, 4]);
1526    /// ```
1527    fn into_iter(self) -> IntoIter<T, A> {
1528        IntoIter { iter: self.map.into_iter() }
1529    }
1530}
1531
1532#[stable(feature = "rust1", since = "1.0.0")]
1533impl<'a, T, A: AllocatorClone> IntoIterator for &'a BTreeSet<T, A> {
1534    type Item = &'a T;
1535    type IntoIter = Iter<'a, T>;
1536
1537    fn into_iter(self) -> Iter<'a, T> {
1538        self.iter()
1539    }
1540}
1541
1542/// This `struct` is created by the [`extract_if`] method on [`BTreeSet`].
1543///
1544/// [`extract_if`]: BTreeSet::extract_if
1545#[stable(feature = "btree_extract_if", since = "1.91.0")]
1546#[must_use = "iterators are lazy and do nothing unless consumed; \
1547    use `retain` or `extract_if().for_each(drop)` to remove and discard elements"]
1548pub struct ExtractIf<
1549    'a,
1550    T,
1551    R,
1552    F,
1553    #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] A: AllocatorClone = Global,
1554> {
1555    pred: F,
1556    inner: super::map::ExtractIfInner<'a, T, SetValZST, R>,
1557    /// The BTreeMap will outlive this IntoIter so we don't care about drop order for `alloc`.
1558    alloc: A,
1559}
1560
1561#[stable(feature = "btree_extract_if", since = "1.91.0")]
1562impl<T, R, F, A> fmt::Debug for ExtractIf<'_, T, R, F, A>
1563where
1564    T: fmt::Debug,
1565    A: AllocatorClone,
1566{
1567    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1568        f.debug_struct("ExtractIf")
1569            .field("peek", &self.inner.peek().map(|(k, _)| k))
1570            .finish_non_exhaustive()
1571    }
1572}
1573
1574#[stable(feature = "btree_extract_if", since = "1.91.0")]
1575impl<T, R, F, A: AllocatorClone> Iterator for ExtractIf<'_, T, R, F, A>
1576where
1577    T: PartialOrd,
1578    R: RangeBounds<T>,
1579    F: FnMut(&T) -> bool,
1580{
1581    type Item = T;
1582
1583    fn next(&mut self) -> Option<T> {
1584        let pred = &mut self.pred;
1585        let mut mapped_pred = |k: &T, _v: &mut SetValZST| pred(k);
1586        self.inner.next(&mut mapped_pred, self.alloc.clone()).map(|(k, _)| k)
1587    }
1588
1589    fn size_hint(&self) -> (usize, Option<usize>) {
1590        self.inner.size_hint()
1591    }
1592}
1593
1594#[stable(feature = "btree_extract_if", since = "1.91.0")]
1595impl<T, R, F, A: AllocatorClone> FusedIterator for ExtractIf<'_, T, R, F, A>
1596where
1597    T: PartialOrd,
1598    R: RangeBounds<T>,
1599    F: FnMut(&T) -> bool,
1600{
1601}
1602
1603#[stable(feature = "rust1", since = "1.0.0")]
1604impl<T: Ord, A: AllocatorClone> Extend<T> for BTreeSet<T, A> {
1605    #[inline]
1606    fn extend<Iter: IntoIterator<Item = T>>(&mut self, iter: Iter) {
1607        iter.into_iter().for_each(move |elem| {
1608            self.insert(elem);
1609        });
1610    }
1611
1612    #[inline]
1613    fn extend_one(&mut self, elem: T) {
1614        self.insert(elem);
1615    }
1616}
1617
1618#[stable(feature = "extend_ref", since = "1.2.0")]
1619impl<'a, T: 'a + Ord + Copy, A: AllocatorClone> Extend<&'a T> for BTreeSet<T, A> {
1620    fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
1621        self.extend(iter.into_iter().cloned());
1622    }
1623
1624    #[inline]
1625    fn extend_one(&mut self, &elem: &'a T) {
1626        self.insert(elem);
1627    }
1628}
1629
1630#[stable(feature = "rust1", since = "1.0.0")]
1631impl<T> Default for BTreeSet<T> {
1632    /// Creates an empty `BTreeSet`.
1633    fn default() -> BTreeSet<T> {
1634        BTreeSet::new()
1635    }
1636}
1637
1638#[stable(feature = "rust1", since = "1.0.0")]
1639impl<T: Ord + Clone, A: AllocatorClone> Sub<&BTreeSet<T, A>> for &BTreeSet<T, A> {
1640    type Output = BTreeSet<T, A>;
1641
1642    /// Returns the difference of `self` and `rhs` as a new `BTreeSet<T>`.
1643    ///
1644    /// # Examples
1645    ///
1646    /// ```
1647    /// use std::collections::BTreeSet;
1648    ///
1649    /// let a = BTreeSet::from([1, 2, 3]);
1650    /// let b = BTreeSet::from([3, 4, 5]);
1651    ///
1652    /// let result = &a - &b;
1653    /// assert_eq!(result, BTreeSet::from([1, 2]));
1654    /// ```
1655    fn sub(self, rhs: &BTreeSet<T, A>) -> BTreeSet<T, A> {
1656        BTreeSet::from_sorted_iter(
1657            self.difference(rhs).cloned(),
1658            ManuallyDrop::into_inner(self.map.alloc.clone()),
1659        )
1660    }
1661}
1662
1663#[stable(feature = "rust1", since = "1.0.0")]
1664impl<T: Ord + Clone, A: AllocatorClone> BitXor<&BTreeSet<T, A>> for &BTreeSet<T, A> {
1665    type Output = BTreeSet<T, A>;
1666
1667    /// Returns the symmetric difference of `self` and `rhs` as a new `BTreeSet<T>`.
1668    ///
1669    /// # Examples
1670    ///
1671    /// ```
1672    /// use std::collections::BTreeSet;
1673    ///
1674    /// let a = BTreeSet::from([1, 2, 3]);
1675    /// let b = BTreeSet::from([2, 3, 4]);
1676    ///
1677    /// let result = &a ^ &b;
1678    /// assert_eq!(result, BTreeSet::from([1, 4]));
1679    /// ```
1680    fn bitxor(self, rhs: &BTreeSet<T, A>) -> BTreeSet<T, A> {
1681        BTreeSet::from_sorted_iter(
1682            self.symmetric_difference(rhs).cloned(),
1683            ManuallyDrop::into_inner(self.map.alloc.clone()),
1684        )
1685    }
1686}
1687
1688#[stable(feature = "rust1", since = "1.0.0")]
1689impl<T: Ord + Clone, A: AllocatorClone> BitAnd<&BTreeSet<T, A>> for &BTreeSet<T, A> {
1690    type Output = BTreeSet<T, A>;
1691
1692    /// Returns the intersection of `self` and `rhs` as a new `BTreeSet<T>`.
1693    ///
1694    /// # Examples
1695    ///
1696    /// ```
1697    /// use std::collections::BTreeSet;
1698    ///
1699    /// let a = BTreeSet::from([1, 2, 3]);
1700    /// let b = BTreeSet::from([2, 3, 4]);
1701    ///
1702    /// let result = &a & &b;
1703    /// assert_eq!(result, BTreeSet::from([2, 3]));
1704    /// ```
1705    fn bitand(self, rhs: &BTreeSet<T, A>) -> BTreeSet<T, A> {
1706        BTreeSet::from_sorted_iter(
1707            self.intersection(rhs).cloned(),
1708            ManuallyDrop::into_inner(self.map.alloc.clone()),
1709        )
1710    }
1711}
1712
1713#[stable(feature = "rust1", since = "1.0.0")]
1714impl<T: Ord + Clone, A: AllocatorClone> BitOr<&BTreeSet<T, A>> for &BTreeSet<T, A> {
1715    type Output = BTreeSet<T, A>;
1716
1717    /// Returns the union of `self` and `rhs` as a new `BTreeSet<T>`.
1718    ///
1719    /// # Examples
1720    ///
1721    /// ```
1722    /// use std::collections::BTreeSet;
1723    ///
1724    /// let a = BTreeSet::from([1, 2, 3]);
1725    /// let b = BTreeSet::from([3, 4, 5]);
1726    ///
1727    /// let result = &a | &b;
1728    /// assert_eq!(result, BTreeSet::from([1, 2, 3, 4, 5]));
1729    /// ```
1730    fn bitor(self, rhs: &BTreeSet<T, A>) -> BTreeSet<T, A> {
1731        BTreeSet::from_sorted_iter(
1732            self.union(rhs).cloned(),
1733            ManuallyDrop::into_inner(self.map.alloc.clone()),
1734        )
1735    }
1736}
1737
1738#[stable(feature = "rust1", since = "1.0.0")]
1739impl<T: Debug, A: AllocatorClone> Debug for BTreeSet<T, A> {
1740    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1741        f.debug_set().entries(self.iter()).finish()
1742    }
1743}
1744
1745#[stable(feature = "rust1", since = "1.0.0")]
1746impl<T> Clone for Iter<'_, T> {
1747    fn clone(&self) -> Self {
1748        Iter { iter: self.iter.clone() }
1749    }
1750}
1751
1752#[stable(feature = "rust1", since = "1.0.0")]
1753impl<'a, T> Iterator for Iter<'a, T> {
1754    type Item = &'a T;
1755
1756    fn next(&mut self) -> Option<&'a T> {
1757        self.iter.next()
1758    }
1759
1760    fn size_hint(&self) -> (usize, Option<usize>) {
1761        self.iter.size_hint()
1762    }
1763
1764    fn last(mut self) -> Option<&'a T> {
1765        self.next_back()
1766    }
1767
1768    fn min(mut self) -> Option<&'a T>
1769    where
1770        &'a T: Ord,
1771    {
1772        self.next()
1773    }
1774
1775    fn max(mut self) -> Option<&'a T>
1776    where
1777        &'a T: Ord,
1778    {
1779        self.next_back()
1780    }
1781}
1782
1783#[stable(feature = "rust1", since = "1.0.0")]
1784impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
1785    fn next_back(&mut self) -> Option<&'a T> {
1786        self.iter.next_back()
1787    }
1788}
1789
1790#[stable(feature = "rust1", since = "1.0.0")]
1791impl<T> ExactSizeIterator for Iter<'_, T> {
1792    fn len(&self) -> usize {
1793        self.iter.len()
1794    }
1795}
1796
1797#[unstable(feature = "trusted_len", issue = "37572")]
1798unsafe impl<T> TrustedLen for Iter<'_, T> {}
1799
1800#[stable(feature = "fused", since = "1.26.0")]
1801impl<T> FusedIterator for Iter<'_, T> {}
1802
1803#[stable(feature = "rust1", since = "1.0.0")]
1804impl<T, A: AllocatorClone> Iterator for IntoIter<T, A> {
1805    type Item = T;
1806
1807    fn next(&mut self) -> Option<T> {
1808        self.iter.next().map(|(k, _)| k)
1809    }
1810
1811    fn size_hint(&self) -> (usize, Option<usize>) {
1812        self.iter.size_hint()
1813    }
1814}
1815
1816#[stable(feature = "default_iters", since = "1.70.0")]
1817impl<T> Default for Iter<'_, T> {
1818    /// Creates an empty `btree_set::Iter`.
1819    ///
1820    /// ```
1821    /// # use std::collections::btree_set;
1822    /// let iter: btree_set::Iter<'_, u8> = Default::default();
1823    /// assert_eq!(iter.len(), 0);
1824    /// ```
1825    fn default() -> Self {
1826        Iter { iter: Default::default() }
1827    }
1828}
1829
1830#[stable(feature = "rust1", since = "1.0.0")]
1831impl<T, A: AllocatorClone> DoubleEndedIterator for IntoIter<T, A> {
1832    fn next_back(&mut self) -> Option<T> {
1833        self.iter.next_back().map(|(k, _)| k)
1834    }
1835}
1836
1837#[stable(feature = "rust1", since = "1.0.0")]
1838impl<T, A: AllocatorClone> ExactSizeIterator for IntoIter<T, A> {
1839    fn len(&self) -> usize {
1840        self.iter.len()
1841    }
1842}
1843
1844#[unstable(feature = "trusted_len", issue = "37572")]
1845unsafe impl<T, A: AllocatorClone> TrustedLen for IntoIter<T, A> {}
1846
1847#[stable(feature = "fused", since = "1.26.0")]
1848impl<T, A: AllocatorClone> FusedIterator for IntoIter<T, A> {}
1849
1850#[stable(feature = "default_iters", since = "1.70.0")]
1851impl<T, A> Default for IntoIter<T, A>
1852where
1853    A: AllocatorClone + Default,
1854{
1855    /// Creates an empty `btree_set::IntoIter`.
1856    ///
1857    /// ```
1858    /// # use std::collections::btree_set;
1859    /// let iter: btree_set::IntoIter<u8> = Default::default();
1860    /// assert_eq!(iter.len(), 0);
1861    /// ```
1862    fn default() -> Self {
1863        IntoIter { iter: Default::default() }
1864    }
1865}
1866
1867#[stable(feature = "btree_range", since = "1.17.0")]
1868impl<T> Clone for Range<'_, T> {
1869    fn clone(&self) -> Self {
1870        Range { iter: self.iter.clone() }
1871    }
1872}
1873
1874#[stable(feature = "btree_range", since = "1.17.0")]
1875impl<'a, T> Iterator for Range<'a, T> {
1876    type Item = &'a T;
1877
1878    fn next(&mut self) -> Option<&'a T> {
1879        self.iter.next().map(|(k, _)| k)
1880    }
1881
1882    fn last(mut self) -> Option<&'a T> {
1883        self.next_back()
1884    }
1885
1886    fn min(mut self) -> Option<&'a T>
1887    where
1888        &'a T: Ord,
1889    {
1890        self.next()
1891    }
1892
1893    fn max(mut self) -> Option<&'a T>
1894    where
1895        &'a T: Ord,
1896    {
1897        self.next_back()
1898    }
1899}
1900
1901#[stable(feature = "btree_range", since = "1.17.0")]
1902impl<'a, T> DoubleEndedIterator for Range<'a, T> {
1903    fn next_back(&mut self) -> Option<&'a T> {
1904        self.iter.next_back().map(|(k, _)| k)
1905    }
1906}
1907
1908#[stable(feature = "fused", since = "1.26.0")]
1909impl<T> FusedIterator for Range<'_, T> {}
1910
1911#[stable(feature = "default_iters", since = "1.70.0")]
1912impl<T> Default for Range<'_, T> {
1913    /// Creates an empty `btree_set::Range`.
1914    ///
1915    /// ```
1916    /// # use std::collections::btree_set;
1917    /// let iter: btree_set::Range<'_, u8> = Default::default();
1918    /// assert_eq!(iter.count(), 0);
1919    /// ```
1920    fn default() -> Self {
1921        Range { iter: Default::default() }
1922    }
1923}
1924
1925#[stable(feature = "rust1", since = "1.0.0")]
1926impl<T, A: AllocatorClone> Clone for Difference<'_, T, A> {
1927    fn clone(&self) -> Self {
1928        Difference {
1929            inner: match &self.inner {
1930                DifferenceInner::Stitch { self_iter, other_iter } => DifferenceInner::Stitch {
1931                    self_iter: self_iter.clone(),
1932                    other_iter: other_iter.clone(),
1933                },
1934                DifferenceInner::Search { self_iter, other_set } => {
1935                    DifferenceInner::Search { self_iter: self_iter.clone(), other_set }
1936                }
1937                DifferenceInner::Iterate(iter) => DifferenceInner::Iterate(iter.clone()),
1938            },
1939        }
1940    }
1941}
1942#[stable(feature = "rust1", since = "1.0.0")]
1943impl<'a, T: Ord, A: AllocatorClone> Iterator for Difference<'a, T, A> {
1944    type Item = &'a T;
1945
1946    fn next(&mut self) -> Option<&'a T> {
1947        match &mut self.inner {
1948            DifferenceInner::Stitch { self_iter, other_iter } => {
1949                let mut self_next = self_iter.next()?;
1950                loop {
1951                    match other_iter.peek().map_or(Less, |other_next| self_next.cmp(other_next)) {
1952                        Less => return Some(self_next),
1953                        Equal => {
1954                            self_next = self_iter.next()?;
1955                            other_iter.next();
1956                        }
1957                        Greater => {
1958                            other_iter.next();
1959                        }
1960                    }
1961                }
1962            }
1963            DifferenceInner::Search { self_iter, other_set } => loop {
1964                let self_next = self_iter.next()?;
1965                if !other_set.contains(self_next) {
1966                    return Some(self_next);
1967                }
1968            },
1969            DifferenceInner::Iterate(iter) => iter.next(),
1970        }
1971    }
1972
1973    fn size_hint(&self) -> (usize, Option<usize>) {
1974        let (self_len, other_len) = match &self.inner {
1975            DifferenceInner::Stitch { self_iter, other_iter } => {
1976                (self_iter.len(), other_iter.len())
1977            }
1978            DifferenceInner::Search { self_iter, other_set } => (self_iter.len(), other_set.len()),
1979            DifferenceInner::Iterate(iter) => (iter.len(), 0),
1980        };
1981        (self_len.saturating_sub(other_len), Some(self_len))
1982    }
1983
1984    fn min(mut self) -> Option<&'a T> {
1985        self.next()
1986    }
1987}
1988
1989#[stable(feature = "fused", since = "1.26.0")]
1990impl<T: Ord, A: AllocatorClone> FusedIterator for Difference<'_, T, A> {}
1991
1992#[stable(feature = "rust1", since = "1.0.0")]
1993impl<T> Clone for SymmetricDifference<'_, T> {
1994    fn clone(&self) -> Self {
1995        SymmetricDifference(self.0.clone())
1996    }
1997}
1998#[stable(feature = "rust1", since = "1.0.0")]
1999impl<'a, T: Ord> Iterator for SymmetricDifference<'a, T> {
2000    type Item = &'a T;
2001
2002    fn next(&mut self) -> Option<&'a T> {
2003        loop {
2004            let (a_next, b_next) = self.0.nexts(Self::Item::cmp);
2005            if a_next.and(b_next).is_none() {
2006                return a_next.or(b_next);
2007            }
2008        }
2009    }
2010
2011    fn size_hint(&self) -> (usize, Option<usize>) {
2012        let (a_len, b_len) = self.0.lens();
2013        // No checked_add, because even if a and b refer to the same set,
2014        // and T is a zero-sized type, the storage overhead of sets limits
2015        // the number of elements to less than half the range of usize.
2016        (0, Some(a_len + b_len))
2017    }
2018
2019    fn min(mut self) -> Option<&'a T> {
2020        self.next()
2021    }
2022}
2023
2024#[stable(feature = "fused", since = "1.26.0")]
2025impl<T: Ord> FusedIterator for SymmetricDifference<'_, T> {}
2026
2027#[stable(feature = "rust1", since = "1.0.0")]
2028impl<T, A: AllocatorClone> Clone for Intersection<'_, T, A> {
2029    fn clone(&self) -> Self {
2030        Intersection {
2031            inner: match &self.inner {
2032                IntersectionInner::Stitch { a, b } => {
2033                    IntersectionInner::Stitch { a: a.clone(), b: b.clone() }
2034                }
2035                IntersectionInner::Search { small_iter, large_set } => {
2036                    IntersectionInner::Search { small_iter: small_iter.clone(), large_set }
2037                }
2038                IntersectionInner::Answer(answer) => IntersectionInner::Answer(*answer),
2039            },
2040        }
2041    }
2042}
2043#[stable(feature = "rust1", since = "1.0.0")]
2044impl<'a, T: Ord, A: AllocatorClone> Iterator for Intersection<'a, T, A> {
2045    type Item = &'a T;
2046
2047    fn next(&mut self) -> Option<&'a T> {
2048        match &mut self.inner {
2049            IntersectionInner::Stitch { a, b } => {
2050                let mut a_next = a.next()?;
2051                let mut b_next = b.next()?;
2052                loop {
2053                    match a_next.cmp(b_next) {
2054                        Less => a_next = a.next()?,
2055                        Greater => b_next = b.next()?,
2056                        Equal => return Some(a_next),
2057                    }
2058                }
2059            }
2060            IntersectionInner::Search { small_iter, large_set } => loop {
2061                let small_next = small_iter.next()?;
2062                if large_set.contains(small_next) {
2063                    return Some(small_next);
2064                }
2065            },
2066            IntersectionInner::Answer(answer) => answer.take(),
2067        }
2068    }
2069
2070    fn size_hint(&self) -> (usize, Option<usize>) {
2071        match &self.inner {
2072            IntersectionInner::Stitch { a, b } => (0, Some(min(a.len(), b.len()))),
2073            IntersectionInner::Search { small_iter, .. } => (0, Some(small_iter.len())),
2074            IntersectionInner::Answer(None) => (0, Some(0)),
2075            IntersectionInner::Answer(Some(_)) => (1, Some(1)),
2076        }
2077    }
2078
2079    fn min(mut self) -> Option<&'a T> {
2080        self.next()
2081    }
2082}
2083
2084#[stable(feature = "fused", since = "1.26.0")]
2085impl<T: Ord, A: AllocatorClone> FusedIterator for Intersection<'_, T, A> {}
2086
2087#[stable(feature = "rust1", since = "1.0.0")]
2088impl<T> Clone for Union<'_, T> {
2089    fn clone(&self) -> Self {
2090        Union(self.0.clone())
2091    }
2092}
2093#[stable(feature = "rust1", since = "1.0.0")]
2094impl<'a, T: Ord> Iterator for Union<'a, T> {
2095    type Item = &'a T;
2096
2097    fn next(&mut self) -> Option<&'a T> {
2098        let (a_next, b_next) = self.0.nexts(Self::Item::cmp);
2099        a_next.or(b_next)
2100    }
2101
2102    fn size_hint(&self) -> (usize, Option<usize>) {
2103        let (a_len, b_len) = self.0.lens();
2104        // No checked_add - see SymmetricDifference::size_hint.
2105        (max(a_len, b_len), Some(a_len + b_len))
2106    }
2107
2108    fn min(mut self) -> Option<&'a T> {
2109        self.next()
2110    }
2111}
2112
2113#[stable(feature = "fused", since = "1.26.0")]
2114impl<T: Ord> FusedIterator for Union<'_, T> {}
2115
2116/// A cursor over a `BTreeSet`.
2117///
2118/// A `Cursor` is like an iterator, except that it can freely seek back-and-forth.
2119///
2120/// Cursors always point to a gap between two elements in the set, and can
2121/// operate on the two immediately adjacent elements.
2122///
2123/// A `Cursor` is created with the [`BTreeSet::lower_bound`] and [`BTreeSet::upper_bound`] methods.
2124#[derive(Clone)]
2125#[unstable(feature = "btree_cursors", issue = "107540")]
2126pub struct Cursor<'a, K: 'a> {
2127    inner: super::map::Cursor<'a, K, SetValZST>,
2128}
2129
2130#[unstable(feature = "btree_cursors", issue = "107540")]
2131impl<K: Debug> Debug for Cursor<'_, K> {
2132    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2133        f.write_str("Cursor")
2134    }
2135}
2136
2137/// A cursor over a `BTreeSet` with editing operations.
2138///
2139/// A `Cursor` is like an iterator, except that it can freely seek back-and-forth, and can
2140/// safely mutate the set during iteration. This is because the lifetime of its yielded
2141/// references is tied to its own lifetime, instead of just the underlying map. This means
2142/// cursors cannot yield multiple elements at once.
2143///
2144/// Cursors always point to a gap between two elements in the set, and can
2145/// operate on the two immediately adjacent elements.
2146///
2147/// A `CursorMut` is created with the [`BTreeSet::lower_bound_mut`] and [`BTreeSet::upper_bound_mut`]
2148/// methods.
2149#[unstable(feature = "btree_cursors", issue = "107540")]
2150pub struct CursorMut<
2151    'a,
2152    K: 'a,
2153    #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] A = Global,
2154> {
2155    inner: super::map::CursorMut<'a, K, SetValZST, A>,
2156}
2157
2158#[unstable(feature = "btree_cursors", issue = "107540")]
2159impl<K: Debug, A> Debug for CursorMut<'_, K, A> {
2160    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2161        f.write_str("CursorMut")
2162    }
2163}
2164
2165/// A cursor over a `BTreeSet` with editing operations, and which allows
2166/// mutating elements.
2167///
2168/// A `Cursor` is like an iterator, except that it can freely seek back-and-forth, and can
2169/// safely mutate the set during iteration. This is because the lifetime of its yielded
2170/// references is tied to its own lifetime, instead of just the underlying set. This means
2171/// cursors cannot yield multiple elements at once.
2172///
2173/// Cursors always point to a gap between two elements in the set, and can
2174/// operate on the two immediately adjacent elements.
2175///
2176/// A `CursorMutKey` is created from a [`CursorMut`] with the
2177/// [`CursorMut::with_mutable_key`] method.
2178///
2179/// # Safety
2180///
2181/// Since this cursor allows mutating elements, you must ensure that the
2182/// `BTreeSet` invariants are maintained. Specifically:
2183///
2184/// * The newly inserted element must be unique in the tree.
2185/// * All elements in the tree must remain in sorted order.
2186#[unstable(feature = "btree_cursors", issue = "107540")]
2187pub struct CursorMutKey<
2188    'a,
2189    K: 'a,
2190    #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] A = Global,
2191> {
2192    inner: super::map::CursorMutKey<'a, K, SetValZST, A>,
2193}
2194
2195#[unstable(feature = "btree_cursors", issue = "107540")]
2196impl<K: Debug, A> Debug for CursorMutKey<'_, K, A> {
2197    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2198        f.write_str("CursorMutKey")
2199    }
2200}
2201
2202impl<'a, K> Cursor<'a, K> {
2203    /// Advances the cursor to the next gap, returning the element that it
2204    /// moved over.
2205    ///
2206    /// If the cursor is already at the end of the set then `None` is returned
2207    /// and the cursor is not moved.
2208    #[unstable(feature = "btree_cursors", issue = "107540")]
2209    pub fn next(&mut self) -> Option<&'a K> {
2210        self.inner.next().map(|(k, _)| k)
2211    }
2212
2213    /// Advances the cursor to the previous gap, returning the element that it
2214    /// moved over.
2215    ///
2216    /// If the cursor is already at the start of the set then `None` is returned
2217    /// and the cursor is not moved.
2218    #[unstable(feature = "btree_cursors", issue = "107540")]
2219    pub fn prev(&mut self) -> Option<&'a K> {
2220        self.inner.prev().map(|(k, _)| k)
2221    }
2222
2223    /// Returns a reference to next element without moving the cursor.
2224    ///
2225    /// If the cursor is at the end of the set then `None` is returned
2226    #[unstable(feature = "btree_cursors", issue = "107540")]
2227    pub fn peek_next(&self) -> Option<&'a K> {
2228        self.inner.peek_next().map(|(k, _)| k)
2229    }
2230
2231    /// Returns a reference to the previous element without moving the cursor.
2232    ///
2233    /// If the cursor is at the start of the set then `None` is returned.
2234    #[unstable(feature = "btree_cursors", issue = "107540")]
2235    pub fn peek_prev(&self) -> Option<&'a K> {
2236        self.inner.peek_prev().map(|(k, _)| k)
2237    }
2238}
2239
2240impl<'a, T, A> CursorMut<'a, T, A> {
2241    /// Advances the cursor to the next gap, returning the element that it
2242    /// moved over.
2243    ///
2244    /// If the cursor is already at the end of the set then `None` is returned
2245    /// and the cursor is not moved.
2246    #[unstable(feature = "btree_cursors", issue = "107540")]
2247    pub fn next(&mut self) -> Option<&T> {
2248        self.inner.next().map(|(k, _)| k)
2249    }
2250
2251    /// Advances the cursor to the previous gap, returning the element that it
2252    /// moved over.
2253    ///
2254    /// If the cursor is already at the start of the set then `None` is returned
2255    /// and the cursor is not moved.
2256    #[unstable(feature = "btree_cursors", issue = "107540")]
2257    pub fn prev(&mut self) -> Option<&T> {
2258        self.inner.prev().map(|(k, _)| k)
2259    }
2260
2261    /// Returns a reference to the next element without moving the cursor.
2262    ///
2263    /// If the cursor is at the end of the set then `None` is returned.
2264    #[unstable(feature = "btree_cursors", issue = "107540")]
2265    pub fn peek_next(&mut self) -> Option<&T> {
2266        self.inner.peek_next().map(|(k, _)| k)
2267    }
2268
2269    /// Returns a reference to the previous element without moving the cursor.
2270    ///
2271    /// If the cursor is at the start of the set then `None` is returned.
2272    #[unstable(feature = "btree_cursors", issue = "107540")]
2273    pub fn peek_prev(&mut self) -> Option<&T> {
2274        self.inner.peek_prev().map(|(k, _)| k)
2275    }
2276
2277    /// Returns a read-only cursor pointing to the same location as the
2278    /// `CursorMut`.
2279    ///
2280    /// The lifetime of the returned `Cursor` is bound to that of the
2281    /// `CursorMut`, which means it cannot outlive the `CursorMut` and that the
2282    /// `CursorMut` is frozen for the lifetime of the `Cursor`.
2283    #[unstable(feature = "btree_cursors", issue = "107540")]
2284    pub fn as_cursor(&self) -> Cursor<'_, T> {
2285        Cursor { inner: self.inner.as_cursor() }
2286    }
2287
2288    /// Converts the cursor into a [`CursorMutKey`], which allows mutating
2289    /// elements in the tree.
2290    ///
2291    /// # Safety
2292    ///
2293    /// Since this cursor allows mutating elements, you must ensure that the
2294    /// `BTreeSet` invariants are maintained. Specifically:
2295    ///
2296    /// * The newly inserted element must be unique in the tree.
2297    /// * All elements in the tree must remain in sorted order.
2298    #[unstable(feature = "btree_cursors", issue = "107540")]
2299    pub unsafe fn with_mutable_key(self) -> CursorMutKey<'a, T, A> {
2300        // ignore-tidy-undocumented-unsafe
2301        CursorMutKey { inner: unsafe { self.inner.with_mutable_key() } }
2302    }
2303}
2304
2305impl<'a, T, A> CursorMutKey<'a, T, A> {
2306    /// Advances the cursor to the next gap, returning the  element that it
2307    /// moved over.
2308    ///
2309    /// If the cursor is already at the end of the set then `None` is returned
2310    /// and the cursor is not moved.
2311    #[unstable(feature = "btree_cursors", issue = "107540")]
2312    pub fn next(&mut self) -> Option<&mut T> {
2313        self.inner.next().map(|(k, _)| k)
2314    }
2315
2316    /// Advances the cursor to the previous gap, returning the element that it
2317    /// moved over.
2318    ///
2319    /// If the cursor is already at the start of the set then `None` is returned
2320    /// and the cursor is not moved.
2321    #[unstable(feature = "btree_cursors", issue = "107540")]
2322    pub fn prev(&mut self) -> Option<&mut T> {
2323        self.inner.prev().map(|(k, _)| k)
2324    }
2325
2326    /// Returns a reference to the next element without moving the cursor.
2327    ///
2328    /// If the cursor is at the end of the set then `None` is returned
2329    #[unstable(feature = "btree_cursors", issue = "107540")]
2330    pub fn peek_next(&mut self) -> Option<&mut T> {
2331        self.inner.peek_next().map(|(k, _)| k)
2332    }
2333
2334    /// Returns a reference to the previous element without moving the cursor.
2335    ///
2336    /// If the cursor is at the start of the set then `None` is returned.
2337    #[unstable(feature = "btree_cursors", issue = "107540")]
2338    pub fn peek_prev(&mut self) -> Option<&mut T> {
2339        self.inner.peek_prev().map(|(k, _)| k)
2340    }
2341
2342    /// Returns a read-only cursor pointing to the same location as the
2343    /// `CursorMutKey`.
2344    ///
2345    /// The lifetime of the returned `Cursor` is bound to that of the
2346    /// `CursorMutKey`, which means it cannot outlive the `CursorMutKey` and that the
2347    /// `CursorMutKey` is frozen for the lifetime of the `Cursor`.
2348    #[unstable(feature = "btree_cursors", issue = "107540")]
2349    pub fn as_cursor(&self) -> Cursor<'_, T> {
2350        Cursor { inner: self.inner.as_cursor() }
2351    }
2352}
2353
2354impl<'a, T: Ord, A: AllocatorClone> CursorMut<'a, T, A> {
2355    /// Inserts a new element into the set in the gap that the
2356    /// cursor is currently pointing to.
2357    ///
2358    /// After the insertion the cursor will be pointing at the gap before the
2359    /// newly inserted element.
2360    ///
2361    /// # Safety
2362    ///
2363    /// You must ensure that the `BTreeSet` invariants are maintained.
2364    /// Specifically:
2365    ///
2366    /// * The newly inserted element must be unique in the tree.
2367    /// * All elements in the tree must remain in sorted order.
2368    #[unstable(feature = "btree_cursors", issue = "107540")]
2369    pub unsafe fn insert_after_unchecked(&mut self, value: T) {
2370        // SAFETY: Upheld by caller.
2371        unsafe { self.inner.insert_after_unchecked(value, SetValZST) }
2372    }
2373
2374    /// Inserts a new element into the set in the gap that the
2375    /// cursor is currently pointing to.
2376    ///
2377    /// After the insertion the cursor will be pointing at the gap after the
2378    /// newly inserted element.
2379    ///
2380    /// # Safety
2381    ///
2382    /// You must ensure that the `BTreeSet` invariants are maintained.
2383    /// Specifically:
2384    ///
2385    /// * The newly inserted element must be unique in the tree.
2386    /// * All elements in the tree must remain in sorted order.
2387    #[unstable(feature = "btree_cursors", issue = "107540")]
2388    pub unsafe fn insert_before_unchecked(&mut self, value: T) {
2389        // SAFETY: Upheld by caller.
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: AllocatorClone> 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        // SAFETY: Upheld by caller.
2459        unsafe { self.inner.insert_after_unchecked(value, SetValZST) }
2460    }
2461
2462    /// Inserts a new element into the set in the gap that the
2463    /// cursor is currently pointing to.
2464    ///
2465    /// After the insertion the cursor will be pointing at the gap after the
2466    /// newly inserted element.
2467    ///
2468    /// # Safety
2469    ///
2470    /// You must ensure that the `BTreeSet` invariants are maintained.
2471    /// Specifically:
2472    ///
2473    /// * The newly inserted element must be unique in the tree.
2474    /// * All elements in the tree must remain in sorted order.
2475    #[unstable(feature = "btree_cursors", issue = "107540")]
2476    pub unsafe fn insert_before_unchecked(&mut self, value: T) {
2477        // SAFETY: Upheld by caller.
2478        unsafe { self.inner.insert_before_unchecked(value, SetValZST) }
2479    }
2480
2481    /// Inserts a new element into the set in the gap that the
2482    /// cursor is currently pointing to.
2483    ///
2484    /// After the insertion the cursor will be pointing at the gap before the
2485    /// newly inserted element.
2486    ///
2487    /// If the inserted element is not greater than the element before the
2488    /// cursor (if any), or if it not less than the element after the cursor (if
2489    /// any), then an [`UnorderedKeyError`] is returned since this would
2490    /// invalidate the [`Ord`] invariant between the elements of the set.
2491    #[unstable(feature = "btree_cursors", issue = "107540")]
2492    pub fn insert_after(&mut self, value: T) -> Result<(), UnorderedKeyError> {
2493        self.inner.insert_after(value, SetValZST)
2494    }
2495
2496    /// Inserts a new element into the set in the gap that the
2497    /// cursor is currently pointing to.
2498    ///
2499    /// After the insertion the cursor will be pointing at the gap after the
2500    /// newly inserted element.
2501    ///
2502    /// If the inserted element is not greater than the element before the
2503    /// cursor (if any), or if it not less than the element after the cursor (if
2504    /// any), then an [`UnorderedKeyError`] is returned since this would
2505    /// invalidate the [`Ord`] invariant between the elements of the set.
2506    #[unstable(feature = "btree_cursors", issue = "107540")]
2507    pub fn insert_before(&mut self, value: T) -> Result<(), UnorderedKeyError> {
2508        self.inner.insert_before(value, SetValZST)
2509    }
2510
2511    /// Removes the next element from the `BTreeSet`.
2512    ///
2513    /// The element that was removed is returned. The cursor position is
2514    /// unchanged (before the removed element).
2515    #[unstable(feature = "btree_cursors", issue = "107540")]
2516    pub fn remove_next(&mut self) -> Option<T> {
2517        self.inner.remove_next().map(|(k, _)| k)
2518    }
2519
2520    /// Removes the preceding element from the `BTreeSet`.
2521    ///
2522    /// The element that was removed is returned. The cursor position is
2523    /// unchanged (after the removed element).
2524    #[unstable(feature = "btree_cursors", issue = "107540")]
2525    pub fn remove_prev(&mut self) -> Option<T> {
2526        self.inner.remove_prev().map(|(k, _)| k)
2527    }
2528}
2529
2530#[unstable(feature = "btree_cursors", issue = "107540")]
2531pub use super::map::UnorderedKeyError;
2532
2533#[cfg(test)]
2534mod tests;