Skip to main content

alloc/collections/btree/
set.rs

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