range_set_blaze/
set.rs

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