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