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