range_set_blaze/
lib.rs

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