Skip to main content

alloc/collections/btree/
set.rs

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