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