range_set_blaze/
map.rs

1use crate::{
2    CheckSortedDisjoint, Integer, IntoKeys, Keys, RangeSetBlaze, SortedDisjoint,
3    iter_map::{IntoIterMap, IterMap},
4    map_op, map_unary_op,
5    range_values::{IntoRangeValuesIter, MapIntoRangesIter, MapRangesIter, RangeValuesIter},
6    set::extract_range,
7    sorted_disjoint_map::{IntoString, SortedDisjointMap},
8    sym_diff_iter_map::SymDiffIterMap,
9    unsorted_priority_map::{SortedDisjointMapWithLenSoFar, UnsortedPriorityMap},
10    values::{IntoValues, Values},
11};
12#[cfg(feature = "std")]
13use alloc::sync::Arc;
14use alloc::vec::Vec;
15use alloc::{collections::BTreeMap, rc::Rc};
16use core::{
17    borrow::Borrow,
18    cmp::{Ordering, max},
19    convert::From,
20    fmt, mem,
21    ops::{BitOr, BitOrAssign, Index, RangeBounds, RangeInclusive},
22    panic,
23};
24use num_traits::{One, Zero};
25
26const STREAM_OVERHEAD: usize = 10;
27
28/// A trait for references to `Eq + Clone` values, used by the [`SortedDisjointMap`] trait.
29///
30/// `ValueRef` enables [`SortedDisjointMap`] to map sorted, disjoint ranges of integers
31/// to values of type `V: Eq + Clone`. It supports both references (`&V`) and shared ownership types
32/// (`Rc<V>` and `Arc<V>`), avoiding unnecessary cloning of the underlying values while allowing
33/// ownership when needed.
34///
35/// References must also implement `Clone`. Standard reference types like `&V`, `Rc<V>`, and `Arc<V>`
36/// implement `Clone` efficiently, as cloning typically involves copying a pointer.
37///
38/// # Motivation
39///
40/// Iterating over `(range, value)` pairs, such as with [`RangeMapBlaze::ranges`], benefits from
41/// references to values, which are cheap to clone. However, iterators like [`RangeMapBlaze::into_ranges`]
42/// require ownership. By supporting `Rc<Eq + Clone>` and `Arc<Eq + Clone>`, `ValueRef` allows shared ownership,
43/// freeing memory when the reference count drops to zero.
44///
45// # Examples
46///
47/// The following demonstrates the [`SortedDisjointMap::intersection`] operation working with
48/// iterators of both `(RangeInclusive<Integer>, &Eq + Clone)` and `(RangeInclusive<Integer>, Rc<Eq + Clone>)`.
49/// (However, types cannot be mixed in the same operation due to Rust's strong type system.)
50///
51/// ```rust
52/// use range_set_blaze::prelude::*;
53/// use std::rc::Rc;
54///
55/// let a = RangeMapBlaze::from_iter([(3..=10, "a".to_string())]);
56/// let b = RangeMapBlaze::from_iter([(2..=3, "b".to_string()), (5..=100, "b".to_string())]);
57///
58/// let mut c = a.range_values() & b.range_values();
59/// assert_eq!(c.next(), Some((3..=3, &"b".to_string())));
60/// assert_eq!(c.next(), Some((5..=10, &"b".to_string())));
61/// assert_eq!(c.next(), None);
62///
63/// let mut c = a.into_range_values() & b.into_range_values();
64/// assert_eq!(c.next(), Some((3..=3, Rc::new("b".to_string()))));
65/// assert_eq!(c.next(), Some((5..=10, Rc::new("b".to_string()))));
66/// assert_eq!(c.next(), None);
67/// ```
68pub trait ValueRef: Borrow<Self::Target> + Clone {
69    /// The `Eq + Clone` value type to which the reference points.
70    type Target: Eq + Clone;
71
72    /// Converts a reference or shared pointer to an owned value of type `Self::Target`.
73    ///
74    /// This method allows values of type `Self` (e.g., `&V`, `Rc<V>`, or `Arc<V>`) to be turned
75    /// into a fully owned `V`, which is required when consuming or storing values independently.
76    ///
77    /// - For plain references (`&V`), this clones the referenced value.
78    /// - For `Rc<V>` and `Arc<V>`, this attempts to unwrap the value if uniquely owned;
79    ///   otherwise, it clones the inner value.
80    ///
81    /// This method is typically used when converting a stream of `(range, value)` pairs
82    /// into owned data, such as when building a new `RangeMapBlaze` from an iterator.
83    ///
84    /// # Example
85    /// ```
86    /// use std::rc::Rc;
87    /// use range_set_blaze::ValueRef;
88    ///
89    /// let rc = Rc::new("hello".to_string());
90    /// let owned: String = rc.to_owned(); // avoids cloning if ref count is 1
91    /// ```
92    fn to_owned(self) -> Self::Target;
93}
94
95// Implementations for references and smart pointers
96impl<V> ValueRef for &V
97where
98    V: Eq + Clone,
99{
100    type Target = V;
101
102    #[inline]
103    fn to_owned(self) -> Self::Target {
104        self.clone()
105    }
106}
107
108impl<V> ValueRef for Rc<V>
109where
110    V: Eq + Clone,
111{
112    type Target = V;
113
114    #[inline]
115    fn to_owned(self) -> Self::Target {
116        Self::try_unwrap(self).unwrap_or_else(|rc| (*rc).clone())
117    }
118}
119
120#[cfg(feature = "std")]
121impl<V> ValueRef for Arc<V>
122where
123    V: Eq + Clone,
124{
125    type Target = V;
126
127    #[inline]
128    fn to_owned(self) -> Self::Target {
129        Self::try_unwrap(self).unwrap_or_else(|arc| (*arc).clone())
130    }
131}
132
133#[expect(clippy::redundant_pub_crate)]
134#[derive(Clone, Hash, Default, PartialEq, Eq, Debug)]
135pub(crate) struct EndValue<T, V>
136where
137    T: Integer,
138    V: Eq + Clone,
139{
140    pub(crate) end: T,
141    pub(crate) value: V,
142}
143
144/// A map from integers to values stored as a map of sorted & disjoint ranges to values.
145///
146/// Internally, the map stores the
147/// ranges and values in a cache-efficient [`BTreeMap`].
148///
149/// # Table of Contents
150/// * [`RangeMapBlaze` Constructors](#rangemapblaze-constructors)
151///    * [Performance](#constructor-performance)
152///    * [Examples](struct.RangeMapBlaze.html#constructor-examples)
153/// * [`RangeMapBlaze` Set Operations](#rangemapblaze-set-operations)
154///    * [Performance](struct.RangeMapBlaze.html#set-operation-performance)
155///    * [Examples](struct.RangeMapBlaze.html#set-operation-examples)
156/// * [`RangeMapBlaze` Union- and Extend-like Methods](#rangemapblaze-union--and-extend-like-methods)
157/// * [`RangeMapBlaze` Comparisons](#rangemapblaze-comparisons)
158/// * [Additional Examples](#additional-examples)
159///
160/// # `RangeMapBlaze` Constructors
161///
162/// You can create `RangeMapBlaze`'s from unsorted and overlapping integers (or ranges), along with values.
163/// However, if you know that your input is sorted and disjoint, you can speed up construction.
164///
165/// Here are the constructors, followed by a
166/// description of the performance, and then some examples.
167///
168///
169/// | Methods                                     | Input                        | Notes                    |
170/// |---------------------------------------------|------------------------------|--------------------------|
171/// | [`new`]/[`default`]                         |                              |                          |
172/// | [`from_iter`][1]/[`collect`][1]           | iterator of `(integer, value)` | References to the pair or value is OK. |
173/// | [`from_iter`][2]/[`collect`][2]           | iterator of `(range, value)`   | References to the pair or value is OK. |
174/// | [`from_sorted_disjoint_map`][3]/<br>[`into_range_set_blaze`][3b] | [`SortedDisjointMap`] iterator |               |
175/// | [`from`][4] /[`into`][4]                    | array of `(integer, value)`  |                          |
176///
177///
178/// [`BTreeMap`]: alloc::collections::BTreeMap
179/// [`new`]: RangeMapBlaze::new
180/// [`default`]: RangeMapBlaze::default
181/// [1]: struct.RangeMapBlaze.html#impl-FromIterator<(T,+V)>-for-RangeMapBlaze<T,+V>
182/// [2]: struct.RangeMapBlaze.html#impl-FromIterator<(RangeInclusive<T>,+V)>-for-RangeMapBlaze<T,+V>
183/// [3]: `RangeMapBlaze::from_sorted_disjoint_map`
184/// [3b]: `SortedDisjointMap::into_range_map_blaze
185/// [`SortedDisjointMap`]: trait.SortedDisjointMap.html#table-of-contents
186/// [4]: `RangeMapBlaze::from`
187///
188/// # Constructor Performance
189///
190/// The [`from_iter`][1]/[`collect`][1] constructors are designed to work fast on 'clumpy' data.
191/// By 'clumpy', we mean that the number of ranges needed to represent the data is
192/// small compared to the number of input integers. To understand this, consider the internals
193/// of the constructors:
194///
195///  Internally, the `from_iter`/`collect` constructors take these steps:
196/// * collect adjacent integers/ranges with equal values into disjoint ranges, O(*n₁*)
197/// * sort the disjoint ranges by their `start`, O(*n₂* ln *n₂*)
198/// * merge ranges giving precedence to the originally right-most values, O(*n₂*)
199/// * create a `BTreeMap` from the now sorted & disjoint ranges, O(*n₃* ln *n₃*)
200///
201/// where *n₁* is the number of input integers/ranges, *n₂* is the number of disjoint & unsorted ranges,
202/// and *n₃* is the final number of sorted & disjoint ranges with equal values.
203///
204/// For example, an input of
205///  * `(3, "a"), (2, "a"), (1, "a"), (4, "a"), (100, "c"), (5, "b"), (4, "b"), (5, "b")`, becomes
206///  * `(1..=4, "a"), (100..=100, "c"), (4..=5, "b")`, and then
207///  * `(1..=4, "a"), (4..=5, "b"), (100..=100, "c")`, and finally
208///  * `(1..=4, "a"), (5..=5, "b"), (100..=100, "c")`.
209///
210/// What is the effect of clumpy data?
211/// Notice that if *n₂* ≈ sqrt(*n₁*), then construction is O(*n₁*).
212/// Indeed, as long as *n₂* ≤ *n₁*/ln(*n₁*), then construction is O(*n₁*).
213/// Moreover, we'll see that set operations are O(*n₃*). Thus, if *n₃* ≈ sqrt(*n₁*) then set operations are O(sqrt(*n₁*)),
214/// a quadratic improvement an O(*n₁*) implementation that ignores the clumps.
215///
216/// ## Constructor Examples
217///
218/// ```
219/// use range_set_blaze::prelude::*;
220///
221/// // Create an empty set with 'new' or 'default'.
222/// let a0 = RangeMapBlaze::<i32, &str>::new();
223/// let a1 = RangeMapBlaze::<i32, &str>::default();
224/// assert!(a0 == a1 && a0.is_empty());
225///
226/// // 'from_iter'/'collect': From an iterator of integers.
227/// // Duplicates and out-of-order elements are fine.
228/// // Values have right-to-left precedence.
229/// let a0 = RangeMapBlaze::from_iter([(100, "b"), (1, "c"),(3, "a"), (2, "a"), (1, "a")]);
230/// let a1: RangeMapBlaze<i32, &str> = [(100, "b"), (1, "c"), (3, "a"), (2, "a"), (1, "a")].into_iter().collect();
231/// assert!(a0 == a1 && a0.to_string() == r#"(1..=3, "a"), (100..=100, "b")"#);
232///
233/// // 'from_iter'/'collect': From an iterator of inclusive ranges, start..=end.
234/// // Overlapping, out-of-order, and empty ranges are fine.
235/// // Values have right-to-left precedence.
236/// #[allow(clippy::reversed_empty_ranges)]
237/// let a0 = RangeMapBlaze::from_iter([(2..=2, "b"), (1..=2, "a"), (-10..=-5, "c"), (1..=0, "d")]);
238/// #[allow(clippy::reversed_empty_ranges)]
239/// let a1: RangeMapBlaze<i32, &str> = [(2..=2, "b"), (1..=2, "a"), (-10..=-5, "c"), (1..=0, "d")].into_iter().collect();
240/// assert!(a0 == a1 && a0.to_string() == r#"(-10..=-5, "c"), (1..=2, "a")"#);
241///
242/// // If we know the ranges are already sorted and disjoint,
243/// // we can avoid work and use 'from_sorted_disjoint_map'/'into_sorted_disjoint_map'.
244/// let a0 = RangeMapBlaze::from_sorted_disjoint_map(CheckSortedDisjointMap::new([(-10..=-5, &"c"), (1..=2, &"a")]));
245/// let a1: RangeMapBlaze<i32, &str> = CheckSortedDisjointMap::new([(-10..=-5, &"c"), (1..=2, &"a")]).into_range_map_blaze();
246/// assert_eq!(a0, a1);
247/// assert_eq!(a0.to_string(),r#"(-10..=-5, "c"), (1..=2, "a")"#);
248///
249/// // For compatibility with `BTreeMap`, we also support
250/// // 'from'/'into' from arrays of integers.
251/// let a0 = RangeMapBlaze::from([(100, "b"), (1, "c"),(3, "a"), (2, "a"), (1, "a")]);
252/// let a1: RangeMapBlaze<i32, &str> = [(100, "b"), (1, "c"),(3, "a"), (2, "a"), (1, "a")].into();
253/// assert_eq!(a0, a1);
254/// assert_eq!(a0.to_string(), r#"(1..=3, "a"), (100..=100, "b")"#);
255/// ```
256///
257/// # `RangeMapBlaze` Set Operations
258///
259/// You can perform set operations on `RangeMapBlaze`s
260/// and `RangeSetBlaze`s using operators. In the table below, `a`, `b`, and `c` are `RangeMapBlaze`s and `s` is a `RangeSetBlaze`.
261///
262/// | Set Operation           | Operator                           | Multiway Method                        |
263/// |--------------------------|------------------------------------|----------------------------------------|
264/// | union                    | [`a` &#124; `b`]                   | `[a, b, c]`.[`union`]\(\)              |
265/// | intersection             | [`a & b`]                          | `[a, b, c]`.[`intersection`]\(\)              |
266/// | intersection             | [`a & s`]                          | *n/a*                                  |
267/// | difference               | [`a - b`]                          | *n/a*                                  |
268/// | difference               | [`a - s`]                          | *n/a*                                  |
269/// | symmetric difference     | [`a ^ b`]                          | `[a, b, c]`.[`symmetric_difference`]\(\) |
270/// | complement (to set)      | [`!a`]                             | *n/a*                                  |
271/// | complement (to map)      | [`a.complement_with(&value)`]      | *n/a*                                  |
272///
273/// The result of all operations is a new `RangeMapBlaze` except for `!a`, which returns a `RangeSetBlaze`.
274///
275/// The union of any number of maps is defined such that, for any overlapping keys,
276/// the values from the right-most input take precedence. This approach ensures
277/// that the data from the right-most inputs remains dominant when merging with
278/// later inputs. Likewise, for symmetric difference of three or more maps.
279///
280/// `RangeMapBlaze` also implements many other methods, such as [`insert`], [`pop_first`] and [`split_off`]. Many of
281/// these methods match those of `BTreeMap`.
282///
283/// [`a` &#124; `b`]: struct.RangeMapBlaze.html#impl-BitOr-for-RangeMapBlaze<T,+V>
284/// [`a & b`]: struct.RangeMapBlaze.html#impl-BitAnd-for-RangeMapBlaze<T,+V>
285/// [`a & s`]: struct.RangeMapBlaze.html#impl-BitAnd<%26RangeSetBlaze<T>>-for-%26RangeMapBlaze<T,+V>
286/// [`a - b`]: struct.RangeMapBlaze.html#impl-Sub-for-RangeMapBlaze<T,+V>
287/// [`a - s`]: struct.RangeMapBlaze.html#impl-Sub<%26RangeSetBlaze<T>>-for-%26RangeMapBlaze<T,+V>
288/// [`a ^ b`]: struct.RangeMapBlaze.html#impl-BitXor-for-RangeMapBlaze<T,+V>
289/// [`!a`]: struct.RangeMapBlaze.html#impl-Not-for-%26RangeMapBlaze<T,+V>
290/// [`a.complement_with(&value)`]: struct.RangeMapBlaze.html#method.complement_with
291/// [`union`]: trait.MultiwayRangeMapBlazeRef.html#method.union
292/// [`intersection`]: trait.MultiwayRangeMapBlazeRef.html#method.intersection
293/// [`symmetric_difference`]: trait.MultiwayRangeMapBlazeRef.html#method.symmetric_difference
294/// [`insert`]: RangeMapBlaze::insert
295/// [`pop_first`]: RangeMapBlaze::pop_first
296/// [`split_off`]: RangeMapBlaze::split_off
297///
298/// ## Set Operation Performance
299///
300/// Every operation is implemented as
301/// 1. a single pass over the sorted & disjoint ranges
302/// 2. the construction of a new `RangeMapBlaze`
303///
304/// Thus, applying multiple operators creates intermediate
305/// `RangeMapBlaze`'s. If you wish, you can avoid these intermediate
306/// `RangeMapBlaze`'s by switching to the [`SortedDisjointMap`] API. The last example below
307/// demonstrates this.
308///
309/// Several union-related operators — such as [`|`] (union) and [`|=`] (union append) — include performance
310/// optimizations for common cases, including when one operand is much smaller than the other.
311/// These optimizations reduce allocations and merging overhead.
312/// **See:** [Summary of Union and Extend-like Methods](#rangemapblaze-union--and-extend-like-methods).
313///
314/// [`SortedDisjointMap`]: trait.SortedDisjointMap.html#table-of-contents
315/// [`|`]: struct.RangeMapBlaze.html#impl-BitOr-for-RangeMapBlaze%3CT,+V%3E
316/// [`|=`]: struct.RangeMapBlaze.html#impl-BitOrAssign-for-RangeMapBlaze%3CT,+V%3E
317///
318/// ## Set Operation Examples
319///
320/// ```
321/// use range_set_blaze::prelude::*;
322///
323/// let a = RangeMapBlaze::from_iter([(2..=6, "a")]);
324/// let b = RangeMapBlaze::from_iter([(1..=2, "b"), (5..=100, "b")]);
325///
326/// // Union of two 'RangeMapBlaze's. Alternatively, we can take ownership via 'a | b'.
327/// // Values have right-to-left precedence.
328/// let result = &a | &b;
329/// assert_eq!(result.to_string(), r#"(1..=2, "b"), (3..=4, "a"), (5..=100, "b")"#);
330///
331/// // Intersection of two 'RangeMapBlaze's.
332/// let result = &a & &b; // Alternatively, 'a & b'.
333/// assert_eq!(result.to_string(), r#"(2..=2, "b"), (5..=6, "b")"#);
334///
335/// // Set difference of two 'RangeMapBlaze's.
336/// let result = &a - &b; // Alternatively, 'a - b'.
337/// assert_eq!(result.to_string(), r#"(3..=4, "a")"#);
338///
339/// // Symmetric difference of two 'RangeMapBlaze's.
340/// let result = &a ^ &b; // Alternatively, 'a ^ b'.
341/// assert_eq!(result.to_string(), r#"(1..=1, "b"), (3..=4, "a"), (7..=100, "b")"#);
342///
343/// // complement of a 'RangeMapBlaze' is a `RangeSetBlaze`.
344/// let result = !&b; // Alternatively, '!b'.
345/// assert_eq!(result.to_string(), "-2147483648..=0, 3..=4, 101..=2147483647"
346/// );
347/// // use `complement_with` to create a 'RangeMapBlaze'.
348/// let result = b.complement_with(&"z");
349/// assert_eq!(result.to_string(), r#"(-2147483648..=0, "z"), (3..=4, "z"), (101..=2147483647, "z")"#);
350///
351/// // Multiway union of 'RangeMapBlaze's.
352/// let z = RangeMapBlaze::from_iter([(2..=2, "z"), (6..=200, "z")]);
353/// let result = [&z, &a, &b].union();
354/// assert_eq!(result.to_string(), r#"(1..=2, "b"), (3..=4, "a"), (5..=100, "b"), (101..=200, "z")"# );
355///
356/// // Multiway intersection of 'RangeMapBlaze's.
357/// let result = [&z, &a, &b].intersection();
358/// assert_eq!(result.to_string(), r#"(2..=2, "b"), (6..=6, "b")"#);
359///
360/// // Applying multiple operators
361/// let result0 = &b - (&z | &a); // Creates an intermediate 'RangeMapBlaze'.
362/// // Alternatively, we can use the 'SortedDisjointMap' API and avoid the intermediate 'RangeMapBlaze'.
363/// let result1 = RangeMapBlaze::from_sorted_disjoint_map(
364///          b.range_values() - (a.range_values() | z.range_values()));
365/// assert_eq!(result0, result1);
366/// assert_eq!(result0.to_string(), r#"(1..=1, "b")"#);
367/// ```
368///
369/// # `RangeMapBlaze` Union- and Extend-like Methods
370///
371/// | Operation & Syntax                  | Input Type           | Pre-merge Touching | Cases Optimized |
372/// |-------------------------------------|----------------------|---------------------|------------------|
373/// | [`a` &#124;= `b`]                   | `RangeMapBlaze`      | -                   | 3                |
374/// | [`a` &#124;= `&b`]                  | `&RangeMapBlaze`     | -                   | 3                |
375/// | [`a` &#124; `b`]                    | `RangeMapBlaze`      | -                   | 3                |
376/// | [`a` &#124; `&b`]                   | `&RangeMapBlaze`     | -                   | 3                |
377/// | [`&a` &#124; `b`]                   | `RangeMapBlaze`      | -                   | 3                |
378/// | [`&a` &#124; `&b`]                  | `&RangeMapBlaze`     | -                   | 3                |
379/// | [`a.extend([(r, v)])`][extend_rv]   | iter `(range, value)`     | Yes                 | 1                |
380/// | [`a.extend([(i, v)])`][extend_iv]   | iter `(integer, value)`   | Yes                 | 1                |
381/// | [`a.extend_simple(...)`][extend_simple] | iter `(range, value)` | No                  | 1                |
382/// | [`a.extend_with(&b)`][extend_with]  | `&RangeMapBlaze`     | -                   | 1                |
383/// | [`a.extend_from(b)`][extend_from]   | `RangeMapBlaze`      | -                   | 1                |
384/// | [`b.append(&mut a)`][append]        | `&mut RangeMapBlaze` | -                   | 1                |
385///
386/// Notes:
387///
388/// - **Pre-merge Touching** means adjacent or overlapping ranges with the same value are combined into a single range before insertions.
389/// - **Cases Optimized** indicates how many usage scenarios have dedicated performance paths:
390///     - `3` = optimized for small-left, small-right, and similar-sized inputs
391///     - `1` = optimized for small-right inputs only
392///
393/// [`a` &#124;= `b`]: struct.RangeMapBlaze.html#impl-BitOrAssign-for-RangeMapBlaze%3CT,+V%3E
394/// [`a` &#124;= `&b`]: struct.RangeMapBlaze.html#impl-BitOrAssign%3C%26RangeMapBlaze%3CT,+V%3E%3E-for-RangeMapBlaze%3CT,+V%3E
395/// [`a` &#124; `b`]: struct.RangeMapBlaze.html#impl-BitOr-for-RangeMapBlaze%3CT,+V%3E
396/// [`a` &#124; `&b`]: struct.RangeMapBlaze.html#impl-BitOr%3C%26RangeMapBlaze%3CT,+V%3E%3E-for-RangeMapBlaze%3CT,+V%3E
397/// [`&a` &#124; `b`]: struct.RangeMapBlaze.html#impl-BitOr%3CRangeMapBlaze%3CT,+V%3E%3E-for-%26RangeMapBlaze%3CT,+V%3E
398/// [`&a` &#124; `&b`]: struct.RangeMapBlaze.html#impl-BitOr%3C%26RangeMapBlaze%3CT,+V%3E%3E-for-%26RangeMapBlaze%3CT,+V%3E
399/// [extend_rv]: struct.RangeMapBlaze.html#impl-Extend%3C(RangeInclusive%3CT%3E,+V)%3E-for-RangeMapBlaze%3CT,+V%3E
400/// [extend_iv]: struct.RangeMapBlaze.html#impl-Extend%3C(T,+V)%3E-for-RangeMapBlaze%3CT,+V%3E
401/// [extend_simple]: struct.RangeMapBlaze.html#method.extend_simple
402/// [extend_with]: struct.RangeMapBlaze.html#method.extend_with
403/// [extend_from]: struct.RangeMapBlaze.html#method.extend_from
404/// [append]: struct.RangeMapBlaze.html#method.append
405///
406/// # `RangeMapBlaze` Comparisons
407///
408/// `RangeMapBlaze` supports comparisons for equality and lexicographic order:
409///
410/// - **Equality**: Use `==` and `!=` to check if two `RangeMapBlaze` instances
411///   are equal. Two `RangeMapBlaze` instances are considered equal if they
412///   contain the same ranges and associated values.
413/// - **Ordering**: If the values implement `Ord`, you can use `<`, `<=`, `>`, and `>=`
414///   to compare two `RangeMapBlaze` instances. These comparisons are lexicographic,
415///   similar to `BTreeMap`, meaning they compare the ranges and their values in sequence.
416/// - **Partial Ordering**: If the values implement `PartialOrd` but not `Ord`, you can use
417///   the [`partial_cmp`] method to compare two `RangeMapBlaze` instances. This method returns
418///   an `Option<Ordering>` that indicates the relative order of the instances or `None` if the
419///   values are not comparable.
420///
421/// See [`partial_cmp`] and [`cmp`] for more examples.
422///
423///
424/// [`BTreeMap`]: alloc::collections::BTreeMap
425/// [`partial_cmp`]: RangeMapBlaze::partial_cmp
426/// [`cmp`]: RangeMapBlaze::cmp
427///
428/// # Additional Examples
429///
430/// See the [module-level documentation] for additional examples.
431///
432/// [module-level documentation]: index.html
433#[derive(Clone, Hash, PartialEq)]
434pub struct RangeMapBlaze<T: Integer, V: Eq + Clone> {
435    pub(crate) len: <T as Integer>::SafeLen,
436    pub(crate) btree_map: BTreeMap<T, EndValue<T, V>>,
437}
438
439/// Creates a new, empty `RangeMapBlaze`.
440///
441/// # Examples
442///
443/// ```
444/// use range_set_blaze::RangeMapBlaze;
445///
446/// let a = RangeMapBlaze::<i32, &str>::default();
447/// assert!(a.is_empty());
448/// ```
449impl<T: Integer, V: Eq + Clone> Default for RangeMapBlaze<T, V> {
450    fn default() -> Self {
451        Self {
452            len: <T as Integer>::SafeLen::zero(),
453            btree_map: BTreeMap::new(),
454        }
455    }
456}
457
458impl<T: Integer, V: Eq + Clone + fmt::Debug> fmt::Debug for RangeMapBlaze<T, V> {
459    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
460        write!(f, "{}", self.range_values().into_string())
461    }
462}
463
464impl<T: Integer, V: Eq + Clone + fmt::Debug> fmt::Display for RangeMapBlaze<T, V> {
465    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
466        write!(f, "{}", self.range_values().into_string())
467    }
468}
469
470impl<T: Integer, V: Eq + Clone> RangeMapBlaze<T, V> {
471    /// Gets an iterator that visits the integer elements in the [`RangeMapBlaze`] in
472    /// ascending and/or descending order. Double-ended.
473    ///
474    /// Also see the [`RangeMapBlaze::ranges`] method.
475    ///
476    /// # Examples
477    ///
478    /// ```
479    /// use range_set_blaze::RangeMapBlaze;
480    ///
481    /// let map = RangeMapBlaze::from_iter([(1..=3,"a")]);
482    /// let mut map_iter = map.iter();
483    /// assert_eq!(map_iter.next(), Some((1, &"a")));
484    /// assert_eq!(map_iter.next(), Some((2, &"a")));
485    /// assert_eq!(map_iter.next(), Some((3, &"a")));
486    /// assert_eq!(map_iter.next(), None);
487    /// ```
488    ///
489    /// Values returned by `.next()` are in ascending order.
490    /// Values returned by `.next_back()` are in descending order.
491    ///
492    /// ```
493    /// use range_set_blaze::RangeMapBlaze;
494    ///
495    /// let map = RangeMapBlaze::from_iter([(3,"c"), (1,"a"), (2,"b")]);
496    /// let mut map_iter = map.iter();
497    /// assert_eq!(map_iter.next(), Some((1, &"a")));
498    /// assert_eq!(map_iter.next_back(), Some((3, &"c")));
499    /// assert_eq!(map_iter.next(), Some((2, &"b")));
500    /// assert_eq!(map_iter.next_back(), None);
501    /// ```
502    pub fn iter(&self) -> IterMap<T, &V, RangeValuesIter<'_, T, V>> {
503        // If the user asks for an iter, we give them a RangesIter iterator
504        // and we iterate that one integer at a time.
505        IterMap::new(self.range_values())
506    }
507
508    /// Gets an iterator that visits the integer elements in the [`RangeMapBlaze`] in
509    /// ascending and/or descending order. Double-ended.
510    ///
511    /// For a consuming version, see the [`RangeMapBlaze::into_keys`] method.
512    ///
513    /// # Examples
514    ///
515    /// ```
516    /// use range_set_blaze::RangeMapBlaze;
517    ///
518    /// let map = RangeMapBlaze::from_iter([(1..=3,"a")]);
519    /// let mut keys_iter = map.keys();
520    /// assert_eq!(keys_iter.next(), Some(1));
521    /// assert_eq!(keys_iter.next(), Some(2));
522    /// assert_eq!(keys_iter.next(), Some(3));
523    /// assert_eq!(keys_iter.next(), None);
524    /// ```
525    ///
526    /// Keys returned by `.next()` are in ascending order.
527    /// Keys returned by `.next_back()` are in descending order.
528    ///
529    /// ```
530    /// # use range_set_blaze::RangeMapBlaze;
531    /// let map = RangeMapBlaze::from_iter([(3,"c"), (1,"a"), (2,"b")]);
532    /// let mut keys_iter = map.keys();
533    /// assert_eq!(keys_iter.next(), Some(1));
534    /// assert_eq!(keys_iter.next_back(), Some(3));
535    /// assert_eq!(keys_iter.next(), Some(2));
536    /// assert_eq!(keys_iter.next_back(), None);
537    /// ```
538    pub fn keys(&self) -> Keys<T, &V, RangeValuesIter<'_, T, V>> {
539        Keys::new(self.range_values())
540    }
541
542    /// Gets an iterator that visits the integer elements in the [`RangeMapBlaze`] in
543    /// ascending and/or descending order. Double-ended.
544    ///
545    /// The iterator consumes the [`RangeMapBlaze`], yielding one integer at a time from its ranges.
546    /// For a non-consuming version, see the [`RangeMapBlaze::keys`] method.
547    ///
548    /// # Examples
549    ///
550    /// Iterating in ascending order:
551    ///
552    /// ```
553    /// use range_set_blaze::RangeMapBlaze;
554    ///
555    /// let map = RangeMapBlaze::from_iter([(1..=3, "a")]);
556    /// let mut into_keys_iter = map.into_keys();
557    /// assert_eq!(into_keys_iter.next(), Some(1));
558    /// assert_eq!(into_keys_iter.next(), Some(2));
559    /// assert_eq!(into_keys_iter.next(), Some(3));
560    /// assert_eq!(into_keys_iter.next(), None);
561    /// ```
562    ///
563    /// Iterating in both ascending and descending order:
564    ///
565    /// ```
566    /// # use range_set_blaze::RangeMapBlaze;
567    /// let map = RangeMapBlaze::from_iter([(1..=3, "a"), (5..=5, "b")]);
568    /// let mut into_keys_iter = map.into_keys();
569    /// assert_eq!(into_keys_iter.next(), Some(1));
570    /// assert_eq!(into_keys_iter.next_back(), Some(5));
571    /// assert_eq!(into_keys_iter.next(), Some(2));
572    /// assert_eq!(into_keys_iter.next_back(), Some(3));
573    /// assert_eq!(into_keys_iter.next(), None);
574    /// ```
575    ///
576    /// Keys returned by `.next()` are in ascending order.
577    /// Keys returned by `.next_back()` are in descending order.
578    #[inline]
579    pub fn into_keys(self) -> IntoKeys<T, V> {
580        IntoKeys::new(self.btree_map.into_iter())
581    }
582
583    /// Gets an iterator that visits the values in the [`RangeMapBlaze`] in
584    /// the order corresponding to the integer elements. Double-ended.
585    ///
586    /// For a consuming version, see the [`RangeMapBlaze::into_values`] method.
587    ///
588    /// # Examples
589    ///
590    /// Iterating over values:
591    ///
592    /// ```rust
593    /// use range_set_blaze::RangeMapBlaze;
594    ///
595    /// let map = RangeMapBlaze::from_iter([(3, "c"), (1, "a"), (2, "b")]);
596    /// let mut values_iter = map.values();
597    /// assert_eq!(values_iter.next(), Some(&"a"));
598    /// assert_eq!(values_iter.next(), Some(&"b"));
599    /// assert_eq!(values_iter.next(), Some(&"c"));
600    /// assert_eq!(values_iter.next(), None);
601    /// ```
602    ///
603    /// Values returned by `.next()` are in the order of corresponding integer elements.
604    /// Values returned by `.next_back()` correspond to elements in descending integer order.
605    ///
606    /// ```rust
607    /// # use range_set_blaze::RangeMapBlaze;
608    /// let map = RangeMapBlaze::from_iter([(3, "c"), (1, "a"), (2, "b")]);
609    /// let mut values_iter = map.values();
610    /// assert_eq!(values_iter.next(), Some(&"a"));
611    /// assert_eq!(values_iter.next_back(), Some(&"c"));
612    /// assert_eq!(values_iter.next(), Some(&"b"));
613    /// assert_eq!(values_iter.next_back(), None);
614    /// ```
615    pub fn values(&self) -> Values<T, &V, RangeValuesIter<'_, T, V>> {
616        Values::new(self.range_values())
617    }
618
619    /// Gets an iterator that visits the values in the [`RangeMapBlaze`] in
620    /// the order corresponding to the integer elements. Double-ended.
621    ///
622    /// The iterator consumes the [`RangeMapBlaze`], yielding one value at a time for
623    /// each integer in its ranges. For a non-consuming version, see the [`RangeMapBlaze::values`] method.
624    ///
625    /// # Examples
626    ///
627    /// Iterating over values in ascending order:
628    ///
629    /// ```rust
630    /// use range_set_blaze::RangeMapBlaze;
631    ///
632    /// let map = RangeMapBlaze::from_iter([(3, "c"), (1, "a"), (2, "b")]);
633    /// let mut into_values_iter = map.into_values();
634    /// assert_eq!(into_values_iter.next(), Some("a"));
635    /// assert_eq!(into_values_iter.next(), Some("b"));
636    /// assert_eq!(into_values_iter.next(), Some("c"));
637    /// assert_eq!(into_values_iter.next(), None);
638    /// ```
639    ///
640    /// Iterating over values in both ascending and descending order:
641    ///
642    /// ```rust
643    /// use range_set_blaze::RangeMapBlaze;
644    ///
645    /// let map = RangeMapBlaze::from_iter([(1..=3, "a"), (5..=5, "b")]);
646    /// let mut into_values_iter = map.into_values();
647    /// assert_eq!(into_values_iter.next(), Some("a"));
648    /// assert_eq!(into_values_iter.next_back(), Some("b"));
649    /// assert_eq!(into_values_iter.next(), Some("a"));
650    /// assert_eq!(into_values_iter.next_back(), Some("a"));
651    /// assert_eq!(into_values_iter.next(), None);
652    /// ```
653    ///
654    /// Values returned by `.next()` correspond to elements in ascending integer order.
655    /// Values returned by `.next_back()` correspond to elements in descending integer order.
656    #[inline]
657    pub fn into_values(self) -> IntoValues<T, V> {
658        IntoValues::new(self.btree_map.into_iter())
659    }
660
661    /// Returns the first element in the set, if any.
662    /// This element is always the minimum of all integer elements in the set.
663    ///
664    /// # Examples
665    ///
666    /// Basic usage:
667    ///
668    /// ```
669    /// use range_set_blaze::RangeMapBlaze;
670    ///
671    /// let mut map = RangeMapBlaze::new();
672    /// assert_eq!(map.first_key_value(), None);
673    /// map.insert(1,"a");
674    /// assert_eq!(map.first_key_value(), Some((1, &"a")));
675    /// map.insert(2,"b");
676    /// assert_eq!(map.first_key_value(), Some((1, &"a")));
677    /// ```
678    #[must_use]
679    pub fn first_key_value(&self) -> Option<(T, &V)> {
680        self.btree_map
681            .first_key_value()
682            .map(|(k, end_value)| (*k, &end_value.value))
683    }
684
685    /// Returns the element in the set, if any, that is equal to
686    /// the value.
687    ///
688    /// # Examples
689    ///
690    /// ```
691    /// use range_set_blaze::RangeMapBlaze;
692    ///
693    /// let map = RangeMapBlaze::from_iter([(3,"c"), (1,"a"), (2,"b")]);
694    /// assert_eq!(map.get(2), Some(&"b"));
695    /// assert_eq!(map.get(4), None);
696    /// ```
697    pub fn get(&self, key: T) -> Option<&V> {
698        self.get_key_value(key).map(|(_, value)| value)
699    }
700
701    /// Returns the key and value in the map, if any, that contains the given key.
702    ///
703    /// # Examples
704    ///
705    /// ```
706    /// use range_set_blaze::RangeMapBlaze;
707    ///
708    /// let map = RangeMapBlaze::from_iter([(3..=5, "c"), (1..=2, "a")]);
709    /// assert_eq!(map.get_key_value(2), Some((2, &"a")));
710    /// assert_eq!(map.get_key_value(4), Some((4, &"c")));
711    /// assert_eq!(map.get_key_value(6), None);
712    /// ```
713    pub fn get_key_value(&self, key: T) -> Option<(T, &V)> {
714        self.btree_map
715            .range(..=key)
716            .next_back()
717            .and_then(|(_start, end_value)| {
718                if key <= end_value.end {
719                    Some((key, &end_value.value))
720                } else {
721                    None
722                }
723            })
724    }
725
726    /// Returns the last element in the set, if any.
727    /// This element is always the maximum of all elements in the set.
728    ///
729    /// # Examples
730    ///
731    /// Basic usage:
732    ///
733    /// ```
734    /// use range_set_blaze::RangeMapBlaze;
735    ///
736    /// let mut map = RangeMapBlaze::new();
737    /// assert_eq!(map.last_key_value(), None);
738    /// map.insert(1, "a");
739    /// assert_eq!(map.last_key_value(), Some((1, &"a")));
740    /// map.insert(2, "b");
741    /// assert_eq!(map.last_key_value(), Some((2, &"b")));
742    /// ```
743    #[must_use]
744    pub fn last_key_value(&self) -> Option<(T, &V)> {
745        self.btree_map
746            .last_key_value()
747            .map(|(_, end_value)| (end_value.end, &end_value.value))
748    }
749
750    /// Create a [`RangeMapBlaze`] from a [`SortedDisjointMap`] iterator.
751    ///
752    /// *For more about constructors and performance, see [`RangeMapBlaze` Constructors](struct.RangeMapBlaze.html#rangemapblaze-constructors).*
753    ///
754    /// [`SortedDisjointMap`]: trait.SortedDisjointMap.html#table-of-contents
755    ///
756    /// # Examples
757    ///
758    /// ```
759    /// use range_set_blaze::prelude::*;
760    ///
761    /// let a0 = RangeMapBlaze::from_sorted_disjoint_map(CheckSortedDisjointMap::new([(-10..=-5, &"a"), (1..=2, &"b")]));
762    /// let a1: RangeMapBlaze<i32,_> = CheckSortedDisjointMap::new([(-10..=-5, &"a"), (1..=2, &"b")]).into_range_map_blaze();
763    /// assert!(a0 == a1 && a0.to_string() == r#"(-10..=-5, "a"), (1..=2, "b")"#);
764    /// ```
765    pub fn from_sorted_disjoint_map<VR, I>(iter: I) -> Self
766    where
767        VR: ValueRef<Target = V>,
768        I: SortedDisjointMap<T, VR>,
769    {
770        let mut iter_with_len = SortedDisjointMapWithLenSoFar::new(iter);
771        let btree_map: BTreeMap<T, EndValue<T, VR::Target>> = (&mut iter_with_len).collect();
772        Self {
773            btree_map,
774            len: iter_with_len.len_so_far(),
775        }
776    }
777
778    #[allow(dead_code)]
779    #[must_use]
780    pub(crate) fn len_slow(&self) -> <T as Integer>::SafeLen {
781        Self::btree_map_len(&self.btree_map)
782    }
783
784    /// Moves all elements from `other` into `self`, leaving `other` empty.
785    ///
786    /// This method has *right-to-left precedence*:  if any ranges overlap, values in `other`
787    /// will overwrite those in `self`.
788    ///
789    /// # Performance
790    ///
791    /// This method inserts each range from `other` into `self` one-by-one, with overall time
792    /// complexity `O(n log m)`, where `n` is the number of ranges in `other` and `m` is the number
793    /// of ranges in `self`.
794    ///
795    /// For large `n`, consider using the `|` operator, which performs a sorted merge and runs in `O(n + m)` time.
796    ///
797    /// **See:** [Summary of Union and Extend-like Methods](#rangemapblaze-union--and-extend-like-methods).
798    ///
799    /// # Examples
800    ///
801    /// ```
802    /// use range_set_blaze::RangeMapBlaze;
803    ///
804    /// let mut a = RangeMapBlaze::from_iter([(1..=3,"a")]);
805    /// let mut b = RangeMapBlaze::from_iter([(3..=5,"b")]);
806    ///
807    /// a.append(&mut b);
808    ///
809    /// assert_eq!(a.len(), 5u64);
810    /// assert_eq!(b.len(), 0u64);
811    ///
812    /// assert_eq!(a[1], "a");
813    /// assert_eq!(a[2], "a");
814    /// assert_eq!(a[3], "b");
815    /// assert_eq!(a[4], "b");
816    /// assert_eq!(a[5], "b");
817    /// ```
818    pub fn append(&mut self, other: &mut Self) {
819        let original_other_btree_map = core::mem::take(&mut other.btree_map);
820        other.len = <T as Integer>::SafeLen::zero();
821
822        for (start, end_value) in original_other_btree_map {
823            self.internal_add(start..=end_value.end, end_value.value);
824        }
825    }
826
827    /// Clears the map, removing all elements.
828    ///
829    /// # Examples
830    ///
831    /// ```
832    /// use range_set_blaze::RangeMapBlaze;
833    ///
834    /// let mut a = RangeMapBlaze::new();
835    /// a.insert(1, "a");
836    /// a.clear();
837    /// assert!(a.is_empty());
838    /// ```
839    pub fn clear(&mut self) {
840        self.btree_map.clear();
841        self.len = <T as Integer>::SafeLen::zero();
842    }
843
844    /// Returns `true` if the map contains no elements.
845    ///
846    /// # Examples
847    ///
848    /// ```
849    /// use range_set_blaze::RangeMapBlaze;
850    ///
851    /// let mut a = RangeMapBlaze::new();
852    /// assert!(a.is_empty());
853    /// a.insert(1, "a");
854    /// assert!(!a.is_empty());
855    /// ```
856    #[must_use]
857    #[inline]
858    pub fn is_empty(&self) -> bool {
859        self.btree_map.is_empty()
860    }
861
862    /// Returns `true` if the set contains an element equal to the value.
863    ///
864    /// # Examples
865    ///
866    /// ```
867    /// use range_set_blaze::RangeMapBlaze;
868    ///
869    /// let map = RangeMapBlaze::from_iter([(3,"c"), (1,"a"), (2,"b")]);
870    /// assert_eq!(map.contains_key(1), true);
871    /// assert_eq!(map.contains_key(4), false);
872    /// ```
873    pub fn contains_key(&self, key: T) -> bool {
874        self.btree_map
875            .range(..=key)
876            .next_back()
877            .is_some_and(|(_, end_value)| key <= end_value.end)
878    }
879
880    // LATER: might be able to shorten code by combining cases
881    fn delete_extra(&mut self, internal_range: &RangeInclusive<T>) {
882        let (start, end) = internal_range.clone().into_inner();
883        let mut after = self.btree_map.range_mut(start..);
884        let (start_after, end_value_after) = after
885            .next()
886            .expect("Real Assert: There will always be a next");
887        debug_assert!(start == *start_after && end == end_value_after.end);
888
889        let mut end_new = end;
890        let mut end_new_same_val = end;
891        let delete_list = after
892            .map_while(|(start_delete, end_value_delete)| {
893                // same values
894                if end_value_after.value == end_value_delete.value {
895                    // must check this in two parts to avoid overflow
896                    if *start_delete <= end || *start_delete <= end.add_one() {
897                        end_new_same_val = max(end_new_same_val, end_value_delete.end);
898                        end_new = max(end_new, end_value_delete.end);
899                        self.len -= T::safe_len(&(*start_delete..=end_value_delete.end));
900                        Some(*start_delete)
901                    } else {
902                        None
903                    }
904                // different values
905                } else if *start_delete <= end {
906                    end_new = max(end_new, end_value_delete.end);
907                    self.len -= T::safe_len(&(*start_delete..=end_value_delete.end));
908                    Some(*start_delete)
909                } else {
910                    None
911                }
912            })
913            .collect::<Vec<_>>();
914        if end >= end_new {
915            for start in delete_list {
916                self.btree_map.remove(&start);
917            }
918        } else if end_new_same_val > end {
919            // last item is the same as the new and extends beyond the new
920            self.len += T::safe_len(&(end..=end_new.sub_one()));
921            debug_assert!(*start_after <= end_new);
922            end_value_after.end = end_new;
923            for start in delete_list {
924                self.btree_map.remove(&start);
925            }
926        } else {
927            // last item extends beyond the new but has a different value.
928            for &start in &delete_list[0..delete_list.len() - 1] {
929                self.btree_map.remove(&start);
930                // take the last one
931            }
932            let last = self
933                .btree_map
934                .remove(&delete_list[delete_list.len() - 1])
935                .expect("Real Assert: There will always be a last");
936            let last_end = last.end;
937            debug_assert!(end.add_one() <= last.end); // real assert
938            self.btree_map.insert(end.add_one(), last);
939            self.len += T::safe_len(&(end.add_one()..=last_end));
940        }
941    }
942
943    /// Adds a value to the set.
944    ///
945    /// Returns whether the value was newly inserted. That is:
946    ///
947    /// - If the set did not previously contain an equal value, `true` is
948    ///   returned.
949    /// - If the set already contained an equal value, `false` is returned, and
950    ///   the entry is not updated.
951    ///
952    /// # Performance
953    /// 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`.
954    /// When n is large, consider using `|` which is O(n+m) time.
955    ///
956    /// # Examples
957    ///
958    /// ```
959    /// use range_set_blaze::RangeMapBlaze;
960    ///
961    /// let mut map = RangeMapBlaze::new();
962    /// assert_eq!(map.insert(37, "a"), None);
963    /// assert_eq!(map.is_empty(), false);
964    ///
965    /// map.insert(37, "b");
966    /// assert_eq!(map.insert(37, "c"), Some("b"));
967    /// assert_eq!(map[37], "c");
968    /// ```
969    pub fn insert(&mut self, key: T, value: V) -> Option<V> {
970        let old = self.get(key).cloned();
971        self.internal_add(key..=key, value);
972        old
973    }
974
975    // LATER: Think about an entry API with or_insert and or_insert_with
976
977    /// Constructs an iterator over a sub-range of elements in the set.
978    ///
979    /// Not to be confused with [`RangeMapBlaze::ranges`], which returns an iterator over the ranges in the set.
980    ///
981    /// The simplest way is to use the range syntax `min..max`, thus `range(min..max)` will
982    /// yield elements from min (inclusive) to max (exclusive).
983    /// The range may also be entered as `(Bound<T, V, VR>, Bound<T, V, VR>)`, so for example
984    /// `range((Excluded(4), Included(10)))` will yield a left-exclusive, right-inclusive
985    /// range from 4 to 10.
986    ///
987    /// # Panics
988    ///
989    /// Panics if start (inclusive) is greater than end (inclusive).
990    ///
991    /// # Performance
992    ///
993    /// 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.
994    ///
995    /// # Examples
996    ///
997    /// ```
998    /// use range_set_blaze::RangeMapBlaze;
999    /// use core::ops::Bound::Included;
1000    ///
1001    /// let mut map = RangeMapBlaze::new();
1002    /// map.insert(3, "a");
1003    /// map.insert(5, "b");
1004    /// map.insert(8, "c");
1005    /// for (key, value) in map.range((Included(4), Included(8))) {
1006    ///     println!("{key}: {value}");
1007    /// } // prints "5: b" and "8: c"
1008    /// assert_eq!(Some((5, "b")), map.range(4..).next());
1009    /// ```
1010    #[allow(clippy::manual_assert)] // We use "if...panic!" for coverage auditing.
1011    pub fn range<R>(&self, range: R) -> IntoIterMap<T, V>
1012    where
1013        R: RangeBounds<T>,
1014    {
1015        // LATER 'range' could be made more efficient (it currently creates a RangeMapBlaze for no good reason)
1016        let (start, end) = extract_range(range);
1017        assert!(
1018            start <= end,
1019            "start (inclusive) must be less than or equal to end (inclusive)"
1020        );
1021
1022        let bounds = CheckSortedDisjoint::new([start..=end]);
1023        let range_map_blaze = self
1024            .range_values()
1025            .map_and_set_intersection(bounds)
1026            .into_range_map_blaze();
1027        range_map_blaze.into_iter()
1028    }
1029
1030    /// Adds a range to the set.
1031    ///
1032    /// Returns whether any values where newly inserted. That is:
1033    ///
1034    /// - If the set did not previously contain some value in the range, `true` is
1035    ///   returned.
1036    /// - If the set already contained every value in the range, `false` is returned, and
1037    ///   the entry is not updated.
1038    ///
1039    /// # Performance
1040    /// 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`.
1041    /// When n is large, consider using `|` which is O(n+m) time.
1042    ///
1043    /// # Examples
1044    ///
1045    /// ```
1046    /// use range_set_blaze::RangeMapBlaze;
1047    ///
1048    /// let mut map = RangeMapBlaze::new();
1049    /// assert_eq!(map.ranges_insert(2..=5, "a"), true);
1050    /// assert_eq!(map.ranges_insert(5..=6, "b"), true);
1051    /// assert_eq!(map.ranges_insert(3..=4, "c"), false);
1052    /// assert_eq!(map.len(), 5u64);
1053    /// ```
1054    pub fn ranges_insert(&mut self, range: RangeInclusive<T>, value: V) -> bool {
1055        let len_before = self.len;
1056        self.internal_add(range, value);
1057        self.len != len_before
1058    }
1059
1060    /// If the set contains an element equal to the value, removes it from the
1061    /// set and drops it. Returns whether such an element was present.
1062    ///
1063    /// # Examples
1064    ///
1065    /// ```
1066    /// use range_set_blaze::RangeMapBlaze;
1067    ///
1068    /// let mut map = RangeMapBlaze::new();
1069    /// map.insert(1, "a");
1070    /// assert_eq!(map.remove(1), Some("a"));
1071    /// assert_eq!(map.remove(1), None);
1072    /// ```
1073    #[allow(clippy::missing_panics_doc)]
1074    pub fn remove(&mut self, key: T) -> Option<V> {
1075        // The code can have only one mutable reference to self.btree_map.
1076
1077        // Find that range that might contain the key
1078        let (start_ref, end_value_mut) = self.btree_map.range_mut(..=key).next_back()?;
1079        let end = end_value_mut.end;
1080
1081        // If the key is not in the range, we're done
1082        if end < key {
1083            return None;
1084        }
1085        let start = *start_ref;
1086        debug_assert!(start <= key, "Real Assert: start <= key");
1087
1088        // It's in the range.
1089        self.len -= <T::SafeLen>::one();
1090
1091        let value = if start == key {
1092            self.btree_map
1093                .remove(&start)
1094                .expect("Real Assert: There will always be a start")
1095                .value
1096        } else {
1097            debug_assert!(start < key, "Real Assert: start < key");
1098            // This range will now end at key-1.
1099            end_value_mut.end = key.sub_one();
1100            end_value_mut.value.clone()
1101        };
1102
1103        // If needed, add a new range after key
1104        if key < end {
1105            self.btree_map.insert(
1106                key.add_one(),
1107                EndValue {
1108                    end,
1109                    value: value.clone(),
1110                },
1111            );
1112        }
1113
1114        Some(value)
1115    }
1116
1117    /// Splits the collection into two at the value. Returns a new collection
1118    /// with all elements greater than or equal to the value.
1119    ///
1120    /// # Examples
1121    ///
1122    /// Basic usage:
1123    ///
1124    /// ```
1125    /// use range_set_blaze::RangeMapBlaze;
1126    ///
1127    /// let mut a = RangeMapBlaze::new();
1128    /// a.insert(1, "a");
1129    /// a.insert(2, "b");
1130    /// a.insert(3, "c");
1131    /// a.insert(17, "d");
1132    /// a.insert(41, "e");
1133    ///
1134    /// let b = a.split_off(3);
1135    ///
1136    /// assert_eq!(a, RangeMapBlaze::from_iter([(1..=1, "a"), (2..=2, "b")]));
1137    /// assert_eq!(b, RangeMapBlaze::from_iter([(3..=3, "c"), (17..=17, "d"), (41..=41, "e")]));
1138    /// ```
1139    #[must_use]
1140    pub fn split_off(&mut self, key: T) -> Self {
1141        let old_len = self.len;
1142        let old_btree_len = self.btree_map.len();
1143        let mut new_btree = self.btree_map.split_off(&key);
1144        let Some(last_entry) = self.btree_map.last_entry() else {
1145            // Left is empty
1146            self.len = T::SafeLen::zero();
1147            return Self {
1148                btree_map: new_btree,
1149                len: old_len,
1150            };
1151        };
1152
1153        let end_value = last_entry.get();
1154        let end = end_value.end;
1155        if end < key {
1156            // The split is clean
1157            let (a_len, b_len) = self.two_element_lengths(old_btree_len, &new_btree, old_len);
1158            self.len = a_len;
1159            return Self {
1160                btree_map: new_btree,
1161                len: b_len,
1162            };
1163        }
1164
1165        // The split is not clean, so we must move some keys from the end of self to the start of b.
1166        let value = end_value.value.clone();
1167        last_entry.into_mut().end = key.sub_one();
1168        new_btree.insert(key, EndValue { end, value });
1169        let (a_len, b_len) = self.two_element_lengths(old_btree_len, &new_btree, old_len);
1170        self.len = a_len;
1171        Self {
1172            btree_map: new_btree,
1173            len: b_len,
1174        }
1175    }
1176
1177    // Find the len of the smaller btree_map and then the element len of self & b.
1178    fn two_element_lengths(
1179        &self,
1180        old_btree_len: usize,
1181        new_btree: &BTreeMap<T, EndValue<T, V>>,
1182        mut old_len: <T as Integer>::SafeLen,
1183    ) -> (<T as Integer>::SafeLen, <T as Integer>::SafeLen) {
1184        if old_btree_len / 2 < new_btree.len() {
1185            let a_len = Self::btree_map_len(&self.btree_map);
1186            old_len -= a_len;
1187            (a_len, old_len)
1188        } else {
1189            let b_len = Self::btree_map_len(new_btree);
1190            old_len -= b_len;
1191            (old_len, b_len)
1192        }
1193    }
1194
1195    fn btree_map_len(btree_map: &BTreeMap<T, EndValue<T, V>>) -> T::SafeLen {
1196        btree_map.iter().fold(
1197            <T as Integer>::SafeLen::zero(),
1198            |acc, (start, end_value)| acc + T::safe_len(&(*start..=end_value.end)),
1199        )
1200    }
1201
1202    #[inline]
1203    fn has_gap(end_before: T, start: T) -> bool {
1204        end_before
1205            .checked_add_one()
1206            .is_some_and(|end_before_succ| end_before_succ < start)
1207    }
1208
1209    #[cfg(never)]
1210    // TODO: Look at other TODOs before enabling this.
1211    // #![cfg_attr(feature = "cursor", feature(btree_cursors, new_range_api))]
1212    // #[cfg(feature = "cursor")]
1213    //  use core::{cmp::min, range::Bound};
1214    #[inline]
1215    fn adjust_touching_for_insert(
1216        &mut self,
1217        stored_start: T,
1218        stored_end_value: EndValue<T, V>,
1219        range: &mut RangeInclusive<T>,
1220        value: &V,
1221    ) {
1222        let stored_value = &stored_end_value.value;
1223        let stored_end = stored_end_value.end;
1224
1225        // ── 1. Same value → coalesce completely ──────────────────────────────
1226        if stored_value == value {
1227            let new_start = min(*range.start(), stored_start);
1228            let new_end = max(*range.end(), stored_end);
1229            *range = new_start..=new_end;
1230
1231            self.len -= T::safe_len(&(stored_start..=stored_end));
1232            self.btree_map.remove(&stored_start);
1233            return;
1234        }
1235
1236        // ── 2. Different value → may need to split ───────────────────────────
1237        let overlaps = stored_start <= *range.end() && stored_end >= *range.start();
1238
1239        if overlaps {
1240            // Remove the overlapping range first.
1241            self.len -= T::safe_len(&(stored_start..=stored_end));
1242            self.btree_map.remove(&stored_start);
1243
1244            // Left residual slice
1245            if stored_start < *range.start() {
1246                let left_end = range.start().sub_one(); // TODO are we sure this won't underflow?
1247                self.len += T::safe_len(&(stored_start..=left_end));
1248                self.btree_map.insert(
1249                    stored_start,
1250                    EndValue {
1251                        end: left_end,
1252                        value: stored_value.clone(),
1253                    },
1254                );
1255            }
1256
1257            // Right residual slice
1258            if stored_end > *range.end() {
1259                let right_start = range.end().add_one();
1260                self.len += T::safe_len(&(right_start..=stored_end));
1261                self.btree_map.insert(
1262                    right_start,
1263                    EndValue {
1264                        end: stored_end,
1265                        value: stored_end_value.value, // already owned
1266                    },
1267                );
1268            }
1269        }
1270        // Otherwise: no overlap → keep ranges as they are.
1271    }
1272
1273    #[cfg(never)]
1274    // For benchmarking, based on https://github.com/jeffparsons/rangemap's `insert` method.
1275    pub(crate) fn internal_add(&mut self, mut range: RangeInclusive<T>, value: V) {
1276        use core::ops::Bound::{Included, Unbounded}; // TODO: Move to the top
1277
1278        let start = *range.start();
1279        let end = *range.end();
1280
1281        // === case: empty
1282        if end < start {
1283            return;
1284        }
1285
1286        // Walk *backwards* from the first stored range whose start ≤ `start`.
1287        //      Take the nearest two so we can look at “before” and “before-before”.
1288        let mut candidates = self
1289            .btree_map
1290            .range::<T, _>((Unbounded, Included(&start))) // ..= start
1291            .rev()
1292            .take(2)
1293            .filter(|(_stored_start, stored_end_value)| {
1294                // TODO use saturation arithmetic to avoid underflow
1295                let end = stored_end_value.end;
1296                end >= start || (start != T::min_value() && end >= start.sub_one())
1297            });
1298
1299        if let Some(mut candidate) = candidates.next() {
1300            // Or the one before it if both cases described above exist.
1301            if let Some(another_candidate) = candidates.next() {
1302                candidate = another_candidate;
1303            }
1304
1305            let stored_start: T = *candidate.0;
1306            let stored_end_value: EndValue<T, V> = candidate.1.clone();
1307            self.adjust_touching_for_insert(
1308                stored_start,
1309                stored_end_value,
1310                &mut range, // `end` is the current (possibly growing) tail
1311                &value,
1312            );
1313        }
1314
1315        // let range = &mut range; // &mut RangeInclusive<T>
1316
1317        loop {
1318            // first range whose start ≥ new_range.start()
1319            let next_entry = self
1320                .btree_map
1321                .range::<T, _>((Included(range.start()), Unbounded))
1322                .next();
1323
1324            let Some((&stored_start, stored_end_value)) = next_entry else {
1325                break; // nothing more
1326            };
1327
1328            let second_last_possible_start = *range.end();
1329            let maybe_latest_start = if second_last_possible_start == T::max_value() {
1330                None
1331            } else {
1332                Some(second_last_possible_start.add_one())
1333            };
1334
1335            if maybe_latest_start.map_or(false, |latest| stored_start > latest) {
1336                break; // beyond end + 1
1337            }
1338            if let Some(latest) = maybe_latest_start {
1339                if stored_start == latest && stored_end_value.value != value {
1340                    break; // touches but diff value
1341                }
1342            }
1343
1344            // clone so we can mutate the map in the helper
1345            let end_value_clone = stored_end_value.clone();
1346
1347            self.adjust_touching_for_insert(stored_start, end_value_clone, &mut range, &value);
1348
1349            // loop again; `new_range` might have grown on the right
1350        }
1351
1352        let start_key = *range.start();
1353        let end_key = *range.end();
1354        // self.len += T::safe_len(&(start_key..=end_key));
1355        self.btree_map.insert(
1356            start_key,
1357            EndValue {
1358                end: end_key,
1359                value,
1360            },
1361        );
1362
1363        debug_assert!(self.len == self.len_slow());
1364    }
1365
1366    #[cfg(never)]
1367    // #[cfg(feature = "cursor")]
1368    pub(crate) fn internal_add(&mut self, mut range: RangeInclusive<T>, value: V) {
1369        // Based on https://github.com/jeffparsons/rangemap's `insert` method but with cursor's added
1370        use core::ops::Bound::{Included, Unbounded};
1371        use std::collections::btree_map::CursorMut;
1372
1373        let start = *range.start();
1374        let end = *range.end();
1375
1376        // === case: empty
1377        if end < start {
1378            return;
1379        }
1380
1381        // Walk *backwards* from the first stored range whose start ≤ `start`.
1382        //      Take the nearest two so we can look at “before” and “before-before”.
1383        let mut candidates = self
1384            .btree_map
1385            .range::<T, _>((Unbounded, Included(&start))) // ..= start
1386            .rev()
1387            .take(2)
1388            .filter(|(_stored_start, stored_end_value)| {
1389                let end = stored_end_value.end;
1390                end >= start || (start != T::min_value() && end >= start.sub_one())
1391            });
1392
1393        if let Some(mut candidate) = candidates.next() {
1394            // Or the one before it if both cases described above exist.
1395            if let Some(another_candidate) = candidates.next() {
1396                candidate = another_candidate;
1397            }
1398
1399            let stored_start: T = *candidate.0;
1400            let stored_end_value: EndValue<T, V> = candidate.1.clone();
1401            self.adjust_touching_for_insert(
1402                stored_start,
1403                stored_end_value,
1404                &mut range, // `end` is the current (possibly growing) tail
1405                &value,
1406            );
1407        }
1408        // keep looping until we hit the stop window
1409        loop {
1410            // create a fresh cursor _for this iteration only_
1411            let mut cur: CursorMut<'_, T, EndValue<T, V>> = self
1412                .btree_map
1413                .lower_bound_mut(Bound::Included(range.start()));
1414
1415            let Some(peeked) = cur.peek_next() else {
1416                break;
1417            };
1418            let (&stored_start, maybe_end_value) = peeked;
1419
1420            let last_ok = *range.end();
1421            if last_ok == T::max_value() {
1422                if stored_start > last_ok {
1423                    break;
1424                }
1425            } else {
1426                let latest = last_ok.add_one();
1427                if stored_start > latest {
1428                    break;
1429                }
1430                if stored_start == latest && maybe_end_value.value != value {
1431                    break;
1432                }
1433            }
1434
1435            // now clone and remove
1436            let cloned = maybe_end_value.clone();
1437            cur.remove_next();
1438
1439            // now we can call any &mut-self helper safely
1440            self.adjust_touching_for_insert(stored_start, cloned, &mut range, &value);
1441        }
1442
1443        let start_key = *range.start();
1444        let end_key = *range.end();
1445
1446        self.btree_map.insert(
1447            start_key,
1448            EndValue {
1449                end: end_key,
1450                value, // moves `value`
1451            },
1452        );
1453        self.len += T::safe_len(&(start_key..=end_key));
1454
1455        debug_assert!(self.len == self.len_slow());
1456    }
1457
1458    // https://stackoverflow.com/questions/49599833/how-to-find-next-smaller-key-in-btreemap-btreeset
1459    // https://stackoverflow.com/questions/35663342/how-to-modify-partially-remove-a-range-from-a-btreemap
1460    // LATER might be able to shorten code by combining cases
1461    // FUTURE: would be nice of BTreeMap to have a partition_point function that returns two iterators
1462    #[allow(clippy::too_many_lines)]
1463    #[allow(clippy::cognitive_complexity)]
1464    pub(crate) fn internal_add(&mut self, range: RangeInclusive<T>, value: V) {
1465        let (start, end) = range.clone().into_inner();
1466
1467        // === case: empty
1468        if end < start {
1469            return;
1470        }
1471        let mut before_iter = self.btree_map.range_mut(..=start).rev();
1472
1473        // === case: no before
1474        let Some((start_before, end_value_before)) = before_iter.next() else {
1475            // no before, so must be first
1476            self.internal_add2(&range, value);
1477            // You must return or break out of the current block after handling the failure case
1478            return;
1479        };
1480
1481        let start_before = *start_before;
1482        let end_before = end_value_before.end;
1483
1484        // === case: gap between before and new
1485        if Self::has_gap(end_before, start) {
1486            // there is a gap between the before and the new
1487            // ??? aa...
1488            self.internal_add2(&range, value);
1489            return;
1490        }
1491
1492        let before_contains_new = end_before >= end;
1493        let same_value = value == end_value_before.value;
1494
1495        // === case: same value and before contains new
1496        if before_contains_new && same_value {
1497            // same value, so do nothing
1498            // AAAAA
1499            //  aaa
1500            return;
1501        }
1502
1503        // === case: same value and new extends beyond before
1504        if !before_contains_new && same_value {
1505            // same value, so just extend the before
1506            // AAA
1507            //  aaaa...
1508            self.len += T::safe_len(&(end_before..=end.sub_one()));
1509            debug_assert!(start_before <= end); // real assert
1510            end_value_before.end = end;
1511            self.delete_extra(&(start_before..=end));
1512            return;
1513        }
1514
1515        // Thus, the values are different
1516
1517        let same_start = start == start_before;
1518
1519        // === case: new goes beyond before and different values
1520        if !before_contains_new && !same_value && same_start {
1521            // Thus, values are different, before contains new, and they start together
1522
1523            let interesting_before_before = match before_iter.next() {
1524                Some(bb) if bb.1.end.add_one() == start && bb.1.value == value => Some(bb),
1525                _ => None,
1526            };
1527
1528            // === case: values are different, new extends beyond before, and they start together and an interesting before-before
1529            // an interesting before-before: something before before, touching and with the same value as new
1530            if let Some(bb) = interesting_before_before {
1531                debug_assert!(!before_contains_new && !same_value && same_start);
1532
1533                // AABBBB
1534                //   aaaaaaa
1535                // AAAAAAAAA
1536                self.len += T::safe_len(&(bb.1.end.add_one()..=end));
1537                let bb_start = *bb.0;
1538                debug_assert!(bb_start <= end); // real assert
1539                bb.1.end = end;
1540                self.delete_extra(&(bb_start..=end));
1541                return;
1542            }
1543
1544            // === case: values are different, they start together but new ends later and no interesting before-before
1545            debug_assert!(!same_value && same_start && interesting_before_before.is_none());
1546
1547            // ^BBBB
1548            //  aaaaaaa
1549            // ^AAAAAAA
1550            debug_assert!(end_before < end); // real assert
1551            self.len += T::safe_len(&(end_before.add_one()..=end));
1552            end_value_before.end = end;
1553            end_value_before.value = value;
1554            self.delete_extra(&range);
1555            return;
1556        }
1557        if !before_contains_new && !same_value && !same_start {
1558            // different value, so must trim the before and then insert the new
1559            // BBB
1560            //  aaaa...
1561            if start <= end_before {
1562                self.len -= T::safe_len(&(start..=end_before));
1563                debug_assert!(start_before <= start.sub_one()); // real assert
1564                end_value_before.end = start.sub_one(); // safe because !same_start
1565            }
1566            self.internal_add2(&range, value);
1567            return;
1568        }
1569
1570        // Thus, the values are different and before contains new
1571        debug_assert!(before_contains_new && !same_value);
1572
1573        let same_end = end == end_before;
1574
1575        // === case: values are different and new is surrounded by before
1576        if !same_start && !same_end {
1577            debug_assert!(before_contains_new && !same_value);
1578            debug_assert!(start_before < start && end < end_before);
1579            // Different values still ...
1580            // The new starts later and ends before,
1581            // BBBBBB
1582            //   aaa
1583            // BBAAAB
1584            //  so trim the before and then insert two
1585            debug_assert!(start_before <= start.sub_one()); // real assert
1586            end_value_before.end = start.sub_one();
1587            let before_value = end_value_before.value.clone();
1588            debug_assert!(start <= end); // real assert
1589            self.btree_map.insert(start, EndValue { end, value });
1590            debug_assert!(end.add_one() <= end_before); // real assert
1591            self.btree_map.insert(
1592                end.add_one(),
1593                EndValue {
1594                    end: end_before,
1595                    value: before_value,
1596                },
1597            );
1598            return;
1599        }
1600
1601        // === case: values are different, new instead of before and they end together
1602        if !same_start && same_end {
1603            debug_assert!(before_contains_new && !same_value);
1604            debug_assert!(start_before < start && end == end_before);
1605            // Different values still ...
1606            // The new starts later but they end together,
1607            // BBBBB???
1608            //   aaa
1609            // BBAAA???
1610            //  so trim the before and then insert the new.
1611            debug_assert!(start_before <= start.sub_one()); // real assert
1612            end_value_before.end = start.sub_one();
1613            debug_assert!(start <= end); // real assert
1614            self.btree_map.insert(start, EndValue { end, value });
1615            self.delete_extra(&(start..=end));
1616            return;
1617        }
1618
1619        // Thus, values are different, before contains new, and they start together
1620
1621        let interesting_before_before = match before_iter.next() {
1622            Some(bb) if bb.1.end.add_one() == start && bb.1.value == value => Some(bb),
1623            _ => None,
1624        };
1625
1626        // === case: values are different, before contains new, and they start together and an interesting before-before
1627        // an interesting before-before: something before before, touching and with the same value as new
1628        if let Some(bb) = interesting_before_before {
1629            debug_assert!(before_contains_new && !same_value && same_start);
1630
1631            // AABBBB???
1632            //   aaaa
1633            // AAAAAA???
1634            self.len += T::safe_len(&(bb.1.end.add_one()..=end));
1635            let bb_start = *bb.0;
1636            debug_assert!(bb_start <= end); // real assert
1637            bb.1.end = end;
1638            self.delete_extra(&(bb_start..=end));
1639            return;
1640        }
1641
1642        // === case: values are different, they start and end together and no interesting before-before
1643        if same_end {
1644            debug_assert!(!same_value && same_start && interesting_before_before.is_none());
1645
1646            // ^BBBB???
1647            //  aaaa
1648            // ^AAAA???
1649            end_value_before.value = value;
1650            self.delete_extra(&(start_before..=end));
1651            return;
1652        }
1653
1654        // === case: values are different, they start together, new ends first, and no interesting before-before
1655        {
1656            debug_assert!(
1657                !same_value
1658                    && same_start
1659                    && end < end_before
1660                    && interesting_before_before.is_none()
1661            );
1662
1663            // ^BBBB
1664            //  aaa
1665            // ^AAAB
1666            let value_before = core::mem::replace(&mut end_value_before.value, value);
1667            debug_assert!(start_before <= end); // real assert
1668            end_value_before.end = end;
1669            debug_assert!(end.add_one() <= end_before); // real assert
1670            self.btree_map.insert(
1671                end.add_one(),
1672                EndValue {
1673                    end: end_before,
1674                    value: value_before,
1675                },
1676            );
1677        }
1678    }
1679
1680    #[inline]
1681    fn internal_add2(&mut self, internal_range: &RangeInclusive<T>, value: V) {
1682        let (start, end) = internal_range.clone().into_inner();
1683        let end_value = EndValue { end, value };
1684        debug_assert!(start <= end_value.end); // real assert
1685        let was_there = self.btree_map.insert(start, end_value);
1686        debug_assert!(was_there.is_none()); // no range with the same start should be there
1687        self.delete_extra(internal_range);
1688        self.len += T::safe_len(internal_range);
1689    }
1690
1691    /// Returns the number of elements in the set.
1692    ///
1693    /// The number is allowed to be very, very large.
1694    ///
1695    /// # Examples
1696    ///
1697    /// ```
1698    /// use range_set_blaze::prelude::*;
1699    ///
1700    /// let mut a = RangeMapBlaze::new();
1701    /// assert_eq!(a.len(), 0u64);
1702    /// a.insert(1, "a");
1703    /// assert_eq!(a.len(), 1u64);
1704    ///
1705    /// let a = RangeMapBlaze::from_iter([
1706    ///     (-170_141_183_460_469_231_731_687_303_715_884_105_728_i128..=10, "a"),
1707    ///     (-10..=170_141_183_460_469_231_731_687_303_715_884_105_726, "a")]);
1708    /// assert_eq!(
1709    ///     a.len(),
1710    ///     UIntPlusOne::UInt(340282366920938463463374607431768211455)
1711    /// );
1712    /// ```
1713    #[must_use]
1714    pub const fn len(&self) -> <T as Integer>::SafeLen {
1715        self.len
1716    }
1717
1718    /// Makes a new, empty [`RangeMapBlaze`].
1719    ///
1720    /// # Examples
1721    ///
1722    /// ```
1723    /// # #![allow(unused_mut)]
1724    /// use range_set_blaze::RangeMapBlaze;
1725    ///
1726    /// let mut map = RangeMapBlaze::new();
1727    ///
1728    /// // entries can now be inserted into the empty map
1729    /// map.insert(1, "a");
1730    /// assert_eq!(map[1], "a");
1731    /// ```
1732    #[inline]
1733    #[must_use]
1734    pub fn new() -> Self {
1735        Self {
1736            btree_map: BTreeMap::new(),
1737            len: <T as Integer>::SafeLen::zero(),
1738        }
1739    }
1740
1741    /// Extends the [`RangeMapBlaze`] with an iterator of `(range, value)` pairs without pre-merging.
1742    ///
1743    /// Unlike [`RangeMapBlaze::extend`], this method does **not** merge adjacent or overlapping ranges
1744    /// before inserting. Each `(range, value)` pair is added as-is, making it faster when the input
1745    /// is already well-structured or disjoint.
1746    ///
1747    /// This method has *right-to-left precedence*: later ranges in the iterator overwrite earlier ones.
1748    ///
1749    /// **See:** [Summary of Union and Extend-like Methods](#rangemapblaze-union--and-extend-like-methods).
1750    ///
1751    /// # Examples
1752    /// ```
1753    /// use range_set_blaze::RangeMapBlaze;
1754    /// let mut a = RangeMapBlaze::from_iter([(1..=4, "a")]);
1755    /// a.extend_simple([(3..=5, "b"), (5..=5, "c")]);
1756    /// assert_eq!(a, RangeMapBlaze::from_iter([(1..=2, "a"), (3..=4, "b"), (5..=5, "c")]));
1757    ///
1758    /// let mut a = RangeMapBlaze::from_iter([(1..=4, "a")]);
1759    /// a.extend([(3..=5, "b"), (5..=5, "c")]);
1760    /// assert_eq!(a, RangeMapBlaze::from_iter([(1..=2, "a"), (3..=4, "b"), (5..=5, "c")]));
1761    ///
1762    /// let mut a = RangeMapBlaze::from_iter([(3..=5, "b"), (5..=5, "c")]);
1763    /// let mut b = RangeMapBlaze::from_iter([(1..=4, "a")]);
1764    /// a |= b;
1765    /// assert_eq!(a, RangeMapBlaze::from_iter([(1..=4, "a"), (5..=5, "c")]));
1766    /// ```
1767    pub fn extend_simple<I>(&mut self, iter: I)
1768    where
1769        I: IntoIterator<Item = (RangeInclusive<T>, V)>,
1770    {
1771        let iter = iter.into_iter();
1772
1773        for (range, value) in iter {
1774            self.internal_add(range, value);
1775        }
1776    }
1777
1778    /// Extends the [`RangeMapBlaze`] with the contents of an owned [`RangeMapBlaze`].
1779    ///
1780    /// This method follows standard *right-to-left precedence*: If the maps contain overlapping ranges,
1781    /// values from `other` will overwrite those in `self`.
1782    ///
1783    /// Compared to [`RangeMapBlaze::extend_with`], this method can be more efficient because it can
1784    /// consume the internal data structures of `other` directly, avoiding some cloning.
1785    ///
1786    /// **See:** [Summary of Union and Extend-like Methods](#rangemapblaze-union--and-extend-like-methods).
1787    ///
1788    /// # Examples
1789    ///
1790    /// ```
1791    /// use range_set_blaze::RangeMapBlaze;
1792    /// let mut a = RangeMapBlaze::from_iter([(1..=4, "a")]);
1793    /// let mut b = RangeMapBlaze::from_iter([(3..=4, "b"), (5..=5, "c")]);
1794    /// a.extend_from(b);
1795    /// assert_eq!(a, RangeMapBlaze::from_iter([(1..=2, "a"), (3..=4, "b"), (5..=5, "c")]));
1796    /// ```
1797    #[inline]
1798    pub fn extend_from(&mut self, other: Self) {
1799        for (start, end_value) in other.btree_map {
1800            let range = start..=end_value.end;
1801            self.internal_add(range, end_value.value);
1802        }
1803    }
1804
1805    /// Extends the [`RangeMapBlaze`] with the contents of a borrowed [`RangeMapBlaze`].
1806    ///
1807    /// This method follows standard *right-to-left precedence*: If the maps contain overlapping ranges,
1808    /// values from `other` will overwrite those in `self`.
1809    ///
1810    /// This method is simple and predictable but not the most efficient option when
1811    /// the right-hand side is larger. For better performance when ownership is available,
1812    /// consider using [`RangeMapBlaze::extend_from`] or the `|=` operator.
1813    ///
1814    /// **See:** [Summary of Union and Extend-like Methods](#rangemapblaze-union--and-extend-like-methods).
1815    ///
1816    /// # Examples
1817    ///
1818    /// ```
1819    /// use range_set_blaze::RangeMapBlaze;
1820    /// let mut a = RangeMapBlaze::from_iter([(1..=4, "a")]);
1821    /// let mut b = RangeMapBlaze::from_iter([(3..=4, "b"), (5..=5, "c")]);
1822    /// a.extend_from(b);
1823    /// assert_eq!(a, RangeMapBlaze::from_iter([(1..=2, "a"), (3..=4, "b"), (5..=5, "c")]));
1824    /// ```
1825    #[inline]
1826    pub fn extend_with(&mut self, other: &Self) {
1827        for (start, end_value) in &other.btree_map {
1828            let range = *start..=end_value.end;
1829            self.internal_add(range, end_value.value.clone());
1830        }
1831    }
1832
1833    /// Removes the first element from the set and returns it, if any.
1834    /// The first element is always the minimum element in the set.
1835    ///
1836    /// Often, internally, the value must be cloned.
1837    ///
1838    /// # Examples
1839    ///
1840    /// ```
1841    /// use range_set_blaze::RangeMapBlaze;
1842    ///
1843    /// let mut map = RangeMapBlaze::new();
1844    ///
1845    /// map.insert(1, "a");
1846    /// map.insert(2, "b");
1847    /// while let Some((key, _val)) = map.pop_first() {
1848    ///     assert!(map.iter().all(|(k, _v)| k > key));
1849    /// }
1850    /// assert!(map.is_empty());
1851    /// ```
1852    pub fn pop_first(&mut self) -> Option<(T, V)>
1853    where
1854        V: Clone,
1855    {
1856        let entry = self.btree_map.first_entry()?;
1857        // We must remove the entry because the key will change
1858        let (start, end_value) = entry.remove_entry();
1859
1860        self.len -= T::SafeLen::one();
1861        if start == end_value.end {
1862            Some((start, end_value.value))
1863        } else {
1864            let value = end_value.value.clone();
1865            self.btree_map.insert(start.add_one(), end_value);
1866            Some((start, value))
1867        }
1868    }
1869
1870    /// Removes the last value from the set and returns it, if any.
1871    /// The last value is always the maximum value in the set.
1872    ///
1873    /// Often, internally, the value must be cloned.
1874    ///
1875    /// # Examples
1876    ///
1877    /// ```
1878    /// use range_set_blaze::RangeMapBlaze;
1879    ///
1880    /// let mut map = RangeMapBlaze::new();
1881    /// map.insert(1, "a");
1882    /// map.insert(2, "b");
1883    /// while let Some((key, _val)) = map.pop_last() {
1884    ///      assert!(map.iter().all(|(k, _v)| k < key));
1885    /// }
1886    /// assert!(map.is_empty());
1887    /// ```
1888    pub fn pop_last(&mut self) -> Option<(T, V)> {
1889        let mut entry = self.btree_map.last_entry()?;
1890        let start = *entry.key();
1891        self.len -= T::SafeLen::one();
1892        let end = entry.get().end;
1893        if start == end {
1894            let value = entry.remove_entry().1.value;
1895            Some((end, value))
1896        } else {
1897            let value = entry.get().value.clone();
1898            entry.get_mut().end.assign_sub_one();
1899            Some((end, value))
1900        }
1901    }
1902
1903    /// An iterator that visits the ranges and values in the [`RangeMapBlaze`],
1904    ///
1905    /// Also see [`RangeMapBlaze::iter`] and [`RangeMapBlaze::into_range_values`].
1906    ///
1907    /// # Examples
1908    ///
1909    /// ```
1910    /// use range_set_blaze::RangeMapBlaze;
1911    ///
1912    /// let map = RangeMapBlaze::from_iter([(30..=40, "c"), (15..=25, "b"), (10..=20, "a")]);
1913    /// let mut range_values = map.range_values();
1914    /// assert_eq!(range_values.next(), Some((10..=20, &"a")));
1915    /// assert_eq!(range_values.next(), Some((21..=25, &"b")));
1916    /// assert_eq!(range_values.next(), Some((30..=40, &"c")));
1917    /// assert_eq!(range_values.next(), None);
1918    /// ```
1919    ///
1920    /// Values returned by the iterator are returned in ascending order
1921    /// with right-to-left precedence.
1922    ///
1923    /// ```
1924    /// use range_set_blaze::RangeMapBlaze;
1925    ///
1926    /// let map = RangeMapBlaze::from_iter([(10..=20, "a"), (15..=25, "b"), (30..=40, "c")]);
1927    /// let mut range_values = map.range_values();
1928    /// assert_eq!(range_values.next(), Some((10..=14, &"a")));
1929    /// assert_eq!(range_values.next(), Some((15..=25, &"b")));
1930    /// assert_eq!(range_values.next(), Some((30..=40, &"c")));
1931    /// assert_eq!(range_values.next(), None);
1932    /// ```
1933    pub fn range_values(&self) -> RangeValuesIter<'_, T, V> {
1934        RangeValuesIter::new(&self.btree_map)
1935    }
1936
1937    /// An iterator that visits the ranges and values in the [`RangeMapBlaze`]. Double-ended.
1938    ///
1939    /// Also see [`RangeMapBlaze::iter`] and [`RangeMapBlaze::range_values`].
1940    ///
1941    /// # Examples
1942    ///
1943    /// ```
1944    /// extern crate alloc;
1945    /// use alloc::rc::Rc;
1946    /// use range_set_blaze::RangeMapBlaze;
1947    ///
1948    /// let map = RangeMapBlaze::from_iter([(30..=40, "c"), (15..=25, "b"), (10..=20, "a")]);
1949    /// let mut range_values = map.into_range_values();
1950    /// assert_eq!(range_values.next(), Some((10..=20, Rc::new("a"))));
1951    /// assert_eq!(range_values.next(), Some((21..=25, Rc::new("b"))));
1952    /// assert_eq!(range_values.next(), Some((30..=40, Rc::new("c"))));
1953    /// assert_eq!(range_values.next(), None);
1954    /// ```
1955    ///
1956    /// Values returned by the iterator are returned in ascending order
1957    /// with right-to-left precedence.
1958    ///
1959    /// ```
1960    /// # extern crate alloc;
1961    /// use alloc::rc::Rc;
1962    /// use range_set_blaze::RangeMapBlaze;
1963    ///
1964    /// let map = RangeMapBlaze::from_iter([(10..=20, "a"), (15..=25, "b"), (30..=40, "c")]);
1965    /// let mut range_values = map.into_range_values();
1966    /// assert_eq!(range_values.next(), Some((10..=14, Rc::new("a"))));
1967    /// assert_eq!(range_values.next(), Some((15..=25, Rc::new("b"))));
1968    /// assert_eq!(range_values.next(), Some((30..=40, Rc::new("c"))));
1969    /// assert_eq!(range_values.next(), None);
1970    /// ```
1971    pub fn into_range_values(self) -> IntoRangeValuesIter<T, V> {
1972        IntoRangeValuesIter::new(self.btree_map)
1973    }
1974
1975    /// An iterator that visits the ranges in the [`RangeMapBlaze`],
1976    /// i.e., the integers as sorted & disjoint ranges.
1977    ///
1978    /// Also see [`RangeMapBlaze::iter`] and [`RangeMapBlaze::into_range_values`].
1979    ///
1980    /// # Examples
1981    ///
1982    /// ```
1983    /// use range_set_blaze::RangeMapBlaze;
1984    ///
1985    /// let map = RangeMapBlaze::from_iter([(10..=20, "a"), (15..=25, "b"), (30..=40, "c")]);
1986    /// let mut ranges = map.ranges();
1987    /// assert_eq!(ranges.next(), Some(10..=25));
1988    /// assert_eq!(ranges.next(), Some(30..=40));
1989    /// assert_eq!(ranges.next(), None);
1990    /// ```
1991    ///
1992    /// Values returned by the iterator are returned in ascending order
1993    /// with right-to-left precedence.
1994    ///
1995    /// ```
1996    /// use range_set_blaze::RangeMapBlaze;
1997    ///
1998    /// let map = RangeMapBlaze::from_iter([(30..=40, "c"), (15..=25, "b"), (10..=20, "a")]);
1999    /// let mut ranges = map.ranges();
2000    /// assert_eq!(ranges.next(), Some(10..=25));
2001    /// assert_eq!(ranges.next(), Some(30..=40));
2002    /// assert_eq!(ranges.next(), None);
2003    /// ```
2004    pub fn ranges(&self) -> MapRangesIter<'_, T, V> {
2005        MapRangesIter::new(self.btree_map.iter())
2006    }
2007
2008    /// An iterator that visits the ranges in the [`RangeMapBlaze`],
2009    /// i.e., the integers as sorted & disjoint ranges.
2010    ///
2011    /// Also see [`RangeMapBlaze::iter`] and [`RangeMapBlaze::into_range_values`].
2012    ///
2013    /// # Examples
2014    ///
2015    /// ```
2016    /// use range_set_blaze::RangeMapBlaze;
2017    ///
2018    /// let map = RangeMapBlaze::from_iter([(10..=20, "a"), (15..=25, "b"), (30..=40, "c")]);
2019    /// let mut ranges = map.into_ranges();
2020    /// assert_eq!(ranges.next(), Some(10..=25));
2021    /// assert_eq!(ranges.next(), Some(30..=40));
2022    /// assert_eq!(ranges.next(), None);
2023    /// ```
2024    ///
2025    /// Values returned by the iterator are returned in ascending order
2026    /// with right-to-left precedence.
2027    ///
2028    /// ```
2029    /// use range_set_blaze::RangeMapBlaze;
2030    ///
2031    /// let map = RangeMapBlaze::from_iter([(30..=40, "c"), (15..=25, "b"), (10..=20, "a")]);
2032    /// let mut ranges = map.into_ranges();
2033    /// assert_eq!(ranges.next(), Some(10..=25));
2034    /// assert_eq!(ranges.next(), Some(30..=40));
2035    /// assert_eq!(ranges.next(), None);
2036    /// ```
2037    pub fn into_ranges(self) -> MapIntoRangesIter<T, V> {
2038        MapIntoRangesIter::new(self.btree_map.into_iter())
2039    }
2040
2041    /// Returns the number of sorted & disjoint ranges in the set.
2042    ///
2043    /// # Example
2044    ///
2045    /// ```
2046    /// use range_set_blaze::RangeMapBlaze;
2047    ///
2048    /// // We put in three ranges, but they are not sorted & disjoint.
2049    /// let map = RangeMapBlaze::from_iter([(10..=20,"a"), (15..=25,"a"), (30..=40,"b")]);
2050    /// // After RangeMapBlaze sorts & 'disjoint's them, we see two ranges.
2051    /// assert_eq!(map.ranges_len(), 2);
2052    /// assert_eq!(map.to_string(), r#"(10..=25, "a"), (30..=40, "b")"#);
2053    /// ```
2054    #[must_use]
2055    pub fn ranges_len(&self) -> usize {
2056        self.btree_map.len()
2057    }
2058
2059    /// ```
2060    /// use range_set_blaze::RangeMapBlaze;
2061    ///
2062    /// let map = RangeMapBlaze::from_iter([(10u16..=20, "a"), (15..=25, "b"), (30..=40, "c")]);
2063    /// let complement = map.complement_with(&"z");
2064    /// assert_eq!(complement.to_string(), r#"(0..=9, "z"), (26..=29, "z"), (41..=65535, "z")"#);
2065    /// ```
2066    #[must_use]
2067    pub fn complement_with(&self, value: &V) -> Self {
2068        self.ranges()
2069            .complement()
2070            .map(|r| (r, value.clone()))
2071            .collect()
2072    }
2073
2074    // FUTURE BTreeSet some of these as 'const' but it uses unstable. When stable, add them here and elsewhere.
2075
2076    /// Returns the number of sorted & disjoint ranges i
2077    /// n the set.
2078    ///
2079    /// # Example
2080    ///
2081    /// ```
2082    /// use range_set_blaze::RangeMapBlaze;
2083    ///
2084    /// // We put in four ranges, but they are not sorted & disjoint.
2085    /// let map = RangeMapBlaze::from_iter([(28..=35, "c"), (30..=40, "c"), (15..=25, "b"), (10..=20, "a")]);
2086    /// // After RangeMapBlaze sorts & 'disjoint's them, we see three ranges.
2087    /// assert_eq!(map.range_values_len(), 3);
2088    /// assert_eq!(map.to_string(), r#"(10..=20, "a"), (21..=25, "b"), (28..=40, "c")"#);
2089    /// ```
2090    #[must_use]
2091    pub fn range_values_len(&self) -> usize {
2092        self.btree_map.len()
2093    }
2094
2095    /// Retains only the elements specified by the predicate.
2096    ///
2097    /// In other words, remove all pairs `(k, v)` for which `f(&k, &mut v)` returns `false`.
2098    /// The elements are visited in ascending key order.
2099    ///
2100    /// Because if visits every element in every range, it is expensive compared to
2101    /// [`RangeMapBlaze::ranges_retain`].
2102    ///
2103    /// # Examples
2104    ///
2105    /// ```
2106    /// use range_set_blaze::RangeMapBlaze;
2107    ///
2108    /// let mut map: RangeMapBlaze<i32, i32> = (0..8).map(|x| (x, x*10)).collect();
2109    /// // Keep only the elements with even-numbered keys.
2110    /// map.retain(|&k, _| k % 2 == 0);
2111    /// assert!(map.into_iter().eq(vec![(0, 0), (2, 20), (4, 40), (6, 60)]));
2112    /// ```
2113    pub fn retain<F>(&mut self, f: F)
2114    where
2115        F: Fn(&T, &V) -> bool,
2116    {
2117        *self = self.iter().filter(|(k, v)| f(k, v)).collect();
2118    }
2119
2120    /// Retains only the `(range, value)` pairs specified by the predicate.
2121    ///
2122    /// In other words, removes all `(range, value)` pairs for which `f(&range, &value)`
2123    /// returns `false`. The `(range, value)` pairs are visited in ascending range order.
2124    ///
2125    /// # Examples
2126    ///
2127    /// ```
2128    /// use range_set_blaze::RangeMapBlaze;
2129    ///
2130    /// let mut map: RangeMapBlaze<i32, &str> = RangeMapBlaze::from_iter([(0..=3, "low"), (4..=7, "high")]);
2131    /// // Keep only the ranges with a specific value.
2132    /// map.ranges_retain(|range, &value| value == "low");
2133    /// assert_eq!(map, RangeMapBlaze::from_iter([(0..=3, "low")]));
2134    /// ```
2135    pub fn ranges_retain<F>(&mut self, mut f: F)
2136    where
2137        F: FnMut(&RangeInclusive<T>, &V) -> bool,
2138    {
2139        self.btree_map.retain(|start, end_value| {
2140            let range = *start..=end_value.end;
2141            if f(&range, &end_value.value) {
2142                true
2143            } else {
2144                self.len -= T::safe_len(&range);
2145                false
2146            }
2147        });
2148    }
2149}
2150
2151impl<T, V> IntoIterator for RangeMapBlaze<T, V>
2152where
2153    T: Integer,
2154    V: Eq + Clone,
2155{
2156    type Item = (T, V);
2157    type IntoIter = IntoIterMap<T, V>;
2158
2159    /// Gets an iterator for moving out the [`RangeSetBlaze`]'s integer contents.
2160    /// Double-ended.
2161    ///
2162    /// # Examples
2163    ///
2164    /// ```
2165    /// use range_set_blaze::RangeSetBlaze;
2166    ///
2167    /// let set = RangeSetBlaze::from_iter([1, 2, 3, 4]);
2168    ///
2169    /// let v: Vec<_> = set.into_iter().collect();
2170    /// assert_eq!(v, [1, 2, 3, 4]);
2171    ///
2172    /// let set = RangeSetBlaze::from_iter([1, 2, 3, 4]);
2173    /// let v: Vec<_> = set.into_iter().rev().collect();
2174    /// assert_eq!(v, [4, 3, 2, 1]);
2175    /// ```
2176    fn into_iter(self) -> IntoIterMap<T, V> {
2177        IntoIterMap::new(self.btree_map.into_iter())
2178    }
2179}
2180
2181// Implementing `IntoIterator` for `&RangeMapBlaze<T, V>` because BTreeMap does.
2182impl<'a, T: Integer, V: Eq + Clone> IntoIterator for &'a RangeMapBlaze<T, V> {
2183    type IntoIter = IterMap<T, &'a V, RangeValuesIter<'a, T, V>>;
2184    type Item = (T, &'a V);
2185
2186    fn into_iter(self) -> Self::IntoIter {
2187        self.iter()
2188    }
2189}
2190
2191impl<T: Integer, V: Eq + Clone> BitOr<Self> for RangeMapBlaze<T, V> {
2192    /// Unions the contents of two [`RangeMapBlaze`]'s.
2193    ///  
2194    /// This operator has *right precedence*: when overlapping ranges are present,
2195    /// values on the right-hand side take priority over those self.
2196    ///
2197    /// This method is optimized for three usage scenarios:
2198    /// when the left-hand side is much smaller, when the right-hand side is much smaller,
2199    /// and when both sides are of similar size.
2200    ///
2201    /// **Also See:** [Summary of Union and Extend-like Methods](#rangemapblaze-union--and-extend-like-methods).
2202    ///
2203    /// # Examples
2204    /// ```
2205    /// use range_set_blaze::RangeMapBlaze;
2206    /// let a = RangeMapBlaze::from_iter([(1..=2, "a"), (5..=100, "a")]);
2207    /// let b = RangeMapBlaze::from_iter([(2..=6, "b")]);
2208    /// let union = a | b;  // Alternatively, '&a | &b', etc.
2209    /// assert_eq!(union, RangeMapBlaze::from_iter([(1..=1, "a"), (2..=6, "b"), (7..=100, "a")]));
2210    /// ```
2211    type Output = Self;
2212    fn bitor(self, other: Self) -> Self {
2213        let b_len = other.ranges_len();
2214        if b_len == 0 {
2215            return self;
2216        }
2217        let a_len = self.ranges_len();
2218        if a_len == 0 {
2219            return other;
2220        }
2221        if much_greater_than(a_len, b_len) {
2222            return small_b_over_a(self, other);
2223        }
2224        if much_greater_than(b_len, a_len) {
2225            return small_a_under_b(self, other);
2226        }
2227        // Sizes are comparable, use the iterator union
2228        (self.into_range_values() | other.into_range_values()).into_range_map_blaze()
2229    }
2230}
2231
2232impl<T: Integer, V: Eq + Clone> BitOr<&Self> for RangeMapBlaze<T, V> {
2233    /// Unions the contents of two [`RangeMapBlaze`]'s.
2234    ///
2235    /// This operator has *right precedence*: when overlapping ranges are present,
2236    /// values on the right-hand side take priority over those self.
2237    ///
2238    /// This method is optimized for three usage scenarios:
2239    /// when the left-hand side is much smaller, when the right-hand side is much smaller,
2240    /// and when both sides are of similar size.
2241    ///
2242    /// **Also See:** [Summary of Union and Extend-like Methods](#rangemapblaze-union--and-extend-like-methods).
2243    ///
2244    /// # Examples
2245    /// ```
2246    /// use range_set_blaze::RangeMapBlaze;
2247    /// let a = RangeMapBlaze::from_iter([(1..=2, "a"), (5..=100, "a")]);
2248    /// let b = RangeMapBlaze::from_iter([(2..=6, "b")]);
2249    /// let union = a | &b; // Alternatively, 'a | b', etc.
2250    /// assert_eq!(union, RangeMapBlaze::from_iter([(1..=1, "a"), (2..=6, "b"), (7..=100, "a")]));
2251    /// ```
2252    type Output = Self;
2253    fn bitor(self, other: &Self) -> Self {
2254        let b_len = other.ranges_len();
2255        if b_len == 0 {
2256            return self;
2257        }
2258        let a_len = self.ranges_len();
2259        if a_len == 0 {
2260            return other.clone();
2261        }
2262        if much_greater_than(a_len, b_len) {
2263            return small_b_over_a(self, other.clone());
2264        }
2265        if much_greater_than(b_len, a_len) {
2266            return small_a_under_b(self, other.clone());
2267        }
2268
2269        // Sizes are comparable, use the iterator union
2270        (self.range_values() | other.range_values()).into_range_map_blaze()
2271    }
2272}
2273
2274impl<T: Integer, V: Eq + Clone> BitOr<RangeMapBlaze<T, V>> for &RangeMapBlaze<T, V> {
2275    type Output = RangeMapBlaze<T, V>;
2276    /// Unions the contents of two [`RangeMapBlaze`]'s.
2277    ///
2278    /// This operator has *right precedence*: when overlapping ranges are present,
2279    /// values on the right-hand side take priority over those self.
2280    ///
2281    /// This method is optimized for three usage scenarios:
2282    /// when the left-hand side is much smaller, when the right-hand side is much smaller,
2283    /// and when both sides are of similar size.
2284    ///
2285    /// **Also See:** [Summary of Union and Extend-like Methods](#rangemapblaze-union--and-extend-like-methods).
2286    ///
2287    /// # Examples
2288    /// ```
2289    /// use range_set_blaze::RangeMapBlaze;
2290    /// let a = RangeMapBlaze::from_iter([(1..=2, "a"), (5..=100, "a")]);
2291    /// let b = RangeMapBlaze::from_iter([(2..=6, "b")]);
2292    /// let union = &a | b;  // Alternatively, 'a | b', etc.
2293    /// assert_eq!(union, RangeMapBlaze::from_iter([(1..=1, "a"), (2..=6, "b"), (7..=100, "a")]));
2294    /// ```
2295    fn bitor(self, other: RangeMapBlaze<T, V>) -> RangeMapBlaze<T, V> {
2296        let a_len = self.ranges_len();
2297        if a_len == 0 {
2298            return other;
2299        }
2300        let b_len = other.ranges_len();
2301        if b_len == 0 {
2302            return self.clone();
2303        }
2304        if much_greater_than(b_len, a_len) {
2305            return small_a_under_b(self.clone(), other);
2306        }
2307        if much_greater_than(a_len, b_len) {
2308            return small_b_over_a(self.clone(), other);
2309        }
2310        // Sizes are comparable, use the iterator union
2311        (self.range_values() | other.range_values()).into_range_map_blaze()
2312    }
2313}
2314
2315impl<T: Integer, V: Eq + Clone> BitOr<&RangeMapBlaze<T, V>> for &RangeMapBlaze<T, V> {
2316    type Output = RangeMapBlaze<T, V>;
2317    /// Unions the contents of two [`RangeMapBlaze`]'s.
2318    ///
2319    /// This operator has *right precedence*: when overlapping ranges are present,
2320    /// values on the right-hand side take priority over those self.
2321    ///
2322    /// This method is optimized for three usage scenarios:
2323    /// when the left-hand side is much smaller, when the right-hand side is much smaller,
2324    /// and when both sides are of similar size.
2325    ///
2326    /// **Also See:** [Summary of Union and Extend-like Methods](#rangemapblaze-union--and-extend-like-methods).
2327    ///
2328    /// # Examples
2329    /// ```
2330    /// use range_set_blaze::RangeMapBlaze;
2331    /// let a = RangeMapBlaze::from_iter([(1..=2, "a"), (5..=100, "a")]);
2332    /// let b = RangeMapBlaze::from_iter([(2..=6, "b")]);
2333    /// let union = &a | &b; // Alternatively, 'a | b', etc.
2334    /// assert_eq!(union, RangeMapBlaze::from_iter([(1..=1, "a"), (2..=6, "b"), (7..=100, "a")]));
2335    /// ```
2336    fn bitor(self, other: &RangeMapBlaze<T, V>) -> RangeMapBlaze<T, V> {
2337        let a_len = self.ranges_len();
2338        if a_len == 0 {
2339            return other.clone();
2340        }
2341        let b_len = other.ranges_len();
2342        if b_len == 0 {
2343            return self.clone();
2344        }
2345        if much_greater_than(a_len, b_len) {
2346            return small_b_over_a(self.clone(), other.clone());
2347        }
2348        if much_greater_than(b_len, a_len) {
2349            return small_a_under_b(self.clone(), other.clone());
2350        }
2351        // Sizes are comparable, use the iterator union
2352        (self.range_values() | other.range_values()).into_range_map_blaze()
2353    }
2354}
2355
2356map_op!(
2357     BitAnd bitand,
2358    RangeMapBlaze<T, V>,          // RHS concrete type
2359
2360    /// Intersects the contents of two [`RangeMapBlaze`]'s.
2361    ///
2362    /// Either, neither, or both inputs may be borrowed.
2363    ///
2364    /// # Examples
2365    /// ```
2366    /// use range_set_blaze::prelude::*;
2367    ///
2368    /// let a = RangeMapBlaze::from_iter([(1..=2, "a"), (5..=100, "a")]);
2369    /// let b = RangeMapBlaze::from_iter([(2..=6, "b")]);
2370    /// let result = &a & &b; // Alternatively, 'a & b'.
2371    /// assert_eq!(result.to_string(), r#"(2..=2, "b"), (5..=6, "b")"#);
2372    /// ```
2373    "placeholder",
2374
2375    // owned ∩ owned
2376    |a, b| {
2377        b.into_range_values()
2378         .map_and_set_intersection(a.into_ranges())
2379         .into_range_map_blaze()
2380    },
2381
2382    // owned ∩ &borrowed
2383    |a, &b| {
2384        b.range_values()
2385         .map_and_set_intersection(a.into_ranges())
2386         .into_range_map_blaze()
2387    },
2388
2389    // &borrowed ∩ owned
2390    |&a, b| {
2391        b.into_range_values()
2392         .map_and_set_intersection(a.ranges())
2393         .into_range_map_blaze()
2394    },
2395
2396    // &borrowed ∩ &borrowed
2397    |&a, &b| {
2398        b.range_values()
2399         .map_and_set_intersection(a.ranges())
2400         .into_range_map_blaze()
2401    },
2402);
2403
2404map_op!(
2405     BitAnd bitand,
2406    RangeSetBlaze<T>,          // RHS concrete type
2407
2408/// Find the intersection between a [`RangeMapBlaze`] and a [`RangeSetBlaze`]. The result is a new [`RangeMapBlaze`].
2409///
2410/// Either, neither, or both inputs may be borrowed.
2411///
2412/// # Examples
2413/// ```
2414/// use range_set_blaze::prelude::*;
2415///
2416/// let a = RangeMapBlaze::from_iter([(1..=100, "a")]);
2417/// let b = RangeSetBlaze::from_iter([2..=6]);
2418/// let result = &a & &b; // Alternatively, 'a & b'.
2419/// assert_eq!(result.to_string(), r#"(2..=6, "a")"#);
2420/// ```
2421    "placeholder",
2422
2423    // owned ∩ owned
2424    |a, b| {
2425        a.into_range_values()
2426         .map_and_set_intersection(b.into_ranges())
2427         .into_range_map_blaze()
2428    },
2429
2430    // owned ∩ &borrowed
2431    |a, &b| {
2432        a.into_range_values()
2433         .map_and_set_intersection(b.ranges())
2434         .into_range_map_blaze()
2435    },
2436
2437    // &borrowed ∩ owned
2438    |&a, b| {
2439        a.range_values()
2440         .map_and_set_intersection(b.into_ranges())
2441         .into_range_map_blaze()
2442    },
2443
2444    // &borrowed ∩ &borrowed
2445    |&a, &b| {
2446        a.range_values()
2447         .map_and_set_intersection(b.ranges())
2448         .into_range_map_blaze()
2449    },
2450);
2451
2452map_op!(
2453    BitXor bitxor,                           // trait + method name
2454    RangeMapBlaze<T, V>,                     // RHS concrete type
2455
2456/// Symmetric difference the contents of two [`RangeMapBlaze`]'s.
2457///
2458/// Either, neither, or both inputs may be borrowed.
2459///
2460/// # Examples
2461/// ```
2462/// use range_set_blaze::prelude::*;
2463///
2464/// let a = RangeMapBlaze::from_iter([(1..=2, "a"), (5..=100, "a")]);
2465/// let b = RangeMapBlaze::from_iter([(2..=6, "b")]);
2466/// let result = &a ^ &b; // Alternatively, 'a ^ b'.
2467/// assert_eq!(result.to_string(), r#"(1..=1, "a"), (3..=4, "b"), (7..=100, "a")"#);
2468/// ```
2469    "placeholder",
2470
2471    // ── owned ^ owned ────────────────────────────────────────────
2472    |a, b| {
2473        SymDiffIterMap::new2(
2474            a.into_range_values(),
2475            b.into_range_values(),
2476        )
2477        .into_range_map_blaze()
2478    },
2479
2480    // ── owned ^ &borrowed ────────────────────────────────────────
2481    |a, &b| {
2482        SymDiffIterMap::new2(
2483            a.range_values(),
2484            b.range_values(),
2485        )
2486        .into_range_map_blaze()
2487    },
2488
2489    // ── &borrowed ^ owned ────────────────────────────────────────
2490    |&a, b| {
2491        SymDiffIterMap::new2(
2492            a.range_values(),
2493            b.range_values(),
2494        )
2495        .into_range_map_blaze()
2496    },
2497
2498    // ── &borrowed ^ &borrowed ────────────────────────────────────
2499    |&a, &b| {
2500        SymDiffIterMap::new2(
2501            a.range_values(),
2502            b.range_values(),
2503        )
2504        .into_range_map_blaze()
2505    },
2506);
2507
2508map_op!(
2509    Sub sub,                                 // trait + method name
2510    RangeMapBlaze<T, V>,         // RHS concrete type
2511
2512    /// **Difference** of two [`RangeMapBlaze`] values (`a - b`).
2513    ///
2514    /// Either, neither, or both inputs may be borrowed.
2515    ///
2516    /// # Example
2517    /// ```
2518    /// use range_set_blaze::prelude::*;
2519    ///
2520    /// let a = RangeMapBlaze::from_iter([(1..=2, "a"), (5..=100, "a")]);
2521    /// let b = RangeMapBlaze::from_iter([(2..=6, "b")]);
2522    /// let result = &a - &b;                // or `a - b`
2523    /// assert_eq!(result.to_string(),
2524    ///            r#"(1..=1, "a"), (7..=100, "a")"#);
2525    /// ```
2526    "placeholder",
2527
2528    // ── owned − owned ────────────────────────────────────────────
2529    |a, b| {
2530        a.into_range_values()
2531         .map_and_set_difference(b.ranges())
2532         .into_range_map_blaze()
2533    },
2534
2535    // ── owned − &borrowed ────────────────────────────────────────
2536    |a, &b| {
2537        a.into_range_values()
2538         .map_and_set_difference(b.ranges())
2539         .into_range_map_blaze()
2540    },
2541
2542    // ── &borrowed − owned ────────────────────────────────────────
2543    |&a, b| {
2544        a.range_values()
2545         .map_and_set_difference(b.into_ranges())
2546         .into_range_map_blaze()
2547    },
2548
2549    // ── &borrowed − &borrowed ────────────────────────────────────
2550    |&a, &b| {
2551        a.range_values()
2552         .map_and_set_difference(b.ranges())
2553         .into_range_map_blaze()
2554    },
2555);
2556
2557map_op!(
2558    Sub sub,                                 // trait + method name
2559    RangeSetBlaze<T>,         // RHS concrete type
2560
2561/// Find the difference between a [`RangeMapBlaze`] and a [`RangeSetBlaze`]. The result is a new [`RangeMapBlaze`].
2562///
2563/// Either, neither, or both inputs may be borrowed.
2564///
2565/// # Examples
2566/// ```
2567/// use range_set_blaze::prelude::*;
2568///
2569/// let a = RangeMapBlaze::from_iter([(1..=100, "a")]);
2570/// let b = RangeSetBlaze::from_iter([2..=6]);
2571/// let result = &a - &b; // Alternatively, 'a - b'.
2572/// assert_eq!(result.to_string(), r#"(1..=1, "a"), (7..=100, "a")"#);
2573/// ```
2574    "placeholder",
2575
2576    // ── owned − owned ────────────────────────────────────────────
2577    |a, b| {
2578        a.into_range_values()
2579         .map_and_set_difference(b.ranges())
2580         .into_range_map_blaze()
2581    },
2582
2583    // ── owned − &borrowed ────────────────────────────────────────
2584    |a, &b| {
2585        a.into_range_values()
2586         .map_and_set_difference(b.ranges())
2587         .into_range_map_blaze()
2588    },
2589
2590    // ── &borrowed − owned ────────────────────────────────────────
2591    |&a, b| {
2592        a.range_values()
2593         .map_and_set_difference(b.into_ranges())
2594         .into_range_map_blaze()
2595    },
2596
2597    // ── &borrowed − &borrowed ────────────────────────────────────
2598    |&a, &b| {
2599        a.range_values()
2600         .map_and_set_difference(b.ranges())
2601         .into_range_map_blaze()
2602    },
2603);
2604
2605map_unary_op!(
2606    Not not,                                   // trait + method
2607    crate::set::RangeSetBlaze<T>,              // output type
2608
2609    /// Takes the complement of a [`RangeMapBlaze`].
2610    ///
2611    /// Produces a [`RangeSetBlaze`] containing all integers *not* present
2612    /// in the map’s key ranges.
2613    ///
2614    /// # Example
2615    /// ```
2616    /// use range_set_blaze::prelude::*;
2617    /// let map =
2618    ///     RangeMapBlaze::from_iter([(10u8..=20, "a"), (15..=25, "b"),
2619    ///                               (30..=40, "c")]);
2620    /// let complement = !&map;                // or `!map`
2621    /// assert_eq!(complement.to_string(), "0..=9, 26..=29, 41..=255");
2622    /// ```
2623    "placeholder",
2624
2625    // body for &map
2626    |&m| {
2627        m.ranges()
2628         .complement()
2629         .into_range_set_blaze()
2630    }
2631);
2632
2633impl<T, V> Extend<(T, V)> for RangeMapBlaze<T, V>
2634where
2635    T: Integer,
2636    V: Eq + Clone,
2637{
2638    /// Extends the [`RangeMapBlaze`] with the contents of an iterator of integer-value pairs.
2639    ///
2640    /// This method has *right-to-left precedence*: later values in the iterator take priority
2641    /// over earlier ones, matching the behavior of standard `BTreeMap::extend`.
2642    ///
2643    /// Each integer is treated as a singleton range. Adjacent integers with the same value
2644    /// are merged before insertion. For alternatives that skip merging or accept full ranges,
2645    /// see [`RangeMapBlaze::extend_simple`] and [`RangeMapBlaze::extend`].
2646    ///
2647    /// **See:** [Summary of Union and Extend-like Methods](#rangemapblaze-union--and-extend-like-methods).
2648    ///
2649    /// # Examples
2650    /// ```
2651    /// use range_set_blaze::RangeMapBlaze;
2652    /// let mut a = RangeMapBlaze::from_iter([(3, "a"), (4, "e"), (5, "f"), (5, "g")]);
2653    /// a.extend([(1..=4, "b")]);
2654    /// assert_eq!(a, RangeMapBlaze::from_iter([(1..=4, "b"), (5..=5, "g")]));
2655    ///
2656    /// let mut a = RangeMapBlaze::from_iter([(3, "a"), (4, "e"), (5, "f"), (5, "g")]);
2657    /// let mut b = RangeMapBlaze::from_iter([(1..=4, "b")]);
2658    /// a |= b;
2659    /// assert_eq!(a, RangeMapBlaze::from_iter([(1..=4, "b"), (5..=5, "g")]));
2660    /// ```
2661    #[inline]
2662    fn extend<I>(&mut self, iter: I)
2663    where
2664        I: IntoIterator<Item = (T, V)>,
2665    {
2666        let iter = iter.into_iter();
2667
2668        // We gather adjacent values into ranges via UnsortedPriorityMap, but ignore the priority.
2669        for priority in UnsortedPriorityMap::new(iter.map(|(r, v)| (r..=r, Rc::new(v)))) {
2670            let (range, value) = priority.into_range_value();
2671            let value: V = Rc::try_unwrap(value).unwrap_or_else(|_| unreachable!());
2672            self.internal_add(range, value);
2673        }
2674    }
2675}
2676
2677impl<T, V> Extend<(RangeInclusive<T>, V)> for RangeMapBlaze<T, V>
2678where
2679    T: Integer,
2680    V: Eq + Clone,
2681{
2682    /// Extends the [`RangeMapBlaze`] with the contents of an iterator of range-value pairs.
2683    ///
2684    /// This method has *right-to-left precedence* — like `BTreeMap` and all other
2685    /// `RangeMapBlaze` methods.
2686    ///
2687    /// It first merges any adjacent or overlapping ranges with the same value, then adds them one by one.
2688    /// For alternatives that skip merging or that accept integer-value pairs, see
2689    /// [`RangeMapBlaze::extend_simple`] and the `(integer, value)` overload.
2690    ///
2691    /// **See:** [Summary of Union and Extend-like Methods](#rangemapblaze-union--and-extend-like-methods).
2692    /// # Examples
2693    /// ```
2694    /// use range_set_blaze::RangeMapBlaze;
2695    /// let mut a = RangeMapBlaze::from_iter([(1..=4, "a")]);
2696    /// a.extend([(3..=5, "b"), (5..=5, "c")]);
2697    /// assert_eq!(a, RangeMapBlaze::from_iter([(1..=2, "a"), (3..=4, "b"), (5..=5, "c")]));
2698    ///
2699    /// // `extend_simple` is a more efficient for the case where the ranges a likely disjoint.
2700    /// let mut a = RangeMapBlaze::from_iter([(1..=4, "a")]);
2701    /// a.extend_simple([(3..=5, "b"), (5..=5, "c")]);
2702    /// assert_eq!(a, RangeMapBlaze::from_iter([(1..=2, "a"), (3..=4, "b"), (5..=5, "c")]));
2703    ///
2704    /// let mut a = RangeMapBlaze::from_iter([(1..=4, "a")]);
2705    /// let mut b = RangeMapBlaze::from_iter([(3..=5, "b"), (5..=5, "c")]);
2706    /// a |= b;
2707    /// assert_eq!(a, RangeMapBlaze::from_iter([(1..=2, "a"), (3..=4, "b"), (5..=5, "c")]));
2708    /// ```
2709    #[inline]
2710    fn extend<I>(&mut self, iter: I)
2711    where
2712        I: IntoIterator<Item = (RangeInclusive<T>, V)>,
2713    {
2714        let iter = iter.into_iter();
2715
2716        // We gather adjacent values into ranges via UnsortedPriorityMap, but ignore the priority.
2717        for priority in UnsortedPriorityMap::new(iter.map(|(r, v)| (r, Rc::new(v)))) {
2718            let (range, value) = priority.into_range_value();
2719            let value = Rc::try_unwrap(value).unwrap_or_else(|_| unreachable!());
2720            self.internal_add(range, value);
2721        }
2722    }
2723}
2724
2725impl<T, V, const N: usize> From<[(T, V); N]> for RangeMapBlaze<T, V>
2726where
2727    T: Integer,
2728    V: Eq + Clone,
2729{
2730    /// For compatibility with [`BTreeMap`] you may create a [`RangeSetBlaze`] from an array of integers.
2731    ///
2732    /// *For more about constructors and performance, see [`RangeSetBlaze` Constructors](struct.RangeSetBlaze.html#rangesetblaze-constructors).*
2733    ///
2734    /// [`BTreeMap`]: alloc::collections::BTreeMap
2735    ///
2736    /// # Examples
2737    ///
2738    /// ```
2739    /// use range_set_blaze::RangeSetBlaze;
2740    ///
2741    /// let a0 = RangeSetBlaze::from([3, 2, 1, 100, 1]);
2742    /// let a1: RangeSetBlaze<i32> = [3, 2, 1, 100, 1].into();
2743    /// assert!(a0 == a1 && a0.to_string() == "1..=3, 100..=100")
2744    /// ```
2745    fn from(arr: [(T, V); N]) -> Self {
2746        arr.into_iter().collect()
2747    }
2748}
2749
2750// implement Index trait
2751impl<T: Integer, V: Eq + Clone> Index<T> for RangeMapBlaze<T, V> {
2752    type Output = V;
2753
2754    /// Returns a reference to the value corresponding to the supplied key.
2755    ///
2756    /// # Panics
2757    ///
2758    /// Panics if the key is not present in the `BTreeMap`.
2759    #[inline]
2760    #[allow(clippy::manual_assert)] // We use "if...panic!" for coverage auditing.
2761    fn index(&self, index: T) -> &Self::Output {
2762        self.get(index).unwrap_or_else(|| {
2763            panic!("no entry found for key");
2764        })
2765    }
2766}
2767
2768// LATER define value_per_range and into_value_per_range
2769
2770impl<T, V> PartialOrd for RangeMapBlaze<T, V>
2771where
2772    T: Integer,
2773    V: Eq + Clone + Ord,
2774{
2775    /// We define a partial ordering on `RangeMapBlaze`. Following the convention of
2776    /// [`BTreeMap`], the ordering is lexicographic, *not* by subset/superset.
2777    ///
2778    /// [`BTreeMap`]: alloc::collections::BTreeMap
2779    ///
2780    /// # Examples
2781    /// ```
2782    /// use range_set_blaze::prelude::*;
2783    ///
2784    /// let a = RangeMapBlaze::from_iter([(1..=3, "a"), (5..=100, "a")]);
2785    /// let b = RangeMapBlaze::from_iter([(2..=2, "b")] );
2786    /// assert!(a < b); // Lexicographic comparison
2787    /// // More lexicographic comparisons
2788    /// assert!(a <= b);
2789    /// assert!(b > a);
2790    /// assert!(b >= a);
2791    /// assert!(a != b);
2792    /// assert!(a == a);
2793    /// use core::cmp::Ordering;
2794    /// assert_eq!(a.cmp(&b), Ordering::Less);
2795    ///
2796    /// // Floats aren't comparable, but we can convert them to comparable bits.
2797    /// let a = RangeMapBlaze::from_iter([(2..=3, 1.0f32.to_bits()), (5..=100, 2.0f32.to_bits())]);
2798    /// let b = RangeMapBlaze::from_iter([(2..=2, f32::NAN.to_bits())] );
2799    /// assert_eq!(a.partial_cmp(&b), Some(Ordering::Less));
2800    /// ```
2801    #[inline]
2802    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
2803        Some(self.cmp(other))
2804    }
2805}
2806
2807impl<T, V> Ord for RangeMapBlaze<T, V>
2808where
2809    T: Integer,
2810    V: Eq + Clone + Ord,
2811{
2812    /// We define an ordering on `RangeMapBlaze`. Following the convention of
2813    /// [`BTreeMap`], the ordering is lexicographic, *not* by subset/superset.
2814    ///
2815    /// [`BTreeMap`]: alloc::collections::BTreeMap
2816    ///
2817    /// # Examples
2818    /// ```
2819    /// use range_set_blaze::prelude::*;
2820    ///
2821    /// let a = RangeMapBlaze::from_iter([(1..=3, "a"), (5..=100, "a")]);
2822    /// let b = RangeMapBlaze::from_iter([(2..=2, "b")] );
2823    /// assert!(a < b); // Lexicographic comparison
2824    /// // More lexicographic comparisons
2825    /// assert!(a <= b);
2826    /// assert!(b > a);
2827    /// assert!(b >= a);
2828    /// assert!(a != b);
2829    /// assert!(a == a);
2830    /// use core::cmp::Ordering;
2831    /// assert_eq!(a.cmp(&b), Ordering::Less);
2832    ///
2833    /// // Floats aren't comparable, but we can convert them to comparable bits.
2834    /// let a = RangeMapBlaze::from_iter([(2..=3, 1.0f32.to_bits()), (5..=100, 2.0f32.to_bits())]);
2835    /// let b = RangeMapBlaze::from_iter([(2..=2, f32::NAN.to_bits())] );
2836    /// assert_eq!(a.partial_cmp(&b), Some(Ordering::Less));
2837    /// ```
2838    #[inline]
2839    fn cmp(&self, other: &Self) -> Ordering {
2840        // fast by ranges:
2841        let mut a = self.range_values();
2842        let mut b = other.range_values();
2843        let mut a_rx = a.next();
2844        let mut b_rx = b.next();
2845        loop {
2846            // compare Some/None
2847            match (a_rx, &b_rx) {
2848                (Some(_), None) => return Ordering::Greater,
2849                (None, Some(_)) => return Ordering::Less,
2850                (None, None) => return Ordering::Equal,
2851                (Some((a_r, a_v)), Some((b_r, b_v))) => {
2852                    // if tie, compare starts
2853                    match a_r.start().cmp(b_r.start()) {
2854                        Ordering::Greater => return Ordering::Greater,
2855                        Ordering::Less => return Ordering::Less,
2856                        Ordering::Equal => { /* keep going */ }
2857                    }
2858
2859                    // if tie, compare values
2860                    match a_v.cmp(b_v) {
2861                        Ordering::Less => return Ordering::Less,
2862                        Ordering::Greater => return Ordering::Greater,
2863                        Ordering::Equal => { /* keep going */ }
2864                    }
2865
2866                    // if tie, compare ends
2867                    match a_r.end().cmp(b_r.end()) {
2868                        Ordering::Less => {
2869                            a_rx = a.next();
2870                            b_rx = Some(((*a_r.end()).add_one()..=*b_r.end(), b_v));
2871                        }
2872                        Ordering::Greater => {
2873                            a_rx = Some(((*b_r.end()).add_one()..=*a_r.end(), a_v));
2874                            b_rx = b.next();
2875                        }
2876                        Ordering::Equal => {
2877                            a_rx = a.next();
2878                            b_rx = b.next();
2879                        }
2880                    }
2881                }
2882            }
2883        }
2884    }
2885}
2886
2887impl<T: Integer, V: Eq + Clone> Eq for RangeMapBlaze<T, V> {}
2888
2889impl<T: Integer, V: Eq + Clone> BitOrAssign<&Self> for RangeMapBlaze<T, V> {
2890    /// Adds the contents of another [`RangeMapBlaze`] to this one.
2891    ///
2892    /// This operator has *right precedence*: when overlapping ranges are present,
2893    /// values on the right-hand side take priority over those self.
2894    ///
2895    /// To get *left precedence*, swap the operands.
2896    ///
2897    /// This method is optimized for three usage scenarios:
2898    /// when the left-hand side is much smaller, when the right-hand side is much smaller,
2899    /// and when both sides are of similar size
2900    ///
2901    /// **Also See:** [Summary of Union and Extend-like Methods](#rangemapblaze-union--and-extend-like-methods).
2902    ///
2903    /// # Examples
2904    /// ```
2905    /// use range_set_blaze::RangeMapBlaze;
2906    /// let mut a = RangeMapBlaze::from_iter([(3, "a"), (4, "e"), (5, "f"), (5, "g")]);
2907    /// let mut b = RangeMapBlaze::from_iter([(1..=4, "b")]);
2908    /// a |= &b;
2909    /// assert_eq!(a, RangeMapBlaze::from_iter([(1..=4, "b"), (5..=5, "g")]));
2910    /// ```
2911    fn bitor_assign(&mut self, other: &Self) {
2912        let original_self = mem::take(self); // Take ownership of self
2913        *self = original_self | other; // Use the union operator to combine
2914    }
2915}
2916
2917impl<T: Integer, V: Eq + Clone> BitOrAssign<Self> for RangeMapBlaze<T, V> {
2918    /// Adds the contents of another [`RangeMapBlaze`] to this one.
2919    ///
2920    /// This operator has *right precedence*: when overlapping ranges are present,
2921    /// values on the right-hand side take priority over those self.
2922    /// To get *left precedence*, swap the operands.
2923    ///
2924    /// This method is optimized for three usage scenarios:
2925    /// when the left-hand side is much smaller, when the right-hand side is much smaller,
2926    /// and when both sides are of similar size
2927    ///
2928    /// **Also See:** [Summary of Union and Extend-like Methods](#rangemapblaze-union--and-extend-like-methods).
2929    ///
2930    /// # Examples
2931    /// ```
2932    /// use range_set_blaze::RangeMapBlaze;
2933    /// let mut a = RangeMapBlaze::from_iter([(3, "a"), (4, "e"), (5, "f"), (5, "g")]);
2934    /// let mut b = RangeMapBlaze::from_iter([(1..=4, "b")]);
2935    /// a |= &b;
2936    /// assert_eq!(a, RangeMapBlaze::from_iter([(1..=4, "b"), (5..=5, "g")]));
2937    /// ```
2938    fn bitor_assign(&mut self, other: Self) {
2939        *self = mem::take(self) | other;
2940    }
2941}
2942
2943#[inline]
2944fn much_greater_than(a_len: usize, b_len: usize) -> bool {
2945    let a_len_log2_plus_one: usize = a_len
2946        .checked_ilog2()
2947        .map_or(0, |log| log.try_into().expect("log2 fits usize"))
2948        + 1;
2949    b_len * a_len_log2_plus_one < STREAM_OVERHEAD * a_len + b_len
2950}
2951
2952#[inline]
2953fn small_b_over_a<T: Integer, V: Eq + Clone>(
2954    mut a: RangeMapBlaze<T, V>,
2955    b: RangeMapBlaze<T, V>,
2956) -> RangeMapBlaze<T, V> {
2957    debug_assert!(much_greater_than(a.ranges_len(), b.ranges_len()));
2958    for (start, end_value) in b.btree_map {
2959        a.internal_add(start..=(end_value.end), end_value.value);
2960    }
2961    a
2962}
2963
2964#[inline]
2965fn small_a_under_b<T: Integer, V: Eq + Clone>(
2966    a: RangeMapBlaze<T, V>,
2967    mut b: RangeMapBlaze<T, V>,
2968) -> RangeMapBlaze<T, V> {
2969    debug_assert!(much_greater_than(b.ranges_len(), a.ranges_len()));
2970    let difference = a - &b;
2971    b.extend_simple(
2972        difference
2973            .btree_map
2974            .into_iter()
2975            .map(|(start, v)| (start..=v.end, v.value)),
2976    );
2977    b
2978}