Skip to main content

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