Skip to main content

range_set_blaze/
set.rs

1#![allow(unexpected_cfgs)]
2#[cfg(any(
3    test,
4    feature = "test_util",
5    not(feature = "cursor_nightly_experimental")
6))]
7use core::cmp::max;
8use core::mem;
9use core::{
10    cmp::Ordering,
11    fmt,
12    iter::FusedIterator,
13    ops::{BitOr, BitOrAssign, Bound, RangeBounds, RangeInclusive},
14};
15use num_traits::{One, Zero};
16#[cfg(all(not(coverage), feature = "std"))]
17use std::{
18    fs::File,
19    io::{self, BufRead, BufReader},
20    path::Path,
21    str::FromStr,
22};
23
24use crate::alloc::string::ToString;
25use crate::sorted_disjoint::RangeOnce;
26#[cfg(feature = "cursor_nightly_experimental")]
27use alloc::collections::btree_map::CursorMut;
28use alloc::collections::{BTreeMap, btree_map};
29use alloc::string::String;
30#[cfg(any(
31    test,
32    feature = "test_util",
33    not(feature = "cursor_nightly_experimental")
34))]
35use alloc::vec::Vec;
36use gen_ops::gen_ops_ex;
37
38use crate::ranges_iter::RangesIter;
39use crate::unsorted_disjoint::{SortedDisjointWithLenSoFar, UnsortedDisjoint};
40use crate::{Integer, prelude::*};
41use crate::{IntoRangesIter, UnionIter};
42
43// // FUTURE: use fn range to implement one-at-a-time intersection, difference, etc. and then add more inplace ops.
44
45#[cfg(all(not(coverage), feature = "std"))]
46#[allow(dead_code)]
47#[doc(hidden)]
48pub fn demo_read_ranges_from_file<P, T>(path: P) -> io::Result<RangeSetBlaze<T>>
49where
50    P: AsRef<Path>,
51    T: FromStr + Integer,
52{
53    let lines = BufReader::new(File::open(&path)?).lines();
54
55    let mut set = RangeSetBlaze::new();
56    for line in lines {
57        let line = line?;
58        let mut split = line.split('\t');
59        let start = split
60            .next()
61            .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "Missing start of range"))?
62            .parse::<T>()
63            .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "Invalid start of range"))?;
64        let end = split
65            .next()
66            .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "Missing end of range"))?
67            .parse::<T>()
68            .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "Invalid end of range"))?;
69        set.ranges_insert(start..=end);
70    }
71
72    Ok(set)
73}
74
75/// A set of integers stored as sorted & disjoint ranges.
76///
77/// Internally, it stores the ranges in a cache-efficient [`BTreeMap`].
78///
79/// For a side-by-side introduction to range lookups and gap filling, see the
80/// [Ranges and gaps guide][crate::gaps].
81///
82/// # Table of Contents
83/// * [`RangeSetBlaze` Constructors](#rangesetblaze-constructors)
84///    * [Performance](#constructor-performance)
85///    * [Examples](struct.RangeSetBlaze.html#constructor-examples)
86/// * [`RangeSetBlaze` Set Operations](#rangesetblaze-set-operations)
87///    * [Performance](struct.RangeSetBlaze.html#set-operation-performance)
88///    * [Examples](struct.RangeSetBlaze.html#set-operation-examples)
89///  * [`RangeSetBlaze` Comparisons](#rangesetblaze-comparisons)
90///  * [Additional Examples](#additional-examples)
91///
92/// # `RangeSetBlaze` Constructors
93///
94/// You can create `RangeSetBlaze`'s from unsorted and overlapping integers (or ranges).
95/// However, if you know that your input is sorted and disjoint, you can speed up construction.
96///
97/// Here are the constructors, followed by a
98/// description of the performance, and then some examples.
99///
100/// | Methods                                     | Input                        | Notes                    |
101/// |---------------------------------------------|------------------------------|--------------------------|
102/// | [`new`]/[`default`]                         |                              |                          |
103/// | [`from_iter`][1]/[`collect`][1]             | integer iterator             |                          |
104/// | [`from_iter`][2]/[`collect`][2]             | ranges iterator              |                          |
105/// | [`from_slice`][5]                           | slice of integers            | Fast, but nightly-only  |
106/// | [`from_sorted_disjoint`][3]/[`into_range_set_blaze`][3] | [`SortedDisjoint`] iterator |               |
107/// | [`from`][5] /[`into`][5]                    | array of integers            |                          |
108/// | [`from`][7]                                 | `RangeInclusive<T>`          |                          |
109///
110///
111/// [`BTreeMap`]: alloc::collections::BTreeMap
112/// [`new`]: RangeSetBlaze::new
113/// [`default`]: RangeSetBlaze::default
114/// [1]: struct.RangeSetBlaze.html#impl-FromIterator<T>-for-RangeSetBlaze<T>
115/// [2]: struct.RangeSetBlaze.html#impl-FromIterator<RangeInclusive<T>>-for-RangeSetBlaze<T>
116/// [3]: RangeSetBlaze::from_sorted_disjoint
117/// [SortedDisjoint]: crate::SortedDisjoint.html#table-of-contents
118/// [5]: RangeSetBlaze::from
119/// [6]: RangeSetBlaze::from_slice()
120/// [7]: #method.from-1
121///
122/// # Constructor Performance
123///
124/// The [`from_iter`][1]/[`collect`][1] constructors are designed to work fast on 'clumpy' data.
125/// By 'clumpy', we mean that the number of ranges needed to represent the data is
126/// small compared to the number of input integers. To understand this, consider the internals
127/// of the constructors:
128///
129///  Internally, the `from_iter`/`collect` constructors take these steps:
130/// * collect adjacent integers/ranges into disjoint ranges, O(*n₁*)
131/// * sort the disjoint ranges by their `start`, O(*n₂* ln *n₂*)
132/// * merge adjacent ranges, O(*n₂*)
133/// * create a `BTreeMap` from the now sorted & disjoint ranges, O(*n₃* ln *n₃*)
134///
135/// where *n₁* is the number of input integers/ranges, *n₂* is the number of disjoint & unsorted ranges,
136/// and *n₃* is the final number of sorted & disjoint ranges.
137///
138/// For example, an input of
139///  *  `3, 2, 1, 4, 5, 6, 7, 0, 8, 8, 8, 100, 1`, becomes
140///  * `0..=8, 100..=100, 1..=1`, and then
141///  * `0..=8, 1..=1, 100..=100`, and finally
142///  * `0..=8, 100..=100`.
143///
144/// What is the effect of clumpy data?
145/// Notice that if *n₂* ≈ sqrt(*n₁*), then construction is O(*n₁*).
146/// Indeed, as long as *n₂* ≤ *n₁*/ln(*n₁*), then construction is O(*n₁*).
147/// Moreover, we'll see that set operations are O(*n₃*). Thus, if *n₃* ≈ sqrt(*n₁*) then set operations are O(sqrt(*n₁*)),
148/// a quadratic improvement an O(*n₁*) implementation that ignores the clumps.
149///
150/// The [`from_slice`][5] constructor typically provides a constant-time speed up for array-like collections of clumpy integers.
151/// On a representative benchmark, the speed up was 7×.
152/// The method works by scanning the input for blocks of consecutive integers, and then using `from_iter` on the results.
153/// Where available, it uses SIMD instructions. It is nightly only and enabled by the `from_slice` feature.
154///
155/// ## Constructor Examples
156///
157/// ```
158/// use range_set_blaze::prelude::*;
159///
160/// // Create an empty set with 'new' or 'default'.
161/// let a0 = RangeSetBlaze::<i32>::new();
162/// let a1 = RangeSetBlaze::<i32>::default();
163/// assert!(a0 == a1 && a0.is_empty());
164///
165/// // 'from_iter'/'collect': From an iterator of integers.
166/// // Duplicates and out-of-order elements are fine.
167/// let a0 = RangeSetBlaze::from_iter([3, 2, 1, 100, 1]);
168/// let a1: RangeSetBlaze<i32> = [3, 2, 1, 100, 1].into_iter().collect();
169/// assert!(a0 == a1 && a0.to_string() == "1..=3, 100..=100");
170///
171/// // 'from_iter'/'collect': From an iterator of inclusive ranges, start..=end.
172/// // Overlapping, out-of-order, and empty ranges are fine.
173/// #[allow(clippy::reversed_empty_ranges)]
174/// let a0 = RangeSetBlaze::from_iter([1..=2, 2..=2, -10..=-5, 1..=0]);
175/// #[allow(clippy::reversed_empty_ranges)]
176/// let a1: RangeSetBlaze<i32> = [1..=2, 2..=2, -10..=-5, 1..=0].into_iter().collect();
177/// assert!(a0 == a1 && a0.to_string() == "-10..=-5, 1..=2");
178///
179/// // 'from_slice': From any array-like collection of integers.
180/// // Nightly-only, but faster than 'from_iter'/'collect' on integers.
181/// #[cfg(feature = "from_slice")]
182/// let a0 = RangeSetBlaze::from_slice(vec![3, 2, 1, 100, 1]);
183/// #[cfg(feature = "from_slice")]
184/// assert!(a0.to_string() == "1..=3, 100..=100");
185///
186/// // If we know the ranges are already sorted and disjoint,
187/// // we can avoid work and use 'from_sorted_disjoint'/'into_range_set_blaze'.
188/// let a0 = RangeSetBlaze::from_sorted_disjoint(CheckSortedDisjoint::new([-10..=-5, 1..=2]));
189/// let a1: RangeSetBlaze<i32> = CheckSortedDisjoint::new([-10..=-5, 1..=2]).into_range_set_blaze();
190/// assert!(a0 == a1 && a0.to_string() == "-10..=-5, 1..=2");
191///
192/// // For compatibility with `BTreeSet`, we also support
193/// // 'from'/'into' from arrays of integers.
194/// let a0 = RangeSetBlaze::from([3, 2, 1, 100, 1]);
195/// let a1: RangeSetBlaze<i32> = [3, 2, 1, 100, 1].into();
196/// assert!(a0 == a1 && a0.to_string() == "1..=3, 100..=100");
197/// ```
198///
199/// # `RangeSetBlaze` Set Operations
200///
201/// You can perform set operations on `RangeSetBlaze`s using operators.
202///
203/// | Set Operation           | Operator          |  Multiway Method |
204/// |-------------------|-------------------------|-------------------------|
205/// | union             |  [`a` &#124; `b`]       | <code>[a, b, c].[union]()</code>`()` |
206/// | intersection      |  [`a & b`]              | <code>[a, b, c].[intersection]()</code>`()` |
207/// | difference        |  [`a - b`]              | *n/a* |
208/// | symmetric difference|  [`a ^ b`]            | <code>[a, b, c].[symmetric_difference]()</code>`()` |
209/// | complement        |  [`!a`]                 | *n/a* |
210///
211/// `RangeSetBlaze` also implements many other methods, such as [`insert`], [`pop_first`] and [`split_off`]. Many of
212/// these methods match those of `BTreeSet`.
213///
214/// [`a` &#124; `b`]: struct.RangeSetBlaze.html#impl-BitOr-for-RangeSetBlaze<T>
215/// [`a & b`]: struct.RangeSetBlaze.html#impl-BitAnd-for-RangeSetBlaze<T>
216/// [`a - b`]: struct.RangeSetBlaze.html#impl-Sub-for-RangeSetBlaze<T>
217/// [`a ^ b`]: struct.RangeSetBlaze.html#impl-BitXor-for-RangeSetBlaze<T>
218/// [`!a`]: struct.RangeSetBlaze.html#method.not
219/// [`union`]: trait.MultiwayRangeSetBlazeRef.html#method.union
220/// [`intersection`]: trait.MultiwayRangeSetBlazeRef.html#method.intersection
221/// [`symmetric_difference`]: trait.MultiwayRangeSetBlazeRef.html#method.symmetric_difference
222/// [`insert`]: RangeSetBlaze::insert
223/// [`pop_first`]: RangeSetBlaze::pop_first
224/// [`split_off`]: RangeSetBlaze::split_off
225/// [SortedDisjoint]: crate::SortedDisjoint.html#table-of-contents
226///
227///
228/// ## Set Operation Performance
229///
230/// Every operation is implemented as
231/// 1. a single pass over the sorted & disjoint ranges
232/// 2. the construction of a new `RangeSetBlaze`
233///
234/// Thus, applying multiple operators creates intermediate
235/// `RangeSetBlaze`'s. If you wish, you can avoid these intermediate
236/// `RangeSetBlaze`'s by switching to the [`SortedDisjoint`] API. The last example below
237/// demonstrates this.
238///
239/// ## Set Operation Examples
240///
241/// ```
242/// use range_set_blaze::prelude::*;
243///
244/// let a = RangeSetBlaze::from_iter([1..=2, 5..=100]);
245/// let b = RangeSetBlaze::from_iter([2..=6]);
246///
247/// // Union of two 'RangeSetBlaze's.
248/// let result = &a | &b;
249/// // Alternatively, we can take ownership via 'a | b'.
250/// assert_eq!(result.to_string(), "1..=100");
251///
252/// // Intersection of two 'RangeSetBlaze's.
253/// let result = &a & &b; // Alternatively, 'a & b'.
254/// assert_eq!(result.to_string(), "2..=2, 5..=6");
255///
256/// // Set difference of two 'RangeSetBlaze's.
257/// let result = &a - &b; // Alternatively, 'a - b'.
258/// assert_eq!(result.to_string(), "1..=1, 7..=100");
259///
260/// // Symmetric difference of two 'RangeSetBlaze's.
261/// let result = &a ^ &b; // Alternatively, 'a ^ b'.
262/// assert_eq!(result.to_string(), "1..=1, 3..=4, 7..=100");
263///
264/// // complement of a 'RangeSetBlaze'.
265/// let result = !&a; // Alternatively, '!a'.
266/// assert_eq!(
267///     result.to_string(),
268///     "-2147483648..=0, 3..=4, 101..=2147483647"
269/// );
270///
271/// // Multiway union of 'RangeSetBlaze's.
272/// let c = RangeSetBlaze::from_iter([2..=2, 6..=200]);
273/// let result = [&a, &b, &c].union();
274/// assert_eq!(result.to_string(), "1..=200");
275///
276/// // Multiway intersection of 'RangeSetBlaze's.
277/// let result = [&a, &b, &c].intersection();
278/// assert_eq!(result.to_string(), "2..=2, 6..=6");
279///
280/// // Applying multiple operators
281/// let result0 = &a - (&b | &c); // Creates an intermediate 'RangeSetBlaze'.
282/// // Alternatively, we can use the 'SortedDisjoint' API and avoid the intermediate 'RangeSetBlaze'.
283/// let result1 = RangeSetBlaze::from_sorted_disjoint(a.ranges() - (b.ranges() | c.ranges()));
284/// assert!(result0 == result1 && result0.to_string() == "1..=1");
285/// ```
286/// # `RangeSetBlaze` Comparisons
287///
288/// We can compare `RangeSetBlaze`s using the following operators:
289/// `<`, `<=`, `>`, `>=`.  Following the convention of `BTreeSet`,
290/// these comparisons are lexicographic. See [`cmp`] for more examples.
291///
292/// Use the [`is_subset`] and [`is_superset`] methods to check if one `RangeSetBlaze` is a subset
293/// or superset of another.
294///
295/// Use `==`, `!=` to check if two `RangeSetBlaze`s are equal or not.
296///
297/// [`BTreeSet`]: alloc::collections::BTreeSet
298/// [`is_subset`]: RangeSetBlaze::is_subset
299/// [`is_superset`]: RangeSetBlaze::is_superset
300/// [`cmp`]: RangeSetBlaze::cmp
301///
302/// # Additional Examples
303///
304/// See the [module-level documentation] for additional examples.
305///
306/// [module-level documentation]: index.html
307#[derive(Clone, Hash, PartialEq)]
308pub struct RangeSetBlaze<T: Integer> {
309    len: <T as Integer>::SafeLen,
310    pub(crate) btree_map: BTreeMap<T, T>,
311}
312
313// impl default
314impl<T: Integer> Default for RangeSetBlaze<T> {
315    /// Creates an empty `RangeSetBlaze`.
316    ///
317    /// # Examples
318    ///
319    /// ```
320    /// use range_set_blaze::RangeSetBlaze;
321    ///
322    /// let set: RangeSetBlaze<i32> = RangeSetBlaze::default();
323    /// assert!(set.is_empty());
324    /// ```
325    fn default() -> Self {
326        Self {
327            len: <T as Integer>::SafeLen::zero(),
328            btree_map: BTreeMap::new(),
329        }
330    }
331}
332
333// FUTURE: Make all RangeSetBlaze iterators DoubleEndedIterator and ExactSizeIterator.
334impl<T: Integer> fmt::Debug for RangeSetBlaze<T> {
335    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
336        write!(f, "{}", self.ranges().into_string())
337    }
338}
339
340impl<T: Integer> fmt::Display for RangeSetBlaze<T> {
341    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
342        write!(f, "{}", self.ranges().into_string())
343    }
344}
345
346impl<T: Integer> RangeSetBlaze<T> {
347    /// Gets an iterator that visits the integer elements in the [`RangeSetBlaze`] in
348    /// ascending and/or descending order. Double-ended.
349    ///
350    /// Also see the [`RangeSetBlaze::ranges`] method.
351    ///
352    /// # Examples
353    ///
354    /// ```
355    /// use range_set_blaze::RangeSetBlaze;
356    ///
357    /// let set = RangeSetBlaze::from_iter([1..=3]);
358    /// let mut set_iter = set.iter();
359    /// assert_eq!(set_iter.next(), Some(1));
360    /// assert_eq!(set_iter.next(), Some(2));
361    /// assert_eq!(set_iter.next(), Some(3));
362    /// assert_eq!(set_iter.next(), None);
363    /// ```
364    ///
365    /// Values returned by `.next()` are in ascending order.
366    /// Values returned by `.next_back()` are in descending order.
367    ///
368    /// ```
369    /// use range_set_blaze::RangeSetBlaze;
370    ///
371    /// let set = RangeSetBlaze::from_iter([3, 1, 2]);
372    /// let mut set_iter = set.iter();
373    /// assert_eq!(set_iter.next(), Some(1));
374    /// assert_eq!(set_iter.next_back(), Some(3));
375    /// assert_eq!(set_iter.next(), Some(2));
376    /// assert_eq!(set_iter.next_back(), None);
377    /// ```
378    #[allow(clippy::iter_without_into_iter)]
379    pub fn iter(&self) -> Iter<T, RangesIter<'_, T>> {
380        // If the user asks for an iter, we give them a RangesIter iterator
381        // and we iterate that one integer at a time.
382        Iter {
383            range_front: T::exhausted_range(),
384            range_back: T::exhausted_range(),
385            btree_set_iter: self.ranges(),
386        }
387    }
388
389    /// Returns the first element in the set, if any.
390    /// This element is always the minimum of all integer elements in the set.
391    ///
392    /// # Examples
393    ///
394    /// Basic usage:
395    ///
396    /// ```
397    /// use range_set_blaze::RangeSetBlaze;
398    ///
399    /// let mut set = RangeSetBlaze::new();
400    /// assert_eq!(set.first(), None);
401    /// set.insert(1);
402    /// assert_eq!(set.first(), Some(1));
403    /// set.insert(2);
404    /// assert_eq!(set.first(), Some(1));
405    /// ```
406    #[must_use]
407    pub fn first(&self) -> Option<T> {
408        self.btree_map.iter().next().map(|(x, _)| *x)
409    }
410
411    /// Returns the element in the set, if any, that is equal to
412    /// the value.
413    ///
414    /// # Examples
415    ///
416    /// ```
417    /// use range_set_blaze::RangeSetBlaze;
418    ///
419    /// let set = RangeSetBlaze::from_iter([1, 2, 3]);
420    /// assert_eq!(set.get(2), Some(2));
421    /// assert_eq!(set.get(4), None);
422    /// ```
423    pub fn get(&self, value: T) -> Option<T> {
424        if self.contains(value) {
425            Some(value)
426        } else {
427            None
428        }
429    }
430
431    /// Returns the stored range containing `value`, if any.
432    ///
433    /// See the [Ranges and gaps guide][crate::gaps] for the corresponding map
434    /// APIs and for the difference between `range_at` and `range_or_gap_at`.
435    ///
436    /// # Examples
437    ///
438    /// ```
439    /// use range_set_blaze::RangeSetBlaze;
440    ///
441    /// let set = RangeSetBlaze::from_iter([1..=3, 7..=10]);
442    /// assert_eq!(set.range_at(2), Some(1..=3));
443    /// assert_eq!(set.range_at(5), None);
444    /// ```
445    #[must_use]
446    pub fn range_at(&self, value: T) -> Option<RangeInclusive<T>> {
447        self.containing_range(value)
448            .map(|(start, end)| *start..=*end)
449    }
450
451    /// Returns the maximal contiguous present range or gap containing `value`.
452    ///
453    /// The Boolean is `true` when the returned range is present and `false`
454    /// when it is a gap.
455    ///
456    /// See the [Ranges and gaps guide][crate::gaps] for the corresponding map
457    /// API and for examples of querying both kinds of container.
458    ///
459    /// # Performance
460    ///
461    /// Performs one tree lookup for a present value and two tree lookups for a
462    /// gap, taking `O(log r)` time, where `r` is the number of stored ranges.
463    ///
464    /// # Examples
465    ///
466    /// ```
467    /// # use range_set_blaze::RangeSetBlaze;
468    /// let set = RangeSetBlaze::from_iter([1..=3, 7..=10]);
469    /// assert_eq!(set.range_or_gap_at(2), (1..=3, true));
470    /// assert_eq!(set.range_or_gap_at(5), (4..=6, false));
471    /// assert_eq!(set.range_or_gap_at(8), (7..=10, true));
472    /// ```
473    #[must_use]
474    #[inline]
475    pub fn range_or_gap_at(&self, value: T) -> (RangeInclusive<T>, bool) {
476        #[cfg(feature = "cursor_nightly_experimental")]
477        return self.range_or_gap_at_cursor(value);
478
479        #[cfg(not(feature = "cursor_nightly_experimental"))]
480        self.range_or_gap_at_baseline(value)
481    }
482
483    #[cfg(any(test, not(feature = "cursor_nightly_experimental")))]
484    #[inline]
485    pub(crate) fn range_or_gap_at_baseline(&self, value: T) -> (RangeInclusive<T>, bool) {
486        if let Some((start_before, end_before)) = self.predecessor_range(value) {
487            if value <= *end_before {
488                return (*start_before..=*end_before, true);
489            }
490            if let Some((start_next, _)) = self.btree_map.range(value..).next() {
491                return (end_before.add_one()..=start_next.sub_one(), false);
492            }
493            return (end_before.add_one()..=T::max_value(), false);
494        }
495
496        if let Some((start_next, _)) = self.btree_map.range(value..).next() {
497            return (T::min_value()..=start_next.sub_one(), false);
498        }
499        (T::min_value()..=T::max_value(), false)
500    }
501
502    #[cfg(feature = "cursor_nightly_experimental")]
503    #[inline]
504    pub(crate) fn range_or_gap_at_cursor(&self, value: T) -> (RangeInclusive<T>, bool) {
505        // A single position exposes both ranges adjacent to `value`; unlike the baseline,
506        // a gap does not require a second logarithmic search for its right boundary.
507        let cursor = self.btree_map.lower_bound(Bound::Included(&value));
508
509        if let Some((start_before, end_before)) = cursor.peek_prev() {
510            if value <= *end_before {
511                return (*start_before..=*end_before, true);
512            }
513            if let Some((start_next, end_next)) = cursor.peek_next() {
514                if value == *start_next {
515                    return (*start_next..=*end_next, true);
516                }
517                return (end_before.add_one()..=start_next.sub_one(), false);
518            }
519            return (end_before.add_one()..=T::max_value(), false);
520        }
521
522        if let Some((start_next, end_next)) = cursor.peek_next() {
523            if value == *start_next {
524                return (*start_next..=*end_next, true);
525            }
526            return (T::min_value()..=start_next.sub_one(), false);
527        }
528        (T::min_value()..=T::max_value(), false)
529    }
530
531    /// Returns the last element in the set, if any.
532    /// This element is always the maximum of all elements in the set.
533    ///
534    /// # Examples
535    ///
536    /// Basic usage:
537    ///
538    /// ```
539    /// use range_set_blaze::RangeSetBlaze;
540    ///
541    /// let mut set = RangeSetBlaze::new();
542    /// assert_eq!(set.last(), None);
543    /// set.insert(1);
544    /// assert_eq!(set.last(), Some(1));
545    /// set.insert(2);
546    /// assert_eq!(set.last(), Some(2));
547    /// ```
548    #[must_use]
549    pub fn last(&self) -> Option<T> {
550        self.btree_map.iter().next_back().map(|(_, x)| *x)
551    }
552
553    /// Create a [`RangeSetBlaze`] from a [`SortedDisjoint`] iterator.
554    ///
555    /// *For more about constructors and performance, see [`RangeSetBlaze` Constructors](struct.RangeSetBlaze.html#rangesetblaze-constructors).*
556    ///
557    /// # Examples
558    ///
559    /// ```
560    /// use range_set_blaze::prelude::*;
561    ///
562    /// let a0 = RangeSetBlaze::from_sorted_disjoint(CheckSortedDisjoint::new([-10..=-5, 1..=2]));
563    /// let a1: RangeSetBlaze<i32> = CheckSortedDisjoint::new([-10..=-5, 1..=2]).into_range_set_blaze();
564    /// assert!(a0 == a1 && a0.to_string() == "-10..=-5, 1..=2");
565    /// ```
566    pub fn from_sorted_disjoint<I>(iter: I) -> Self
567    where
568        I: SortedDisjoint<T>,
569    {
570        let mut iter_with_len = SortedDisjointWithLenSoFar::new(iter);
571        let btree_map = (&mut iter_with_len).collect();
572        Self {
573            btree_map,
574            len: iter_with_len.len_so_far(),
575        }
576    }
577
578    /// Creates a [`RangeSetBlaze`] from a collection of integers. It is typically many
579    /// times faster than [`from_iter`][1]/[`collect`][1].
580    /// On a representative benchmark, the speed up was 7×.
581    ///
582    /// **Warning: Requires the nightly compiler. Also, you must enable the `from_slice`
583    /// feature in your `Cargo.toml`. For example, with the command:**
584    /// ```bash
585    ///  cargo add range-set-blaze --features "from_slice"
586    /// ```
587    /// The function accepts any type that can be referenced as a slice of integers,
588    /// including slices, arrays, and vectors. Duplicates and out-of-order elements are fine.
589    ///
590    /// Where available, this function leverages SIMD (Single Instruction, Multiple Data) instructions
591    /// for performance optimization. To enable SIMD optimizations, compile with the Rust compiler
592    /// (rustc) flag `-C target-cpu=native`. This instructs rustc to use the native instruction set
593    /// of the CPU on the machine compiling the code, potentially enabling more SIMD optimizations.
594    ///
595    /// **Caution**: Compiling with `-C target-cpu=native` optimizes the binary for your current CPU architecture,
596    /// which may lead to compatibility issues on other machines with different architectures.
597    /// This is particularly important for distributing the binary or running it in varied environments.
598    ///
599    /// *For more about constructors and performance, see [`RangeSetBlaze` Constructors](struct.RangeSetBlaze.html#rangesetblaze-constructors).*
600    ///
601    /// # Examples
602    ///
603    /// ```
604    /// use range_set_blaze::RangeSetBlaze;
605    ///
606    /// let a0 = RangeSetBlaze::from_slice(&[3, 2, 1, 100, 1]); // reference to a slice
607    /// let a1 = RangeSetBlaze::from_slice([3, 2, 1, 100, 1]);   // array
608    /// let a2 = RangeSetBlaze::from_slice(vec![3, 2, 1, 100, 1]); // vector
609    /// assert!(a0 == a1 && a1 == a2 && a0.to_string() == "1..=3, 100..=100");
610    /// ```
611    /// [1]: struct.RangeSetBlaze.html#impl-FromIterator<T>-for-RangeSetBlaze<T>
612    #[cfg(feature = "from_slice")]
613    #[inline]
614    pub fn from_slice(slice: impl AsRef<[T]>) -> Self {
615        T::from_slice(slice)
616    }
617
618    #[allow(dead_code)]
619    #[must_use]
620    pub(crate) fn len_slow(&self) -> <T as Integer>::SafeLen {
621        Self::btree_map_len(&self.btree_map)
622    }
623
624    /// Moves all elements from `other` into `self`, leaving `other` empty.
625    ///
626    /// # Performance
627    /// It adds the integers in `other` to `self` in O(n log m) time, where n is the number of ranges in `other`
628    /// and m is the number of ranges in `self`.
629    /// When n is large, consider using `|` which is O(n+m) time.
630    ///
631    /// # Examples
632    ///
633    /// ```
634    /// use range_set_blaze::RangeSetBlaze;
635    ///
636    /// let mut a = RangeSetBlaze::from_iter([1..=3]);
637    /// let mut b = RangeSetBlaze::from_iter([3..=5]);
638    ///
639    /// a.append(&mut b);
640    ///
641    /// assert_eq!(a.len(), 5u64);
642    /// assert_eq!(b.len(), 0u64);
643    ///
644    /// assert!(a.contains(1));
645    /// assert!(a.contains(2));
646    /// assert!(a.contains(3));
647    /// assert!(a.contains(4));
648    /// assert!(a.contains(5));
649    ///
650    /// ```
651    pub fn append(&mut self, other: &mut Self) {
652        for range in other.ranges() {
653            self.internal_add(range);
654        }
655        other.clear();
656    }
657
658    /// Clears the set, removing all integer elements.
659    ///
660    /// # Examples
661    ///
662    /// ```
663    /// use range_set_blaze::RangeSetBlaze;
664    ///
665    /// let mut v = RangeSetBlaze::new();
666    /// v.insert(1);
667    /// v.clear();
668    /// assert!(v.is_empty());
669    /// ```
670    pub fn clear(&mut self) {
671        self.btree_map.clear();
672        self.len = <T as Integer>::SafeLen::zero();
673    }
674
675    /// Returns `true` if the set contains no elements.
676    ///
677    /// # Examples
678    ///
679    /// ```
680    /// use range_set_blaze::RangeSetBlaze;
681    ///
682    /// let mut v = RangeSetBlaze::new();
683    /// assert!(v.is_empty());
684    /// v.insert(1);
685    /// assert!(!v.is_empty());
686    /// ```
687    #[must_use]
688    #[inline]
689    pub fn is_empty(&self) -> bool {
690        self.ranges_len() == 0
691    }
692
693    /// Returns `true` if the set contains all possible integers.
694    ///
695    /// For type `T`, this means covering the full domain from `T::min_value()` to `T::max_value()`.
696    /// Complexity: O(1).
697    ///
698    /// # Examples
699    ///
700    /// ```
701    /// use range_set_blaze::RangeSetBlaze;
702    ///
703    /// let mut v = RangeSetBlaze::<u8>::new();
704    /// assert!(!v.is_universal());
705    ///
706    /// let universal = !RangeSetBlaze::<u8>::new();
707    /// assert!(universal.is_universal());
708    /// ```
709    #[must_use]
710    #[inline]
711    pub fn is_universal(&self) -> bool {
712        self.ranges().is_universal()
713    }
714
715    /// Returns `true` if the set is a subset of another,
716    /// i.e., `other` contains at least all the elements in `self`.
717    ///
718    /// # Examples
719    ///
720    /// ```
721    /// use range_set_blaze::RangeSetBlaze;
722    ///
723    /// let sup = RangeSetBlaze::from_iter([1..=3]);
724    /// let mut set = RangeSetBlaze::new();
725    ///
726    /// assert_eq!(set.is_subset(&sup), true);
727    /// set.insert(2);
728    /// assert_eq!(set.is_subset(&sup), true);
729    /// set.insert(4);
730    /// assert_eq!(set.is_subset(&sup), false);
731    /// ```
732    #[must_use]
733    #[inline]
734    pub fn is_subset(&self, other: &Self) -> bool {
735        // Add a fast path
736        if self.len() > other.len() {
737            return false;
738        }
739        self.ranges().is_subset(other.ranges())
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 range_set_blaze::RangeSetBlaze;
749    ///
750    /// let sub = RangeSetBlaze::from_iter([1, 2]);
751    /// let mut set = RangeSetBlaze::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    pub fn is_superset(&self, other: &Self) -> bool {
764        other.is_subset(self)
765    }
766
767    /// Returns `true` if the set contains an element equal to the value.
768    ///
769    /// # Examples
770    ///
771    /// ```
772    /// use range_set_blaze::RangeSetBlaze;
773    ///
774    /// let set = RangeSetBlaze::from_iter([1, 2, 3]);
775    /// assert_eq!(set.contains(1), true);
776    /// assert_eq!(set.contains(4), false);
777    /// ```
778    pub fn contains(&self, value: T) -> bool {
779        self.containing_range(value).is_some()
780    }
781
782    fn predecessor_range(&self, value: T) -> Option<(&T, &T)> {
783        self.btree_map.range(..=value).next_back()
784    }
785
786    fn containing_range(&self, value: T) -> Option<(&T, &T)> {
787        self.predecessor_range(value)
788            .and_then(|(start, end)| (value <= *end).then_some((start, end)))
789    }
790
791    /// Returns `true` if `self` has no elements in common with `other`.
792    /// This is equivalent to checking for an empty intersection.
793    ///
794    /// # Examples
795    ///
796    /// ```
797    /// use range_set_blaze::RangeSetBlaze;
798    ///
799    /// let a = RangeSetBlaze::from_iter([1..=3]);
800    /// let mut b = RangeSetBlaze::new();
801    ///
802    /// assert_eq!(a.is_disjoint(&b), true);
803    /// b.insert(4);
804    /// assert_eq!(a.is_disjoint(&b), true);
805    /// b.insert(1);
806    /// assert_eq!(a.is_disjoint(&b), false);
807    /// ```
808    #[must_use]
809    #[inline]
810    pub fn is_disjoint(&self, other: &Self) -> bool {
811        self.ranges().is_disjoint(other.ranges())
812    }
813
814    #[cfg(any(
815        test,
816        feature = "test_util",
817        not(feature = "cursor_nightly_experimental")
818    ))]
819    fn delete_extra(&mut self, internal_range: &RangeInclusive<T>) {
820        let (start, end) = internal_range.clone().into_inner();
821        let mut after = self.btree_map.range_mut(start..);
822        let (start_after, end_after) = after
823            .next()
824            .expect("Real assert: there will always be a next");
825        debug_assert!(start == *start_after && end == *end_after);
826
827        let mut end_new = end;
828        let delete_list = after
829            .map_while(|(start_delete, end_delete)| {
830                // must check this in two parts to avoid overflow
831                if *start_delete <= end || *start_delete <= end.add_one() {
832                    end_new = max(end_new, *end_delete);
833                    self.len -= T::safe_len(&(*start_delete..=*end_delete));
834                    Some(*start_delete)
835                } else {
836                    None
837                }
838            })
839            .collect::<Vec<_>>();
840        if end_new > end {
841            self.len += T::safe_len(&(end..=end_new.sub_one()));
842            *end_after = end_new;
843        }
844        for start in delete_list {
845            self.btree_map.remove(&start);
846        }
847    }
848
849    /// Adds a value to the set.
850    ///
851    /// Returns whether the value was newly inserted. That is:
852    ///
853    /// - If the set did not previously contain an equal value, `true` is
854    ///   returned.
855    /// - If the set already contained an equal value, `false` is returned, and
856    ///   the entry is not updated.
857    ///
858    /// # Performance
859    /// Inserting n items will take in O(n log m) time, where n is the number of inserted items and m is the number of ranges in `self`.
860    /// When n is large, consider using `|` which is O(n+m) time.
861    /// The nightly-only `cursor_nightly_experimental` feature speeds up this method by roughly 2x; see the
862    /// [Cargo Features section of the README](crate#cargo-features).
863    ///
864    /// # Examples
865    ///
866    /// ```
867    /// use range_set_blaze::RangeSetBlaze;
868    ///
869    /// let mut set = RangeSetBlaze::new();
870    ///
871    /// assert_eq!(set.insert(2), true);
872    /// assert_eq!(set.insert(2), false);
873    /// assert_eq!(set.len(), 1u64);
874    /// ```
875    pub fn insert(&mut self, value: T) -> bool {
876        let len_before = self.len;
877        self.internal_add(value..=value);
878        self.len != len_before
879    }
880
881    /// Constructs an iterator over a sub-range of elements in the set.
882    ///
883    /// Not to be confused with [`RangeSetBlaze::ranges`], which returns an iterator over the ranges in the set.
884    ///
885    /// The simplest way is to use the range syntax `min..max`, thus `range(min..max)` will
886    /// yield elements from min (inclusive) to max (exclusive).
887    /// The range may also be entered as `(Bound<T>, Bound<T>)`, so for example
888    /// `range((Excluded(4), Included(10)))` will yield a left-exclusive, right-inclusive
889    /// range from 4 to 10.
890    ///
891    /// # Panics
892    ///
893    /// Panics if range `start > end`.
894    /// Panics if range `start == end` and both bounds are `Excluded`.
895    ///
896    /// # Performance
897    ///
898    /// Although this could be written to run in time O(ln(n)) in the number of ranges, it is currently O(n) in the number of ranges.
899    ///
900    /// # Examples
901    ///
902    /// ```
903    /// use range_set_blaze::RangeSetBlaze;
904    /// use core::ops::Bound::Included;
905    ///
906    /// let mut set = RangeSetBlaze::new();
907    /// set.insert(3);
908    /// set.insert(5);
909    /// set.insert(8);
910    /// for elem in set.range((Included(4), Included(8))) {
911    ///     println!("{elem}");
912    /// }
913    /// assert_eq!(Some(5), set.range(4..).next());
914    /// ```
915    pub fn range<R>(&self, range: R) -> IntoIter<T>
916    where
917        R: RangeBounds<T>,
918    {
919        let (start, end) = extract_range(range);
920        assert!(
921            start <= end,
922            "start (inclusive) must be less than or equal to end (inclusive)"
923        );
924
925        let bounds = CheckSortedDisjoint::new([start..=end]);
926        Self::from_sorted_disjoint(self.ranges() & bounds).into_iter()
927    }
928
929    /// Adds a range to the set.
930    ///
931    /// Returns whether any values where newly inserted. That is:
932    ///
933    /// - If the set did not previously contain some value in the range, `true` is
934    ///   returned.
935    /// - If the set already contained every value in the range, `false` is returned, and
936    ///   the entry is not updated.
937    ///
938    /// # Performance
939    /// Inserting n items will take in O(n log m) time, where n is the number of inserted items and m is the number of ranges in `self`.
940    /// When n is large, consider using `|` which is O(n+m) time.
941    /// The nightly-only `cursor_nightly_experimental` feature speeds up this method by roughly 2x; see the
942    /// [Cargo Features section of the README](crate#cargo-features).
943    ///
944    /// # Examples
945    ///
946    /// ```
947    /// use range_set_blaze::RangeSetBlaze;
948    ///
949    /// let mut set = RangeSetBlaze::new();
950    ///
951    /// assert_eq!(set.ranges_insert(2..=5), true);
952    /// assert_eq!(set.ranges_insert(5..=6), true);
953    /// assert_eq!(set.ranges_insert(3..=4), false);
954    /// assert_eq!(set.len(), 5u64);
955    /// ```
956    pub fn ranges_insert<R>(&mut self, range: R) -> bool
957    where
958        R: RangeBounds<T>,
959    {
960        let len_before = self.len;
961        let (start, end) = extract_range(range);
962        self.internal_add(start..=end);
963        self.len != len_before
964    }
965
966    /// If the set contains an element equal to the value, removes it from the
967    /// set and drops it. Returns whether such an element was present.
968    ///
969    /// # Examples
970    ///
971    /// ```
972    /// use range_set_blaze::RangeSetBlaze;
973    ///
974    /// let mut set = RangeSetBlaze::new();
975    ///
976    /// set.insert(2);
977    /// assert!(set.remove(2));
978    /// assert!(!set.remove(2));
979    /// ```
980    pub fn remove(&mut self, value: T) -> bool {
981        // The code can have only one mutable reference to self.btree_map.
982        let Some((start_ref, end_ref)) = self.btree_map.range_mut(..=value).next_back() else {
983            return false;
984        };
985
986        let end = *end_ref;
987        if end < value {
988            return false;
989        }
990        let start = *start_ref;
991        // special case if in range and start strictly less than value
992        if start < value {
993            *end_ref = value.sub_one();
994            // special, special case if value == end
995            if value == end {
996                self.len -= <T::SafeLen>::one();
997                return true;
998            }
999        }
1000        self.len -= <T::SafeLen>::one();
1001        if start == value {
1002            self.btree_map.remove(&start);
1003        }
1004        if value < end {
1005            self.btree_map.insert(value.add_one(), end);
1006        }
1007        true
1008    }
1009
1010    /// Splits the collection into two at the value. Returns a new collection
1011    /// with all elements greater than or equal to the value.
1012    ///
1013    /// # Examples
1014    ///
1015    /// Basic usage:
1016    ///
1017    /// ```
1018    /// use range_set_blaze::RangeSetBlaze;
1019    ///
1020    /// let mut a = RangeSetBlaze::new();
1021    /// a.insert(1);
1022    /// a.insert(2);
1023    /// a.insert(3);
1024    /// a.insert(17);
1025    /// a.insert(41);
1026    ///
1027    /// let b = a.split_off(3);
1028    ///
1029    /// assert_eq!(a, RangeSetBlaze::from_iter([1, 2]));
1030    /// assert_eq!(b, RangeSetBlaze::from_iter([3, 17, 41]));
1031    /// ```
1032    #[must_use]
1033    pub fn split_off(&mut self, key: T) -> Self {
1034        let old_len = self.len;
1035        let old_btree_len = self.btree_map.len();
1036        let mut new_btree = self.btree_map.split_off(&key);
1037        let Some(last_entry) = self.btree_map.last_entry() else {
1038            // Left is empty
1039            self.len = T::SafeLen::zero();
1040            return Self {
1041                btree_map: new_btree,
1042                len: old_len,
1043            };
1044        };
1045
1046        let end = *last_entry.get();
1047        if end < key {
1048            // The split is clean
1049            let (a_len, b_len) = self.two_element_lengths(old_btree_len, &new_btree, old_len);
1050            self.len = a_len;
1051            return Self {
1052                btree_map: new_btree,
1053                len: b_len,
1054            };
1055        }
1056
1057        // The split is not clean, so we must move some keys from the end of self to the start of b.
1058        *(last_entry.into_mut()) = key.sub_one();
1059        new_btree.insert(key, end);
1060        let (a_len, b_len) = self.two_element_lengths(old_btree_len, &new_btree, old_len);
1061        self.len = a_len;
1062        Self {
1063            btree_map: new_btree,
1064            len: b_len,
1065        }
1066    }
1067
1068    // Find the len of the smaller btree_map and then the element len of self & b.
1069    fn two_element_lengths(
1070        &self,
1071        old_btree_len: usize,
1072        new_btree: &BTreeMap<T, T>,
1073        mut old_len: <T as Integer>::SafeLen,
1074    ) -> (<T as Integer>::SafeLen, <T as Integer>::SafeLen) {
1075        if old_btree_len / 2 < new_btree.len() {
1076            let a_len = Self::btree_map_len(&self.btree_map);
1077            old_len -= a_len;
1078            (a_len, old_len)
1079        } else {
1080            let b_len = Self::btree_map_len(new_btree);
1081            old_len -= b_len;
1082            (old_len, b_len)
1083        }
1084    }
1085
1086    fn btree_map_len(btree_map: &BTreeMap<T, T>) -> T::SafeLen {
1087        btree_map
1088            .iter()
1089            .fold(<T as Integer>::SafeLen::zero(), |acc, (start, end)| {
1090                acc + T::safe_len(&(*start..=*end))
1091            })
1092    }
1093
1094    /// Removes and returns the element in the set, if any, that is equal to
1095    /// the value.
1096    ///
1097    /// # Examples
1098    ///
1099    /// ```
1100    /// use range_set_blaze::RangeSetBlaze;
1101    ///
1102    /// let mut set = RangeSetBlaze::from_iter([1, 2, 3]);
1103    /// assert_eq!(set.take(2), Some(2));
1104    /// assert_eq!(set.take(2), None);
1105    /// ```
1106    pub fn take(&mut self, value: T) -> Option<T> {
1107        if self.remove(value) {
1108            Some(value)
1109        } else {
1110            None
1111        }
1112    }
1113
1114    /// Adds a value to the set, replacing the existing element, if any, that is
1115    /// equal to the value. Returns the replaced element.
1116    ///
1117    /// Note: This is very similar to `insert`. It is included for consistency with [`BTreeSet`].
1118    ///
1119    /// [`BTreeSet`]: alloc::collections::BTreeSet
1120    ///
1121    /// # Examples
1122    ///
1123    /// ```
1124    /// use range_set_blaze::RangeSetBlaze;
1125    ///
1126    /// let mut set = RangeSetBlaze::new();
1127    /// assert!(set.replace(5).is_none());
1128    /// assert!(set.replace(5).is_some());
1129    /// ```
1130    pub fn replace(&mut self, value: T) -> Option<T> {
1131        if self.insert(value) {
1132            None
1133        } else {
1134            Some(value)
1135        }
1136    }
1137
1138    // https://stackoverflow.com/questions/49599833/how-to-find-next-smaller-key-in-btreemap-btreeset
1139    // https://stackoverflow.com/questions/35663342/how-to-modify-partially-remove-a-range-from-a-btreemap
1140    #[cfg(any(
1141        test,
1142        feature = "test_util",
1143        not(feature = "cursor_nightly_experimental")
1144    ))]
1145    pub(crate) fn internal_add_baseline(&mut self, range: RangeInclusive<T>) {
1146        let (start, end) = range.clone().into_inner();
1147        if end < start {
1148            return;
1149        }
1150        // FUTURE: would be nice of BTreeMap to have a partition_point function that returns two iterators
1151        let mut before = self.btree_map.range_mut(..=start).rev();
1152        if let Some((start_before, end_before)) = before.next() {
1153            // Must check this in two parts to avoid overflow
1154            if (*end_before)
1155                .checked_add_one()
1156                .is_some_and(|end_before_succ| end_before_succ < start)
1157            {
1158                self.internal_add2(&range);
1159            } else if *end_before < end {
1160                self.len += T::safe_len(&(*end_before..=end.sub_one()));
1161                *end_before = end;
1162                let start_before = *start_before;
1163                self.delete_extra(&(start_before..=end));
1164            } else {
1165                // completely contained, so do nothing
1166            }
1167        } else {
1168            self.internal_add2(&range);
1169        }
1170    }
1171
1172    #[cfg(feature = "cursor_nightly_experimental")]
1173    fn cursor_absorb_successors(
1174        cursor: &mut CursorMut<'_, T, T>,
1175        len: &mut T::SafeLen,
1176        mut pending_end: T,
1177        pending_is_stored: bool,
1178    ) -> T {
1179        // When `pending_is_stored` is true, `peek_prev()` is the already-extended
1180        // pending range. Successors are removed in place, and that predecessor is
1181        // extended again if a successor reaches farther to the right.
1182        let initial_pending_end = pending_end;
1183        while let Some((stored_start, stored_end)) = cursor
1184            .peek_next()
1185            .map(|(stored_start, stored_end)| (*stored_start, *stored_end))
1186        {
1187            let interacts =
1188                stored_start <= pending_end || pending_end.checked_add_one() == Some(stored_start);
1189            if !interacts {
1190                break;
1191            }
1192
1193            cursor
1194                .remove_next()
1195                .expect("Real Assert: the peeked successor still exists");
1196            *len -= T::safe_len(&(stored_start..=stored_end));
1197
1198            if stored_end > pending_end {
1199                pending_end = stored_end;
1200            }
1201        }
1202
1203        if pending_is_stored && pending_end > initial_pending_end {
1204            let (_, stored_end) = cursor
1205                .peek_prev()
1206                .expect("Real Assert: the stored pending range is the predecessor");
1207            // `pending_end > initial_pending_end` proves that `initial_pending_end`
1208            // is not the maximum value before computing the newly covered tail.
1209            *stored_end = pending_end;
1210            *len += T::safe_len(&(initial_pending_end.add_one()..=pending_end));
1211        }
1212        pending_end
1213    }
1214
1215    #[cfg(feature = "cursor_nightly_experimental")]
1216    pub(crate) fn internal_add_cursor(&mut self, range: RangeInclusive<T>) {
1217        let (start, mut pending_end) = range.into_inner();
1218        if pending_end < start {
1219            return;
1220        }
1221
1222        let mut cursor = self.btree_map.lower_bound_mut(Bound::Included(&start));
1223
1224        // `peek_prev` is the only range to the left that can overlap or touch the insertion.
1225        if let Some((_, stored_end)) = cursor.peek_prev() {
1226            let stored_end = *stored_end;
1227            let interacts = stored_end >= start || stored_end.checked_add_one() == Some(start);
1228            if interacts {
1229                if stored_end >= pending_end {
1230                    return;
1231                }
1232
1233                let (_, stored_end_mut) = cursor
1234                    .peek_prev()
1235                    .expect("Real Assert: the peeked predecessor still exists");
1236                // `stored_end < pending_end` was established above, so this
1237                // increment cannot overflow at the maximum element.
1238                self.len += T::safe_len(&(stored_end.add_one()..=pending_end));
1239                *stored_end_mut = pending_end;
1240                Self::cursor_absorb_successors(&mut cursor, &mut self.len, pending_end, true);
1241                debug_assert!(self.len == self.len_slow());
1242                return;
1243            }
1244        }
1245
1246        // An equal-start successor can contain the insertion exactly as stored.
1247        if cursor
1248            .peek_next()
1249            .is_some_and(|(stored_start, stored_end)| {
1250                *stored_start == start && *stored_end >= pending_end
1251            })
1252        {
1253            return;
1254        }
1255
1256        pending_end =
1257            Self::cursor_absorb_successors(&mut cursor, &mut self.len, pending_end, false);
1258        cursor
1259            .insert_before(start, pending_end)
1260            .expect("Real Assert: the range belongs at the cursor");
1261        self.len += T::safe_len(&(start..=pending_end));
1262        debug_assert!(self.len == self.len_slow());
1263    }
1264
1265    #[inline]
1266    pub(crate) fn internal_add(&mut self, range: RangeInclusive<T>) {
1267        #[cfg(feature = "cursor_nightly_experimental")]
1268        {
1269            self.internal_add_cursor(range);
1270        }
1271
1272        #[cfg(not(feature = "cursor_nightly_experimental"))]
1273        {
1274            self.internal_add_baseline(range);
1275        }
1276    }
1277
1278    #[cfg(any(
1279        test,
1280        feature = "test_util",
1281        not(feature = "cursor_nightly_experimental")
1282    ))]
1283    #[inline]
1284    fn internal_add2(&mut self, internal_range: &RangeInclusive<T>) {
1285        let (start, end) = internal_range.clone().into_inner();
1286        let was_there = self.btree_map.insert(start, end);
1287        debug_assert!(was_there.is_none()); // real assert
1288        self.delete_extra(internal_range);
1289        self.len += T::safe_len(internal_range);
1290    }
1291
1292    /// Returns the number of elements in the set.
1293    ///
1294    /// The number is allowed to be very, very large.
1295    ///
1296    /// # Examples
1297    ///
1298    /// ```
1299    /// use range_set_blaze::prelude::*;
1300    ///
1301    /// let mut v = RangeSetBlaze::new();
1302    /// assert_eq!(v.len(), 0u64);
1303    /// v.insert(1);
1304    /// assert_eq!(v.len(), 1u64);
1305    ///
1306    /// let v = RangeSetBlaze::from_iter([
1307    ///     -170_141_183_460_469_231_731_687_303_715_884_105_728i128..=10,
1308    ///     -10..=170_141_183_460_469_231_731_687_303_715_884_105_726,
1309    /// ]);
1310    /// assert_eq!(
1311    ///     v.len(),
1312    ///     UIntPlusOne::UInt(340282366920938463463374607431768211455)
1313    /// );
1314    /// ```
1315    #[must_use]
1316    pub const fn len(&self) -> <T as Integer>::SafeLen {
1317        self.len
1318    }
1319
1320    /// Makes a new, empty [`RangeSetBlaze`].
1321    ///
1322    /// # Examples
1323    ///
1324    /// ```
1325    /// # #![allow(unused_mut)]
1326    /// use range_set_blaze::RangeSetBlaze;
1327    ///
1328    /// let mut set: RangeSetBlaze<i32> = RangeSetBlaze::new();
1329    /// ```
1330    #[must_use]
1331    #[inline]
1332    pub fn new() -> Self {
1333        Self {
1334            btree_map: BTreeMap::new(),
1335            len: <T as Integer>::SafeLen::zero(),
1336        }
1337    }
1338
1339    /// Removes the first element from the set and returns it, if any.
1340    /// The first element is always the minimum element in the set.
1341    ///
1342    /// # Examples
1343    ///
1344    /// ```
1345    /// use range_set_blaze::RangeSetBlaze;
1346    ///
1347    /// let mut set = RangeSetBlaze::new();
1348    ///
1349    /// set.insert(1);
1350    /// while let Some(n) = set.pop_first() {
1351    ///     assert_eq!(n, 1);
1352    /// }
1353    /// assert!(set.is_empty());
1354    /// ```
1355    pub fn pop_first(&mut self) -> Option<T> {
1356        if let Some(entry) = self.btree_map.first_entry() {
1357            let (start, end) = entry.remove_entry();
1358            self.len -= T::safe_len(&(start..=end));
1359            if start != end {
1360                let start = start.add_one();
1361                self.btree_map.insert(start, end);
1362                self.len += T::safe_len(&(start..=end));
1363            }
1364            Some(start)
1365        } else {
1366            None
1367        }
1368    }
1369
1370    /// Removes the last value from the set and returns it, if any.
1371    /// The last value is always the maximum value in the set.
1372    ///
1373    /// # Examples
1374    ///
1375    /// ```
1376    /// use range_set_blaze::RangeSetBlaze;
1377    ///
1378    /// let mut set = RangeSetBlaze::new();
1379    ///
1380    /// set.insert(1);
1381    /// while let Some(n) = set.pop_last() {
1382    ///     assert_eq!(n, 1);
1383    /// }
1384    /// assert!(set.is_empty());
1385    /// ```
1386    pub fn pop_last(&mut self) -> Option<T> {
1387        let mut entry = self.btree_map.last_entry()?;
1388        let start = *entry.key();
1389        let end = entry.get_mut();
1390        let result = *end;
1391        self.len -= T::safe_len(&(start..=*end));
1392        if start == *end {
1393            entry.remove_entry();
1394        } else {
1395            (*end).assign_sub_one();
1396            self.len += T::safe_len(&(start..=*end));
1397        }
1398        Some(result)
1399    }
1400
1401    /// An iterator that visits the ranges in the [`RangeSetBlaze`],
1402    /// i.e., the integers as sorted & disjoint ranges. Double-ended.
1403    ///
1404    /// Also see [`RangeSetBlaze::iter`] and [`RangeSetBlaze::into_ranges`].
1405    ///
1406    /// # Examples
1407    ///
1408    /// ```
1409    /// use range_set_blaze::RangeSetBlaze;
1410    ///
1411    /// let set = RangeSetBlaze::from_iter([10..=20, 15..=25, 30..=40]);
1412    /// let mut ranges = set.ranges();
1413    /// assert_eq!(ranges.next(), Some(10..=25));
1414    /// assert_eq!(ranges.next(), Some(30..=40));
1415    /// assert_eq!(ranges.next(), None);
1416    /// ```
1417    ///
1418    /// Values returned by the iterator are returned in ascending order:
1419    ///
1420    /// ```
1421    /// use range_set_blaze::RangeSetBlaze;
1422    ///
1423    /// let set = RangeSetBlaze::from_iter([30..=40, 15..=25, 10..=20]);
1424    /// let mut ranges = set.ranges();
1425    /// assert_eq!(ranges.next(), Some(10..=25));
1426    /// assert_eq!(ranges.next(), Some(30..=40));
1427    /// assert_eq!(ranges.next(), None);
1428    /// ```
1429    pub fn ranges(&self) -> RangesIter<'_, T> {
1430        RangesIter {
1431            iter: self.btree_map.iter(),
1432        }
1433    }
1434
1435    /// Returns a [`RangeMapBlaze`] over the complete integer domain, mapping
1436    /// present ranges to `true` and gaps to `false`.
1437    ///
1438    /// The result covers [`Integer::min_value`] through [`Integer::max_value`].
1439    /// The `false` values are ordinary map values, so the resulting map's key
1440    /// domain is universal. Because map operators act on those key ranges, `!`
1441    /// on the filled map yields an empty set rather than negating the Boolean
1442    /// values.
1443    ///
1444    /// To fill gaps lazily without materializing a map, use
1445    /// [`SortedDisjoint::fill_gaps`] on a set stream such as
1446    /// [`RangeSetBlaze::ranges`].
1447    ///
1448    /// The [Ranges and gaps guide][crate::gaps] compares this materialized form
1449    /// with the lazy streaming form and its map counterpart.
1450    ///
1451    /// # Examples
1452    ///
1453    /// ```
1454    /// # use range_set_blaze::RangeSetBlaze;
1455    /// let set = RangeSetBlaze::from_iter([1..=3, 7..=10]);
1456    /// let filled = set.fill_gaps();
1457    /// assert_eq!(filled.get(i32::MIN), Some(&false));
1458    /// assert_eq!(filled.get(2), Some(&true));
1459    /// assert_eq!(filled.get(5), Some(&false));
1460    /// assert_eq!(filled.get(8), Some(&true));
1461    /// assert_eq!(filled.get(i32::MAX), Some(&false));
1462    /// ```
1463    #[must_use]
1464    pub fn fill_gaps(&self) -> RangeMapBlaze<T, bool> {
1465        self.ranges().fill_gaps().into_range_map_blaze()
1466    }
1467
1468    /// An iterator that moves out the ranges in the [`RangeSetBlaze`],
1469    /// i.e., the integers as sorted & disjoint ranges.
1470    ///
1471    /// Also see [`RangeSetBlaze::into_iter`] and [`RangeSetBlaze::ranges`].
1472    ///
1473    /// # Examples
1474    ///
1475    /// ```
1476    /// use range_set_blaze::RangeSetBlaze;
1477    ///
1478    /// let mut ranges = RangeSetBlaze::from_iter([10..=20, 15..=25, 30..=40]).into_ranges();
1479    /// assert_eq!(ranges.next(), Some(10..=25));
1480    /// assert_eq!(ranges.next(), Some(30..=40));
1481    /// assert_eq!(ranges.next(), None);
1482    /// ```
1483    ///
1484    /// Values returned by the iterator are returned in ascending order:
1485    ///
1486    /// ```
1487    /// use range_set_blaze::RangeSetBlaze;
1488    ///
1489    /// let mut ranges = RangeSetBlaze::from_iter([30..=40, 15..=25, 10..=20]).into_ranges();
1490    /// assert_eq!(ranges.next(), Some(10..=25));
1491    /// assert_eq!(ranges.next(), Some(30..=40));
1492    /// assert_eq!(ranges.next(), None);
1493    /// ```
1494    pub fn into_ranges(self) -> IntoRangesIter<T> {
1495        IntoRangesIter {
1496            iter: self.btree_map.into_iter(),
1497        }
1498    }
1499
1500    /// Deprecated. Use `RangeSetBlaze::to_string` instead.
1501    #[deprecated(since = "0.2.0", note = "Use `RangeSetBlaze::to_string` instead.")]
1502    pub fn into_string(&self) -> String {
1503        self.to_string()
1504    }
1505
1506    // FUTURE BTreeSet some of these as 'const' but it uses unstable. When stable, add them here and elsewhere.
1507
1508    /// Returns the number of sorted & disjoint ranges in the set.
1509    ///
1510    /// # Example
1511    ///
1512    /// ```
1513    /// use range_set_blaze::RangeSetBlaze;
1514    ///
1515    /// // We put in three ranges, but they are not sorted & disjoint.
1516    /// let set = RangeSetBlaze::from_iter([10..=20, 15..=25, 30..=40]);
1517    /// // After RangeSetBlaze sorts & 'disjoint's them, we see two ranges.
1518    /// assert_eq!(set.ranges_len(), 2);
1519    /// assert_eq!(set.to_string(), "10..=25, 30..=40");
1520    /// ```
1521    #[must_use]
1522    pub fn ranges_len(&self) -> usize {
1523        self.btree_map.len()
1524    }
1525
1526    /// Retains only the elements specified by the predicate.
1527    ///
1528    /// In other words, remove all integers `t` for which `f(&t)` returns `false`.
1529    /// The integer elements are visited in ascending order.
1530    ///
1531    /// Because if visits every element in every range, it is expensive compared to
1532    /// [`RangeSetBlaze::ranges_retain`].
1533    ///
1534    /// # Examples
1535    ///
1536    /// ```
1537    /// use range_set_blaze::RangeSetBlaze;
1538    ///
1539    /// let mut set = RangeSetBlaze::from_iter([1..=6]);
1540    /// // Keep only the even numbers.
1541    /// set.retain(|k| k % 2 == 0);
1542    /// assert_eq!(set, RangeSetBlaze::from_iter([2, 4, 6]));
1543    /// ```
1544    pub fn retain<F>(&mut self, mut f: F)
1545    where
1546        F: FnMut(&T) -> bool,
1547    {
1548        *self = self.iter().filter(|t| f(t)).collect();
1549    }
1550
1551    /// Retains only the ranges specified by the predicate.
1552    ///
1553    /// In other words, remove all ranges `r` for which `f(&r)` returns `false`.
1554    /// The ranges are visited in ascending order.
1555    ///
1556    /// # Examples
1557    ///
1558    /// ```
1559    /// use range_set_blaze::RangeSetBlaze;
1560    ///
1561    /// let mut set = RangeSetBlaze::from_iter([1..=6, 10..=15]);
1562    /// // Keep only the ranges starting before 10.
1563    /// set.ranges_retain(|range| range.start() < &10);
1564    /// assert_eq!(set, RangeSetBlaze::from_iter([1..=6]));
1565    /// ```
1566    pub fn ranges_retain<F>(&mut self, mut f: F)
1567    where
1568        F: FnMut(&RangeInclusive<T>) -> bool,
1569    {
1570        self.btree_map.retain(|start, end| {
1571            let range = *start..=*end;
1572            if f(&range) {
1573                true
1574            } else {
1575                self.len -= T::safe_len(&range);
1576                false
1577            }
1578        });
1579    }
1580}
1581
1582// We create a RangeSetBlaze from an iterator of integers or integer ranges by
1583// 1. turning them into a UnionIter (internally, it collects into intervals and sorts by start).
1584// 2. Turning the SortedDisjoint into a BTreeMap.
1585impl<T: Integer> FromIterator<T> for RangeSetBlaze<T> {
1586    /// Create a [`RangeSetBlaze`] from an iterator of integers. Duplicates and out-of-order elements are fine.
1587    ///
1588    /// *For more about constructors and performance, see [`RangeSetBlaze` Constructors](struct.RangeSetBlaze.html#rangesetblaze-constructors).*
1589    ///
1590    /// # Examples
1591    ///
1592    /// ```
1593    /// use range_set_blaze::RangeSetBlaze;
1594    ///
1595    /// let a0 = RangeSetBlaze::from_iter([3, 2, 1, 100, 1]);
1596    /// let a1: RangeSetBlaze<i32> = [3, 2, 1, 100, 1].into_iter().collect();
1597    /// assert!(a0 == a1 && a0.to_string() == "1..=3, 100..=100");
1598    /// ```
1599    fn from_iter<I>(iter: I) -> Self
1600    where
1601        I: IntoIterator<Item = T>,
1602    {
1603        iter.into_iter().map(|x| x..=x).collect()
1604    }
1605}
1606
1607impl<'a, T: Integer> FromIterator<&'a T> for RangeSetBlaze<T> {
1608    /// Create a [`RangeSetBlaze`] from an iterator of integers references. Duplicates and out-of-order elements are fine.
1609    ///
1610    /// *For more about constructors and performance, see [`RangeSetBlaze` Constructors](struct.RangeSetBlaze.html#rangesetblaze-constructors).*
1611    ///
1612    /// # Examples
1613    ///
1614    /// ```
1615    /// use range_set_blaze::RangeSetBlaze;
1616    ///
1617    /// let a0 = RangeSetBlaze::from_iter(vec![3, 2, 1, 100, 1]);
1618    /// let a1: RangeSetBlaze<i32> = vec![3, 2, 1, 100, 1].into_iter().collect();
1619    /// assert!(a0 == a1 && a0.to_string() == "1..=3, 100..=100");
1620    /// ```
1621    fn from_iter<I>(iter: I) -> Self
1622    where
1623        I: IntoIterator<Item = &'a T>,
1624    {
1625        iter.into_iter().map(|x| *x..=*x).collect()
1626    }
1627}
1628
1629impl<T: Integer> FromIterator<RangeInclusive<T>> for RangeSetBlaze<T> {
1630    /// Create a [`RangeSetBlaze`] from an iterator of inclusive ranges, `start..=end`.
1631    /// Overlapping, out-of-order, and empty ranges are fine.
1632    ///
1633    /// *For more about constructors and performance, see [`RangeSetBlaze` Constructors](struct.RangeSetBlaze.html#rangesetblaze-constructors).*
1634    ///
1635    /// # Examples
1636    ///
1637    /// ```
1638    /// use range_set_blaze::RangeSetBlaze;
1639    ///
1640    /// #[allow(clippy::reversed_empty_ranges)]
1641    /// let a0 = RangeSetBlaze::from_iter([1..=2, 2..=2, -10..=-5, 1..=0]);
1642    /// #[allow(clippy::reversed_empty_ranges)]
1643    /// let a1: RangeSetBlaze<i32> = [1..=2, 2..=2, -10..=-5, 1..=0].into_iter().collect();
1644    /// assert!(a0 == a1 && a0.to_string() == "-10..=-5, 1..=2");
1645    /// ```
1646    fn from_iter<I>(iter: I) -> Self
1647    where
1648        I: IntoIterator<Item = RangeInclusive<T>>,
1649    {
1650        let union_iter: UnionIter<T, _> = iter.into_iter().collect();
1651        Self::from_sorted_disjoint(union_iter)
1652    }
1653}
1654
1655impl<'a, T: Integer> FromIterator<&'a RangeInclusive<T>> for RangeSetBlaze<T> {
1656    /// Create a [`RangeSetBlaze`] from an iterator of inclusive ranges, `start..=end`.
1657    /// Overlapping, out-of-order, and empty ranges are fine.
1658    ///
1659    /// *For more about constructors and performance, see [`RangeSetBlaze` Constructors](struct.RangeSetBlaze.html#rangesetblaze-constructors).*
1660    ///
1661    /// # Examples
1662    ///
1663    /// ```
1664    /// use range_set_blaze::RangeSetBlaze;
1665    ///
1666    /// #[allow(clippy::reversed_empty_ranges)]
1667    /// let vec_range = vec![1..=2, 2..=2, -10..=-5, 1..=0];
1668    /// let a0 = RangeSetBlaze::from_iter(&vec_range);
1669    /// let a1: RangeSetBlaze<i32> = vec_range.iter().collect();
1670    /// assert!(a0 == a1 && a0.to_string() == "-10..=-5, 1..=2");
1671    /// ```
1672    fn from_iter<I>(iter: I) -> Self
1673    where
1674        I: IntoIterator<Item = &'a RangeInclusive<T>>,
1675    {
1676        let union_iter: UnionIter<T, _> = iter.into_iter().cloned().collect();
1677        Self::from_sorted_disjoint(union_iter)
1678    }
1679}
1680
1681impl<T: Integer, const N: usize> From<[T; N]> for RangeSetBlaze<T> {
1682    /// For compatibility with [`BTreeSet`] you may create a [`RangeSetBlaze`] from an array of integers.
1683    ///
1684    /// *For more about constructors and performance, see [`RangeSetBlaze` Constructors](struct.RangeSetBlaze.html#rangesetblaze-constructors).*
1685    ///
1686    /// [`BTreeSet`]: alloc::collections::BTreeSet
1687    ///
1688    /// # Examples
1689    ///
1690    /// ```
1691    /// use range_set_blaze::RangeSetBlaze;
1692    ///
1693    /// let a0 = RangeSetBlaze::from([3, 2, 1, 100, 1]);
1694    /// let a1: RangeSetBlaze<i32> = [3, 2, 1, 100, 1].into();
1695    /// assert!(a0 == a1 && a0.to_string() == "1..=3, 100..=100")
1696    /// ```
1697    #[cfg(not(feature = "from_slice"))]
1698    fn from(arr: [T; N]) -> Self {
1699        arr.into_iter().collect()
1700    }
1701    #[cfg(feature = "from_slice")]
1702    fn from(arr: [T; N]) -> Self {
1703        Self::from_slice(arr)
1704    }
1705}
1706
1707impl<T: Integer> From<RangeInclusive<T>> for RangeSetBlaze<T> {
1708    /// Construct a [`RangeSetBlaze<T>`] directly from a [`RangeInclusive<T>`].
1709    fn from(value: RangeInclusive<T>) -> Self {
1710        Self::from_sorted_disjoint(RangeOnce::new(value))
1711    }
1712}
1713
1714gen_ops_ex!(
1715    <T>;
1716    types ref RangeSetBlaze<T>, ref RangeSetBlaze<T> => RangeSetBlaze<T>;
1717
1718    /// Intersects the contents of two [`RangeSetBlaze`]'s.
1719    ///
1720    /// Either, neither, or both inputs may be borrowed.
1721    ///
1722    /// # Examples
1723    /// ```
1724    /// use range_set_blaze::prelude::*;
1725    ///
1726    /// let a = RangeSetBlaze::from_iter([1..=2, 5..=100]);
1727    /// let b = RangeSetBlaze::from_iter([2..=6]);
1728    /// let result = &a & &b; // Alternatively, 'a & b'.
1729    /// assert_eq!(result.to_string(), "2..=2, 5..=6");
1730    /// ```
1731    for & call |a: &RangeSetBlaze<T>, b: &RangeSetBlaze<T>| {
1732        (a.ranges() & b.ranges()).into_range_set_blaze()
1733    };
1734
1735    /// Symmetric difference the contents of two [`RangeSetBlaze`]'s.
1736    ///
1737    /// Either, neither, or both inputs may be borrowed.
1738    ///
1739    /// # Examples
1740    /// ```
1741    /// use range_set_blaze::prelude::*;
1742    ///
1743    /// let a = RangeSetBlaze::from_iter([1..=2, 5..=100]);
1744    /// let b = RangeSetBlaze::from_iter([2..=6]);
1745    /// let result = &a ^ &b; // Alternatively, 'a ^ b'.
1746    /// assert_eq!(result.to_string(), "1..=1, 3..=4, 7..=100");
1747    /// ```
1748    for ^ call |a: &RangeSetBlaze<T>, b: &RangeSetBlaze<T>| {
1749        a.ranges().symmetric_difference(b.ranges()).into_range_set_blaze()
1750    };
1751
1752    /// Difference the contents of two [`RangeSetBlaze`]'s.
1753    ///
1754    /// Either, neither, or both inputs may be borrowed.
1755    ///
1756    /// # Examples
1757    /// ```
1758    /// use range_set_blaze::prelude::*;
1759    ///
1760    /// let a = RangeSetBlaze::from_iter([1..=2, 5..=100]);
1761    /// let b = RangeSetBlaze::from_iter([2..=6]);
1762    /// let result = &a - &b; // Alternatively, 'a - b'.
1763    /// assert_eq!(result.to_string(), "1..=1, 7..=100");
1764    /// ```
1765    for - call |a: &RangeSetBlaze<T>, b: &RangeSetBlaze<T>| {
1766        (a.ranges() - b.ranges()).into_range_set_blaze()
1767    };
1768    where T: Integer //Where clause for all impl's
1769);
1770
1771gen_ops_ex!(
1772    <T>;
1773    types ref RangeSetBlaze<T> => RangeSetBlaze<T>;
1774
1775    /// Complement the contents of a [`RangeSetBlaze`].
1776    ///
1777    /// The input may be borrowed or not.
1778    ///
1779    /// # Examples
1780    /// ```
1781    /// use range_set_blaze::prelude::*;
1782    ///
1783    /// let a = RangeSetBlaze::from_iter([1..=2, 5..=100]);
1784    /// let result = !&a; // Alternatively, '!a'.
1785    /// assert_eq!(
1786    ///     result.to_string(),
1787    ///     "-2147483648..=0, 3..=4, 101..=2147483647"
1788    /// );
1789    /// ```
1790    for ! call |a: &RangeSetBlaze<T>| {
1791        (!a.ranges()).into_range_set_blaze()
1792    };
1793
1794    where T: Integer //Where clause for all impl's
1795);
1796
1797// Implementing `IntoIterator` for `&RangeSetBlaze` because BTreeSet does.
1798impl<'a, T: Integer> IntoIterator for &'a RangeSetBlaze<T> {
1799    type Item = T;
1800    type IntoIter = Iter<T, RangesIter<'a, T>>;
1801    fn into_iter(self) -> Self::IntoIter {
1802        self.iter()
1803    }
1804}
1805
1806impl<T: Integer> IntoIterator for RangeSetBlaze<T> {
1807    type Item = T;
1808    type IntoIter = IntoIter<T>;
1809
1810    /// Gets an iterator for moving out the [`RangeSetBlaze`]'s integer contents.
1811    /// Double-ended.
1812    ///
1813    /// # Examples
1814    ///
1815    /// ```
1816    /// use range_set_blaze::RangeSetBlaze;
1817    ///
1818    /// let set = RangeSetBlaze::from_iter([1, 2, 3, 4]);
1819    ///
1820    /// let v: Vec<_> = set.into_iter().collect();
1821    /// assert_eq!(v, [1, 2, 3, 4]);
1822    ///
1823    /// let set = RangeSetBlaze::from_iter([1, 2, 3, 4]);
1824    /// let v: Vec<_> = set.into_iter().rev().collect();
1825    /// assert_eq!(v, [4, 3, 2, 1]);
1826    /// ```
1827    fn into_iter(self) -> IntoIter<T> {
1828        IntoIter {
1829            option_range_front: None,
1830            option_range_back: None,
1831            btree_map_into_iter: self.btree_map.into_iter(),
1832        }
1833    }
1834}
1835
1836/// An iterator over the integer elements of a [`RangeSetBlaze`]. Double-ended.
1837///
1838/// This `struct` is created by the [`iter`] method on [`RangeSetBlaze`]. See its
1839/// documentation for more.
1840///
1841/// [`iter`]: RangeSetBlaze::iter
1842#[must_use = "iterators are lazy and do nothing unless consumed"]
1843#[derive(Clone, Debug)]
1844#[allow(clippy::struct_field_names)]
1845pub struct Iter<T, I> {
1846    btree_set_iter: I,
1847    // FUTURE: here and elsewhere, when core::iter:Step is available could
1848    // FUTURE: use RangeInclusive as an iterator (with exhaustion) rather than needing an Option
1849    range_front: RangeInclusive<T>,
1850    range_back: RangeInclusive<T>,
1851}
1852
1853impl<T: Integer, I> FusedIterator for Iter<T, I> where I: SortedDisjoint<T> + FusedIterator {}
1854
1855impl<T: Integer, I> Iterator for Iter<T, I>
1856where
1857    I: SortedDisjoint<T>,
1858{
1859    type Item = T;
1860    fn next(&mut self) -> Option<T> {
1861        // return the next integer (if any) from range_front
1862        if let Some(next_item) = T::range_next(&mut self.range_front) {
1863            return Some(next_item);
1864        }
1865
1866        // if range_front is exhausted, get the next range from the btree_set_iter and its next integer
1867        if let Some(next_range) = self.btree_set_iter.next() {
1868            debug_assert!(next_range.start() <= next_range.end()); // real assert
1869            self.range_front = next_range;
1870            return T::range_next(&mut self.range_front); // will never be None
1871        }
1872
1873        // if that doesn't work, move the back range to the front and get the next integer (if any)
1874        self.range_front = mem::replace(&mut self.range_back, T::exhausted_range());
1875        T::range_next(&mut self.range_front)
1876    }
1877
1878    // We'll have at least as many integers as intervals. There could be more that usize MAX
1879    // The option_range field could increase the number of integers, but we can ignore that.
1880    fn size_hint(&self) -> (usize, Option<usize>) {
1881        let (low, _high) = self.btree_set_iter.size_hint();
1882        (low, None)
1883    }
1884}
1885
1886impl<T: Integer, I> DoubleEndedIterator for Iter<T, I>
1887where
1888    I: SortedDisjoint<T> + DoubleEndedIterator,
1889{
1890    fn next_back(&mut self) -> Option<Self::Item> {
1891        // return the next_back integer (if any) from range_back
1892        if let Some(next_item) = T::range_next_back(&mut self.range_back) {
1893            return Some(next_item);
1894        }
1895
1896        // if the range_back is exhausted, get the next_back range from the btree_set_iter and its next_back integer
1897        if let Some(next_back_range) = self.btree_set_iter.next_back() {
1898            debug_assert!(next_back_range.start() <= next_back_range.end()); // real assert
1899            self.range_back = next_back_range;
1900            return T::range_next_back(&mut self.range_back); // will never be None
1901        }
1902
1903        // if that doesn't work, move the front range to the back and get the next back integer (if any)
1904        self.range_back = mem::replace(&mut self.range_front, T::exhausted_range());
1905        T::range_next_back(&mut self.range_back)
1906    }
1907}
1908
1909/// An iterator over the integer elements of a [`RangeSetBlaze`]. Double-ended.
1910///
1911/// This `struct` is created by the [`into_iter`] method on [`RangeSetBlaze`]. See its
1912/// documentation for more.
1913///
1914/// [`into_iter`]: RangeSetBlaze::into_iter
1915#[must_use = "iterators are lazy and do nothing unless consumed"]
1916#[derive(Debug)]
1917#[allow(clippy::struct_field_names)]
1918pub struct IntoIter<T> {
1919    option_range_front: Option<RangeInclusive<T>>,
1920    option_range_back: Option<RangeInclusive<T>>,
1921    btree_map_into_iter: btree_map::IntoIter<T, T>,
1922}
1923
1924impl<T: Integer> FusedIterator for IntoIter<T> {}
1925
1926impl<T: Integer> Iterator for IntoIter<T> {
1927    type Item = T;
1928
1929    fn next(&mut self) -> Option<Self::Item> {
1930        let range = self
1931            .option_range_front
1932            .take()
1933            .or_else(|| {
1934                self.btree_map_into_iter
1935                    .next()
1936                    .map(|(start, end)| start..=end)
1937            })
1938            .or_else(|| self.option_range_back.take())?;
1939
1940        let (start, end) = range.into_inner();
1941        debug_assert!(start <= end);
1942        if start < end {
1943            self.option_range_front = Some(start.add_one()..=end);
1944        }
1945        Some(start)
1946    }
1947
1948    // We'll have at least as many integers as intervals. There could be more that usize MAX
1949    // the option_range field could increase the number of integers, but we can ignore that.
1950    fn size_hint(&self) -> (usize, Option<usize>) {
1951        let (low, _high) = self.btree_map_into_iter.size_hint();
1952        (low, None)
1953    }
1954}
1955
1956impl<T: Integer> DoubleEndedIterator for IntoIter<T> {
1957    fn next_back(&mut self) -> Option<Self::Item> {
1958        let range = self
1959            .option_range_back
1960            .take()
1961            .or_else(|| {
1962                self.btree_map_into_iter
1963                    .next_back()
1964                    .map(|(start, end)| start..=end)
1965            })
1966            .or_else(|| self.option_range_front.take())?;
1967
1968        let (start, end) = range.into_inner();
1969        debug_assert!(start <= end);
1970        if start < end {
1971            self.option_range_back = Some(start..=end.sub_one());
1972        }
1973
1974        Some(end)
1975    }
1976}
1977
1978impl<T: Integer> Extend<T> for RangeSetBlaze<T> {
1979    /// Extends the [`RangeSetBlaze`] with the contents of an Integer iterator.
1980    ///
1981    /// Integers are added one-by-one. There is also a version
1982    /// that takes a range iterator.
1983    ///
1984    /// The [`|=`](RangeSetBlaze::bitor_assign) operator extends a [`RangeSetBlaze`]
1985    /// from another [`RangeSetBlaze`]. It is never slower
1986    /// than  [`RangeSetBlaze::extend`] and often several times faster.
1987    ///
1988    /// # Examples
1989    /// ```
1990    /// use range_set_blaze::RangeSetBlaze;
1991    /// let mut a = RangeSetBlaze::from_iter([1..=4]);
1992    /// a.extend([5, 0, 0, 3, 4, 10]);
1993    /// assert_eq!(a, RangeSetBlaze::from_iter([0..=5, 10..=10]));
1994    ///
1995    /// let mut a = RangeSetBlaze::from_iter([1..=4]);
1996    /// let mut b = RangeSetBlaze::from_iter([5, 0, 0, 3, 4, 10]);
1997    /// a |= b;
1998    /// assert_eq!(a, RangeSetBlaze::from_iter([0..=5, 10..=10]));
1999    /// ```
2000    #[inline]
2001    fn extend<I>(&mut self, iter: I)
2002    where
2003        I: IntoIterator<Item = T>,
2004    {
2005        let iter = iter.into_iter();
2006        for range in UnsortedDisjoint::new(iter.map(|x| x..=x)) {
2007            self.internal_add(range);
2008        }
2009    }
2010}
2011
2012impl<T: Integer> BitOrAssign<&Self> for RangeSetBlaze<T> {
2013    /// Adds the contents of another [`RangeSetBlaze`] to this one.
2014    ///
2015    /// Passing the right-hand side by ownership rather than borrow
2016    /// will allow a many-times faster speed up when the
2017    /// right-hand side is much larger than the left-hand side.
2018    ///
2019    /// Also, this operation is never slower than [`RangeSetBlaze::extend`] and
2020    /// can often be many times faster.
2021    ///
2022    /// # Examples
2023    /// ```
2024    /// use range_set_blaze::RangeSetBlaze;
2025    /// let mut a = RangeSetBlaze::from_iter([1..=4]);
2026    /// let mut b = RangeSetBlaze::from_iter([0..=0, 3..=5, 10..=10]);
2027    /// a |= &b;
2028    /// assert_eq!(a, RangeSetBlaze::from_iter([0..=5, 10..=10]));
2029    /// ```
2030    fn bitor_assign(&mut self, other: &Self) {
2031        let b_len = other.ranges_len();
2032        if b_len == 0 {
2033            return;
2034        }
2035        let a_len = self.ranges_len();
2036        if a_len == 0 {
2037            *self = other.clone();
2038            return;
2039        }
2040        let a_len_log2: usize = a_len
2041            .ilog2()
2042            .try_into() // u32 → usize
2043            .expect(
2044                "ilog2 result always fits in usize on our targets so this will be optimized away",
2045            );
2046
2047        if b_len * (a_len_log2 + 1) < a_len + b_len {
2048            for (start, end) in &other.btree_map {
2049                self.internal_add(*start..=*end);
2050            }
2051        } else {
2052            *self = (self.ranges() | other.ranges()).into_range_set_blaze();
2053        }
2054    }
2055}
2056
2057impl<T: Integer> BitOrAssign<Self> for RangeSetBlaze<T> {
2058    /// Adds the contents of another [`RangeSetBlaze`] to this one.
2059    ///
2060    /// Passing the right-hand side by ownership rather than borrow
2061    /// will allow a many-times faster speed up when the
2062    /// right-hand side is much larger than the left-hand side.
2063    ///
2064    /// Also, this operation is never slower than [`RangeSetBlaze::extend`] and
2065    /// can often be many times faster.
2066    ///
2067    ///
2068    /// # Examples
2069    /// ```
2070    /// use range_set_blaze::RangeSetBlaze;
2071    /// let mut a = RangeSetBlaze::from_iter([1..=4]);
2072    /// let mut b = RangeSetBlaze::from_iter([0..=0, 3..=5, 10..=10]);
2073    /// a |= b;
2074    /// assert_eq!(a, RangeSetBlaze::from_iter([0..=5, 10..=10]));
2075    /// ```
2076    fn bitor_assign(&mut self, mut other: Self) {
2077        let a_len = self.ranges_len();
2078        let b_len = other.ranges_len();
2079        if b_len <= a_len {
2080            *self |= &other;
2081        } else {
2082            other |= &*self;
2083            *self = other;
2084        }
2085    }
2086}
2087
2088impl<T: Integer> BitOr<Self> for RangeSetBlaze<T> {
2089    /// Unions the contents of two [`RangeSetBlaze`]'s.
2090    ///
2091    /// Passing ownership rather than borrow sometimes allows a many-times
2092    /// faster speed up.
2093    ///
2094    /// Also see [`a |= b`](RangeSetBlaze::bitor_assign).
2095    ///
2096    /// # Examples
2097    /// ```
2098    /// use range_set_blaze::RangeSetBlaze;
2099    /// let a = RangeSetBlaze::from_iter([1..=4]);
2100    /// let b = RangeSetBlaze::from_iter([0..=0, 3..=5, 10..=10]);
2101    /// let union = a | b; // Alternatively, '&a | &b', etc.
2102    /// assert_eq!(union, RangeSetBlaze::from_iter([0..=5, 10..=10]));
2103    /// ```
2104    type Output = Self;
2105    fn bitor(mut self, other: Self) -> Self {
2106        self |= other;
2107        self
2108    }
2109}
2110
2111impl<T: Integer> BitOr<&Self> for RangeSetBlaze<T> {
2112    /// Unions the contents of two [`RangeSetBlaze`]'s.
2113    ///
2114    /// Passing ownership rather than borrow sometimes allows a many-times
2115    /// faster speed up.
2116    ///
2117    /// Also see [`a |= b`](RangeSetBlaze::bitor_assign).
2118    ///
2119    /// # Examples
2120    /// ```
2121    /// use range_set_blaze::RangeSetBlaze;
2122    /// let a = RangeSetBlaze::from_iter([1..=4]);
2123    /// let b = RangeSetBlaze::from_iter([0..=0, 3..=5, 10..=10]);
2124    /// let union = a | &b;  // Alternatively, 'a | b', etc.
2125    /// assert_eq!(union, RangeSetBlaze::from_iter([0..=5, 10..=10]));
2126    /// ```
2127    type Output = Self;
2128    fn bitor(mut self, other: &Self) -> Self {
2129        self |= other;
2130        self
2131    }
2132}
2133
2134impl<T: Integer> BitOr<RangeSetBlaze<T>> for &RangeSetBlaze<T> {
2135    type Output = RangeSetBlaze<T>;
2136    /// Unions the contents of two [`RangeSetBlaze`]'s.
2137    ///
2138    /// Passing ownership rather than borrow sometimes allows a many-times
2139    /// faster speed up.
2140    ///
2141    /// Also see [`a |= b`](RangeSetBlaze::bitor_assign).
2142    ///
2143    /// # Examples
2144    /// ```
2145    /// use range_set_blaze::RangeSetBlaze;
2146    /// let a = RangeSetBlaze::from_iter([1..=4]);
2147    /// let b = RangeSetBlaze::from_iter([0..=0, 3..=5, 10..=10]);
2148    /// let union = &a | b;  // Alternatively, 'a | b', etc.
2149    /// assert_eq!(union, RangeSetBlaze::from_iter([0..=5, 10..=10]));
2150    /// ```
2151    fn bitor(self, mut other: RangeSetBlaze<T>) -> RangeSetBlaze<T> {
2152        other |= self;
2153        other
2154    }
2155}
2156
2157impl<T: Integer> BitOr<&RangeSetBlaze<T>> for &RangeSetBlaze<T> {
2158    type Output = RangeSetBlaze<T>;
2159    /// Unions the contents of two [`RangeSetBlaze`]'s.
2160    ///
2161    /// Passing ownership rather than borrow sometimes allows a many-times
2162    /// faster speed up.
2163    ///
2164    /// Also see [`a |= b`](RangeSetBlaze::bitor_assign).
2165    ///
2166    /// # Examples
2167    /// ```
2168    /// use range_set_blaze::RangeSetBlaze;
2169    /// let a = RangeSetBlaze::from_iter([1..=4]);
2170    /// let b = RangeSetBlaze::from_iter([0..=0, 3..=5, 10..=10]);
2171    /// let union = &a | &b;  // Alternatively, 'a | b', etc.
2172    /// assert_eq!(union, RangeSetBlaze::from_iter([0..=5, 10..=10]));
2173    /// ```
2174    fn bitor(self, other: &RangeSetBlaze<T>) -> RangeSetBlaze<T> {
2175        if other.ranges_len() == 0 {
2176            return self.clone();
2177        }
2178        if self.ranges_len() == 0 {
2179            return other.clone();
2180        }
2181        (self.ranges() | other.ranges()).into_range_set_blaze()
2182    }
2183}
2184
2185impl<T: Integer> Extend<RangeInclusive<T>> for RangeSetBlaze<T> {
2186    /// Extends the [`RangeSetBlaze`] with the contents of a
2187    /// range iterator.
2188    ///
2189    /// Elements are added one-by-one. There is also a version
2190    /// that takes an integer iterator.
2191    ///
2192    /// The [`|=`](RangeSetBlaze::bitor_assign) operator extends a [`RangeSetBlaze`]
2193    /// from another [`RangeSetBlaze`]. It is never slower
2194    ///  than  [`RangeSetBlaze::extend`] and often several times faster.
2195    ///
2196    /// # Examples
2197    /// ```
2198    /// use range_set_blaze::RangeSetBlaze;
2199    /// let mut a = RangeSetBlaze::from_iter([1..=4]);
2200    /// a.extend([5..=5, 0..=0, 0..=0, 3..=4, 10..=10]);
2201    /// assert_eq!(a, RangeSetBlaze::from_iter([0..=5, 10..=10]));
2202    ///
2203    /// let mut a = RangeSetBlaze::from_iter([1..=4]);
2204    /// let b = RangeSetBlaze::from_iter([5..=5, 0..=0, 0..=0, 3..=4, 10..=10]);
2205    /// a |= b;
2206    /// assert_eq!(a, RangeSetBlaze::from_iter([0..=5, 10..=10]));
2207    /// ```
2208    #[inline]
2209    fn extend<I>(&mut self, iter: I)
2210    where
2211        I: IntoIterator<Item = RangeInclusive<T>>,
2212    {
2213        let iter = iter.into_iter();
2214        let iter = UnsortedDisjoint::new(iter);
2215        for range in iter {
2216            self.internal_add(range);
2217        }
2218    }
2219}
2220
2221impl<T: Integer> Ord for RangeSetBlaze<T> {
2222    /// We define a total ordering on `RangeSetBlaze`. Following the convention of
2223    /// [`BTreeSet`], the ordering is lexicographic, *not* by subset/superset.
2224    ///
2225    /// [`BTreeSet`]: alloc::collections::BTreeSet
2226    ///
2227    /// # Examples
2228    /// ```
2229    /// use range_set_blaze::RangeSetBlaze;
2230    ///
2231    /// let a = RangeSetBlaze::from_iter([1..=3, 5..=7]);
2232    /// let b = RangeSetBlaze::from_iter([2..=2]);
2233    /// assert!(a < b); // Lexicographic comparison
2234    /// assert!(b.is_subset(&a)); // Subset comparison
2235    /// // More lexicographic comparisons
2236    /// assert!(a <= b);
2237    /// assert!(b > a);
2238    /// assert!(b >= a);
2239    /// assert!(a != b);
2240    /// assert!(a == a);
2241    /// use core::cmp::Ordering;
2242    /// assert_eq!(a.cmp(&b), Ordering::Less);
2243    /// assert_eq!(a.partial_cmp(&b), Some(Ordering::Less));
2244    /// ```
2245    #[inline]
2246    fn cmp(&self, other: &Self) -> Ordering {
2247        // slow one by one: return self.iter().cmp(other.iter());
2248
2249        // fast by ranges:
2250        let mut a = self.ranges();
2251        let mut b = other.ranges();
2252        let mut a_rx = a.next();
2253        let mut b_rx = b.next();
2254        loop {
2255            match (a_rx, b_rx) {
2256                (Some(a_r), Some(b_r)) => {
2257                    let cmp_start = a_r.start().cmp(b_r.start());
2258                    if cmp_start != Ordering::Equal {
2259                        return cmp_start;
2260                    }
2261                    let cmp_end = a_r.end().cmp(b_r.end());
2262                    match cmp_end {
2263                        Ordering::Equal => {
2264                            a_rx = a.next();
2265                            b_rx = b.next();
2266                        }
2267                        Ordering::Less => {
2268                            a_rx = a.next();
2269                            b_rx = Some((*a_r.end()).add_one()..=*b_r.end());
2270                        }
2271                        Ordering::Greater => {
2272                            a_rx = Some((*b_r.end()).add_one()..=*a_r.end());
2273                            b_rx = b.next();
2274                        }
2275                    }
2276                }
2277                (Some(_), None) => return Ordering::Greater,
2278                (None, Some(_)) => return Ordering::Less,
2279                (None, None) => return Ordering::Equal,
2280            }
2281        }
2282    }
2283}
2284
2285impl<T: Integer> PartialOrd for RangeSetBlaze<T> {
2286    #[inline]
2287    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
2288        Some(self.cmp(other))
2289    }
2290}
2291
2292impl<T: Integer> Eq for RangeSetBlaze<T> {}
2293
2294/// Extracts the start and end of a range from a `RangeBounds`.
2295///
2296/// Empty ranges are allowed.
2297#[allow(clippy::redundant_pub_crate)]
2298#[inline]
2299pub(crate) fn extract_range<T: Integer, R>(range: R) -> (T, T)
2300where
2301    R: RangeBounds<T>,
2302{
2303    let start = match range.start_bound() {
2304        Bound::Included(n) => *n,
2305        Bound::Excluded(n) => {
2306            assert!(
2307                *n < T::max_value(),
2308                "inclusive start must be <= T::max_safe_value()"
2309            );
2310            n.add_one()
2311        }
2312        Bound::Unbounded => T::min_value(),
2313    };
2314    let end = match range.end_bound() {
2315        Bound::Included(n) => *n,
2316        Bound::Excluded(n) => {
2317            assert!(
2318                *n > T::min_value(),
2319                "inclusive end must be >= T::min_value()"
2320            );
2321            n.sub_one()
2322        }
2323        Bound::Unbounded => T::max_value(),
2324    };
2325    (start, end)
2326}