Skip to main content

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<R>(&mut self, range: R, value: V) -> bool
1095    where
1096        R: RangeBounds<T>,
1097    {
1098        let len_before = self.len;
1099        let (start, end) = extract_range(range);
1100        self.internal_add(start..=end, value);
1101        self.len != len_before
1102    }
1103
1104    /// If the set contains an element equal to the value, removes it from the
1105    /// set and drops it. Returns whether such an element was present.
1106    ///
1107    /// # Examples
1108    ///
1109    /// ```
1110    /// use range_set_blaze::RangeMapBlaze;
1111    ///
1112    /// let mut map = RangeMapBlaze::new();
1113    /// map.insert(1, "a");
1114    /// assert_eq!(map.remove(1), Some("a"));
1115    /// assert_eq!(map.remove(1), None);
1116    /// ```
1117    #[allow(clippy::missing_panics_doc)]
1118    pub fn remove(&mut self, key: T) -> Option<V> {
1119        // The code can have only one mutable reference to self.btree_map.
1120
1121        // Find that range that might contain the key
1122        let (start_ref, end_value_mut) = self.btree_map.range_mut(..=key).next_back()?;
1123        let end = end_value_mut.end;
1124
1125        // If the key is not in the range, we're done
1126        if end < key {
1127            return None;
1128        }
1129        let start = *start_ref;
1130        debug_assert!(start <= key, "Real Assert: start <= key");
1131
1132        // It's in the range.
1133        self.len -= <T::SafeLen>::one();
1134
1135        let value = if start == key {
1136            self.btree_map
1137                .remove(&start)
1138                .expect("Real Assert: There will always be a start")
1139                .value
1140        } else {
1141            debug_assert!(start < key, "Real Assert: start < key");
1142            // This range will now end at key-1.
1143            end_value_mut.end = key.sub_one();
1144            end_value_mut.value.clone()
1145        };
1146
1147        // If needed, add a new range after key
1148        if key < end {
1149            self.btree_map.insert(
1150                key.add_one(),
1151                EndValue {
1152                    end,
1153                    value: value.clone(),
1154                },
1155            );
1156        }
1157
1158        Some(value)
1159    }
1160
1161    /// Splits the collection into two at the value. Returns a new collection
1162    /// with all elements greater than or equal to the value.
1163    ///
1164    /// # Examples
1165    ///
1166    /// Basic usage:
1167    ///
1168    /// ```
1169    /// use range_set_blaze::RangeMapBlaze;
1170    ///
1171    /// let mut a = RangeMapBlaze::new();
1172    /// a.insert(1, "a");
1173    /// a.insert(2, "b");
1174    /// a.insert(3, "c");
1175    /// a.insert(17, "d");
1176    /// a.insert(41, "e");
1177    ///
1178    /// let b = a.split_off(3);
1179    ///
1180    /// assert_eq!(a, RangeMapBlaze::from_iter([(1..=1, "a"), (2..=2, "b")]));
1181    /// assert_eq!(b, RangeMapBlaze::from_iter([(3..=3, "c"), (17..=17, "d"), (41..=41, "e")]));
1182    /// ```
1183    #[must_use]
1184    pub fn split_off(&mut self, key: T) -> Self {
1185        let old_len = self.len;
1186        let old_btree_len = self.btree_map.len();
1187        let mut new_btree = self.btree_map.split_off(&key);
1188        let Some(last_entry) = self.btree_map.last_entry() else {
1189            // Left is empty
1190            self.len = T::SafeLen::zero();
1191            return Self {
1192                btree_map: new_btree,
1193                len: old_len,
1194            };
1195        };
1196
1197        let end_value = last_entry.get();
1198        let end = end_value.end;
1199        if end < key {
1200            // The split is clean
1201            let (a_len, b_len) = self.two_element_lengths(old_btree_len, &new_btree, old_len);
1202            self.len = a_len;
1203            return Self {
1204                btree_map: new_btree,
1205                len: b_len,
1206            };
1207        }
1208
1209        // The split is not clean, so we must move some keys from the end of self to the start of b.
1210        let value = end_value.value.clone();
1211        last_entry.into_mut().end = key.sub_one();
1212        new_btree.insert(key, EndValue { end, value });
1213        let (a_len, b_len) = self.two_element_lengths(old_btree_len, &new_btree, old_len);
1214        self.len = a_len;
1215        Self {
1216            btree_map: new_btree,
1217            len: b_len,
1218        }
1219    }
1220
1221    // Find the len of the smaller btree_map and then the element len of self & b.
1222    fn two_element_lengths(
1223        &self,
1224        old_btree_len: usize,
1225        new_btree: &BTreeMap<T, EndValue<T, V>>,
1226        mut old_len: <T as Integer>::SafeLen,
1227    ) -> (<T as Integer>::SafeLen, <T as Integer>::SafeLen) {
1228        if old_btree_len / 2 < new_btree.len() {
1229            let a_len = Self::btree_map_len(&self.btree_map);
1230            old_len -= a_len;
1231            (a_len, old_len)
1232        } else {
1233            let b_len = Self::btree_map_len(new_btree);
1234            old_len -= b_len;
1235            (old_len, b_len)
1236        }
1237    }
1238
1239    fn btree_map_len(btree_map: &BTreeMap<T, EndValue<T, V>>) -> T::SafeLen {
1240        btree_map.iter().fold(
1241            <T as Integer>::SafeLen::zero(),
1242            |acc, (start, end_value)| acc + T::safe_len(&(*start..=end_value.end)),
1243        )
1244    }
1245
1246    #[inline]
1247    fn has_gap(end_before: T, start: T) -> bool {
1248        end_before
1249            .checked_add_one()
1250            .is_some_and(|end_before_succ| end_before_succ < start)
1251    }
1252
1253    #[cfg(never)]
1254    // TODO: Look at other TODOs before enabling this.
1255    // #![cfg_attr(feature = "cursor", feature(btree_cursors, new_range_api))]
1256    // #[cfg(feature = "cursor")]
1257    //  use core::{cmp::min, range::Bound};
1258    #[inline]
1259    fn adjust_touching_for_insert(
1260        &mut self,
1261        stored_start: T,
1262        stored_end_value: EndValue<T, V>,
1263        range: &mut RangeInclusive<T>,
1264        value: &V,
1265    ) {
1266        let stored_value = &stored_end_value.value;
1267        let stored_end = stored_end_value.end;
1268
1269        // ── 1. Same value → coalesce completely ──────────────────────────────
1270        if stored_value == value {
1271            let new_start = min(*range.start(), stored_start);
1272            let new_end = max(*range.end(), stored_end);
1273            *range = new_start..=new_end;
1274
1275            self.len -= T::safe_len(&(stored_start..=stored_end));
1276            self.btree_map.remove(&stored_start);
1277            return;
1278        }
1279
1280        // ── 2. Different value → may need to split ───────────────────────────
1281        let overlaps = stored_start <= *range.end() && stored_end >= *range.start();
1282
1283        if overlaps {
1284            // Remove the overlapping range first.
1285            self.len -= T::safe_len(&(stored_start..=stored_end));
1286            self.btree_map.remove(&stored_start);
1287
1288            // Left residual slice
1289            if stored_start < *range.start() {
1290                let left_end = range.start().sub_one(); // TODO are we sure this won't underflow?
1291                self.len += T::safe_len(&(stored_start..=left_end));
1292                self.btree_map.insert(
1293                    stored_start,
1294                    EndValue {
1295                        end: left_end,
1296                        value: stored_value.clone(),
1297                    },
1298                );
1299            }
1300
1301            // Right residual slice
1302            if stored_end > *range.end() {
1303                let right_start = range.end().add_one();
1304                self.len += T::safe_len(&(right_start..=stored_end));
1305                self.btree_map.insert(
1306                    right_start,
1307                    EndValue {
1308                        end: stored_end,
1309                        value: stored_end_value.value, // already owned
1310                    },
1311                );
1312            }
1313        }
1314        // Otherwise: no overlap → keep ranges as they are.
1315    }
1316
1317    #[cfg(never)]
1318    // For benchmarking, based on https://github.com/jeffparsons/rangemap's `insert` method.
1319    pub(crate) fn internal_add(&mut self, mut range: RangeInclusive<T>, value: V) {
1320        use core::ops::Bound::{Included, Unbounded}; // TODO: Move to the top
1321
1322        let start = *range.start();
1323        let end = *range.end();
1324
1325        // === case: empty
1326        if end < start {
1327            return;
1328        }
1329
1330        // Walk *backwards* from the first stored range whose start ≤ `start`.
1331        //      Take the nearest two so we can look at “before” and “before-before”.
1332        let mut candidates = self
1333            .btree_map
1334            .range::<T, _>((Unbounded, Included(&start))) // ..= start
1335            .rev()
1336            .take(2)
1337            .filter(|(_stored_start, stored_end_value)| {
1338                // TODO use saturation arithmetic to avoid underflow
1339                let end = stored_end_value.end;
1340                end >= start || (start != T::min_value() && end >= start.sub_one())
1341            });
1342
1343        if let Some(mut candidate) = candidates.next() {
1344            // Or the one before it if both cases described above exist.
1345            if let Some(another_candidate) = candidates.next() {
1346                candidate = another_candidate;
1347            }
1348
1349            let stored_start: T = *candidate.0;
1350            let stored_end_value: EndValue<T, V> = candidate.1.clone();
1351            self.adjust_touching_for_insert(
1352                stored_start,
1353                stored_end_value,
1354                &mut range, // `end` is the current (possibly growing) tail
1355                &value,
1356            );
1357        }
1358
1359        // let range = &mut range; // &mut RangeInclusive<T>
1360
1361        loop {
1362            // first range whose start ≥ new_range.start()
1363            let next_entry = self
1364                .btree_map
1365                .range::<T, _>((Included(range.start()), Unbounded))
1366                .next();
1367
1368            let Some((&stored_start, stored_end_value)) = next_entry else {
1369                break; // nothing more
1370            };
1371
1372            let second_last_possible_start = *range.end();
1373            let maybe_latest_start = if second_last_possible_start == T::max_value() {
1374                None
1375            } else {
1376                Some(second_last_possible_start.add_one())
1377            };
1378
1379            if maybe_latest_start.map_or(false, |latest| stored_start > latest) {
1380                break; // beyond end + 1
1381            }
1382            if let Some(latest) = maybe_latest_start {
1383                if stored_start == latest && stored_end_value.value != value {
1384                    break; // touches but diff value
1385                }
1386            }
1387
1388            // clone so we can mutate the map in the helper
1389            let end_value_clone = stored_end_value.clone();
1390
1391            self.adjust_touching_for_insert(stored_start, end_value_clone, &mut range, &value);
1392
1393            // loop again; `new_range` might have grown on the right
1394        }
1395
1396        let start_key = *range.start();
1397        let end_key = *range.end();
1398        // self.len += T::safe_len(&(start_key..=end_key));
1399        self.btree_map.insert(
1400            start_key,
1401            EndValue {
1402                end: end_key,
1403                value,
1404            },
1405        );
1406
1407        debug_assert!(self.len == self.len_slow());
1408    }
1409
1410    #[cfg(never)]
1411    // #[cfg(feature = "cursor")]
1412    pub(crate) fn internal_add(&mut self, mut range: RangeInclusive<T>, value: V) {
1413        // Based on https://github.com/jeffparsons/rangemap's `insert` method but with cursor's added
1414        use core::ops::Bound::{Included, Unbounded};
1415        use std::collections::btree_map::CursorMut;
1416
1417        let start = *range.start();
1418        let end = *range.end();
1419
1420        // === case: empty
1421        if end < start {
1422            return;
1423        }
1424
1425        // Walk *backwards* from the first stored range whose start ≤ `start`.
1426        //      Take the nearest two so we can look at “before” and “before-before”.
1427        let mut candidates = self
1428            .btree_map
1429            .range::<T, _>((Unbounded, Included(&start))) // ..= start
1430            .rev()
1431            .take(2)
1432            .filter(|(_stored_start, stored_end_value)| {
1433                let end = stored_end_value.end;
1434                end >= start || (start != T::min_value() && end >= start.sub_one())
1435            });
1436
1437        if let Some(mut candidate) = candidates.next() {
1438            // Or the one before it if both cases described above exist.
1439            if let Some(another_candidate) = candidates.next() {
1440                candidate = another_candidate;
1441            }
1442
1443            let stored_start: T = *candidate.0;
1444            let stored_end_value: EndValue<T, V> = candidate.1.clone();
1445            self.adjust_touching_for_insert(
1446                stored_start,
1447                stored_end_value,
1448                &mut range, // `end` is the current (possibly growing) tail
1449                &value,
1450            );
1451        }
1452        // keep looping until we hit the stop window
1453        loop {
1454            // create a fresh cursor _for this iteration only_
1455            let mut cur: CursorMut<'_, T, EndValue<T, V>> = self
1456                .btree_map
1457                .lower_bound_mut(Bound::Included(range.start()));
1458
1459            let Some(peeked) = cur.peek_next() else {
1460                break;
1461            };
1462            let (&stored_start, maybe_end_value) = peeked;
1463
1464            let last_ok = *range.end();
1465            if last_ok == T::max_value() {
1466                if stored_start > last_ok {
1467                    break;
1468                }
1469            } else {
1470                let latest = last_ok.add_one();
1471                if stored_start > latest {
1472                    break;
1473                }
1474                if stored_start == latest && maybe_end_value.value != value {
1475                    break;
1476                }
1477            }
1478
1479            // now clone and remove
1480            let cloned = maybe_end_value.clone();
1481            cur.remove_next();
1482
1483            // now we can call any &mut-self helper safely
1484            self.adjust_touching_for_insert(stored_start, cloned, &mut range, &value);
1485        }
1486
1487        let start_key = *range.start();
1488        let end_key = *range.end();
1489
1490        self.btree_map.insert(
1491            start_key,
1492            EndValue {
1493                end: end_key,
1494                value, // moves `value`
1495            },
1496        );
1497        self.len += T::safe_len(&(start_key..=end_key));
1498
1499        debug_assert!(self.len == self.len_slow());
1500    }
1501
1502    // https://stackoverflow.com/questions/49599833/how-to-find-next-smaller-key-in-btreemap-btreeset
1503    // https://stackoverflow.com/questions/35663342/how-to-modify-partially-remove-a-range-from-a-btreemap
1504    // LATER might be able to shorten code by combining cases
1505    // FUTURE: would be nice of BTreeMap to have a partition_point function that returns two iterators
1506    #[allow(clippy::too_many_lines)]
1507    #[allow(clippy::cognitive_complexity)]
1508    pub(crate) fn internal_add(&mut self, range: RangeInclusive<T>, value: V) {
1509        let (start, end) = range.clone().into_inner();
1510
1511        // === case: empty
1512        if end < start {
1513            return;
1514        }
1515        let mut before_iter = self.btree_map.range_mut(..=start).rev();
1516
1517        // === case: no before
1518        let Some((start_before, end_value_before)) = before_iter.next() else {
1519            // no before, so must be first
1520            self.internal_add2(&range, value);
1521            // You must return or break out of the current block after handling the failure case
1522            return;
1523        };
1524
1525        let start_before = *start_before;
1526        let end_before = end_value_before.end;
1527
1528        // === case: gap between before and new
1529        if Self::has_gap(end_before, start) {
1530            // there is a gap between the before and the new
1531            // ??? aa...
1532            self.internal_add2(&range, value);
1533            return;
1534        }
1535
1536        let before_contains_new = end_before >= end;
1537        let same_value = value == end_value_before.value;
1538
1539        // === case: same value and before contains new
1540        if before_contains_new && same_value {
1541            // same value, so do nothing
1542            // AAAAA
1543            //  aaa
1544            return;
1545        }
1546
1547        // === case: same value and new extends beyond before
1548        if !before_contains_new && same_value {
1549            // same value, so just extend the before
1550            // AAA
1551            //  aaaa...
1552            self.len += T::safe_len(&(end_before..=end.sub_one()));
1553            debug_assert!(start_before <= end); // real assert
1554            end_value_before.end = end;
1555            self.delete_extra(&(start_before..=end));
1556            return;
1557        }
1558
1559        // Thus, the values are different
1560
1561        let same_start = start == start_before;
1562
1563        // === case: new goes beyond before and different values
1564        if !before_contains_new && !same_value && same_start {
1565            // Thus, values are different, before contains new, and they start together
1566
1567            let interesting_before_before = match before_iter.next() {
1568                Some(bb) if bb.1.end.add_one() == start && bb.1.value == value => Some(bb),
1569                _ => None,
1570            };
1571
1572            // === case: values are different, new extends beyond before, and they start together and an interesting before-before
1573            // an interesting before-before: something before before, touching and with the same value as new
1574            if let Some(bb) = interesting_before_before {
1575                debug_assert!(!before_contains_new && !same_value && same_start);
1576
1577                // AABBBB
1578                //   aaaaaaa
1579                // AAAAAAAAA
1580                self.len += T::safe_len(&(bb.1.end.add_one()..=end));
1581                let bb_start = *bb.0;
1582                debug_assert!(bb_start <= end); // real assert
1583                bb.1.end = end;
1584                self.delete_extra(&(bb_start..=end));
1585                return;
1586            }
1587
1588            // === case: values are different, they start together but new ends later and no interesting before-before
1589            debug_assert!(!same_value && same_start && interesting_before_before.is_none());
1590
1591            // ^BBBB
1592            //  aaaaaaa
1593            // ^AAAAAAA
1594            debug_assert!(end_before < end); // real assert
1595            self.len += T::safe_len(&(end_before.add_one()..=end));
1596            end_value_before.end = end;
1597            end_value_before.value = value;
1598            self.delete_extra(&range);
1599            return;
1600        }
1601        if !before_contains_new && !same_value && !same_start {
1602            // different value, so must trim the before and then insert the new
1603            // BBB
1604            //  aaaa...
1605            if start <= end_before {
1606                self.len -= T::safe_len(&(start..=end_before));
1607                debug_assert!(start_before <= start.sub_one()); // real assert
1608                end_value_before.end = start.sub_one(); // safe because !same_start
1609            }
1610            self.internal_add2(&range, value);
1611            return;
1612        }
1613
1614        // Thus, the values are different and before contains new
1615        debug_assert!(before_contains_new && !same_value);
1616
1617        let same_end = end == end_before;
1618
1619        // === case: values are different and new is surrounded by before
1620        if !same_start && !same_end {
1621            debug_assert!(before_contains_new && !same_value);
1622            debug_assert!(start_before < start && end < end_before);
1623            // Different values still ...
1624            // The new starts later and ends before,
1625            // BBBBBB
1626            //   aaa
1627            // BBAAAB
1628            //  so trim the before and then insert two
1629            debug_assert!(start_before <= start.sub_one()); // real assert
1630            end_value_before.end = start.sub_one();
1631            let before_value = end_value_before.value.clone();
1632            debug_assert!(start <= end); // real assert
1633            self.btree_map.insert(start, EndValue { end, value });
1634            debug_assert!(end.add_one() <= end_before); // real assert
1635            self.btree_map.insert(
1636                end.add_one(),
1637                EndValue {
1638                    end: end_before,
1639                    value: before_value,
1640                },
1641            );
1642            return;
1643        }
1644
1645        // === case: values are different, new instead of before and they end together
1646        if !same_start && same_end {
1647            debug_assert!(before_contains_new && !same_value);
1648            debug_assert!(start_before < start && end == end_before);
1649            // Different values still ...
1650            // The new starts later but they end together,
1651            // BBBBB???
1652            //   aaa
1653            // BBAAA???
1654            //  so trim the before and then insert the new.
1655            debug_assert!(start_before <= start.sub_one()); // real assert
1656            end_value_before.end = start.sub_one();
1657            debug_assert!(start <= end); // real assert
1658            self.btree_map.insert(start, EndValue { end, value });
1659            self.delete_extra(&(start..=end));
1660            return;
1661        }
1662
1663        // Thus, values are different, before contains new, and they start together
1664
1665        let interesting_before_before = match before_iter.next() {
1666            Some(bb) if bb.1.end.add_one() == start && bb.1.value == value => Some(bb),
1667            _ => None,
1668        };
1669
1670        // === case: values are different, before contains new, and they start together and an interesting before-before
1671        // an interesting before-before: something before before, touching and with the same value as new
1672        if let Some(bb) = interesting_before_before {
1673            debug_assert!(before_contains_new && !same_value && same_start);
1674
1675            // AABBBB???
1676            //   aaaa
1677            // AAAAAA???
1678            self.len += T::safe_len(&(bb.1.end.add_one()..=end));
1679            let bb_start = *bb.0;
1680            debug_assert!(bb_start <= end); // real assert
1681            bb.1.end = end;
1682            self.delete_extra(&(bb_start..=end));
1683            return;
1684        }
1685
1686        // === case: values are different, they start and end together and no interesting before-before
1687        if same_end {
1688            debug_assert!(!same_value && same_start && interesting_before_before.is_none());
1689
1690            // ^BBBB???
1691            //  aaaa
1692            // ^AAAA???
1693            end_value_before.value = value;
1694            self.delete_extra(&(start_before..=end));
1695            return;
1696        }
1697
1698        // === case: values are different, they start together, new ends first, and no interesting before-before
1699        {
1700            debug_assert!(
1701                !same_value
1702                    && same_start
1703                    && end < end_before
1704                    && interesting_before_before.is_none()
1705            );
1706
1707            // ^BBBB
1708            //  aaa
1709            // ^AAAB
1710            let value_before = core::mem::replace(&mut end_value_before.value, value);
1711            debug_assert!(start_before <= end); // real assert
1712            end_value_before.end = end;
1713            debug_assert!(end.add_one() <= end_before); // real assert
1714            self.btree_map.insert(
1715                end.add_one(),
1716                EndValue {
1717                    end: end_before,
1718                    value: value_before,
1719                },
1720            );
1721        }
1722    }
1723
1724    #[inline]
1725    fn internal_add2(&mut self, internal_range: &RangeInclusive<T>, value: V) {
1726        let (start, end) = internal_range.clone().into_inner();
1727        let end_value = EndValue { end, value };
1728        debug_assert!(start <= end_value.end); // real assert
1729        let was_there = self.btree_map.insert(start, end_value);
1730        debug_assert!(was_there.is_none()); // no range with the same start should be there
1731        self.delete_extra(internal_range);
1732        self.len += T::safe_len(internal_range);
1733    }
1734
1735    /// Returns the number of elements in the set.
1736    ///
1737    /// The number is allowed to be very, very large.
1738    ///
1739    /// # Examples
1740    ///
1741    /// ```
1742    /// use range_set_blaze::prelude::*;
1743    ///
1744    /// let mut a = RangeMapBlaze::new();
1745    /// assert_eq!(a.len(), 0u64);
1746    /// a.insert(1, "a");
1747    /// assert_eq!(a.len(), 1u64);
1748    ///
1749    /// let a = RangeMapBlaze::from_iter([
1750    ///     (-170_141_183_460_469_231_731_687_303_715_884_105_728_i128..=10, "a"),
1751    ///     (-10..=170_141_183_460_469_231_731_687_303_715_884_105_726, "a")]);
1752    /// assert_eq!(
1753    ///     a.len(),
1754    ///     UIntPlusOne::UInt(340282366920938463463374607431768211455)
1755    /// );
1756    /// ```
1757    #[must_use]
1758    pub const fn len(&self) -> <T as Integer>::SafeLen {
1759        self.len
1760    }
1761
1762    /// Makes a new, empty [`RangeMapBlaze`].
1763    ///
1764    /// # Examples
1765    ///
1766    /// ```
1767    /// # #![allow(unused_mut)]
1768    /// use range_set_blaze::RangeMapBlaze;
1769    ///
1770    /// let mut map = RangeMapBlaze::new();
1771    ///
1772    /// // entries can now be inserted into the empty map
1773    /// map.insert(1, "a");
1774    /// assert_eq!(map[1], "a");
1775    /// ```
1776    #[inline]
1777    #[must_use]
1778    pub fn new() -> Self {
1779        Self {
1780            btree_map: BTreeMap::new(),
1781            len: <T as Integer>::SafeLen::zero(),
1782        }
1783    }
1784
1785    /// Extends the [`RangeMapBlaze`] with an iterator of `(range, value)` pairs without pre-merging.
1786    ///
1787    /// Unlike [`RangeMapBlaze::extend`], this method does **not** merge adjacent or overlapping ranges
1788    /// before inserting. Each `(range, value)` pair is added as-is, making it faster when the input
1789    /// is already well-structured or disjoint.
1790    ///
1791    /// This method has *right-to-left precedence*: later ranges in the iterator overwrite earlier ones.
1792    ///
1793    /// **See:** [Summary of Union and Extend-like Methods](#rangemapblaze-union--and-extend-like-methods).
1794    ///
1795    /// # Examples
1796    /// ```
1797    /// use range_set_blaze::RangeMapBlaze;
1798    /// let mut a = RangeMapBlaze::from_iter([(1..=4, "a")]);
1799    /// a.extend_simple([(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([(1..=4, "a")]);
1803    /// a.extend([(3..=5, "b"), (5..=5, "c")]);
1804    /// assert_eq!(a, RangeMapBlaze::from_iter([(1..=2, "a"), (3..=4, "b"), (5..=5, "c")]));
1805    ///
1806    /// let mut a = RangeMapBlaze::from_iter([(3..=5, "b"), (5..=5, "c")]);
1807    /// let mut b = RangeMapBlaze::from_iter([(1..=4, "a")]);
1808    /// a |= b;
1809    /// assert_eq!(a, RangeMapBlaze::from_iter([(1..=4, "a"), (5..=5, "c")]));
1810    /// ```
1811    pub fn extend_simple<I>(&mut self, iter: I)
1812    where
1813        I: IntoIterator<Item = (RangeInclusive<T>, V)>,
1814    {
1815        let iter = iter.into_iter();
1816
1817        for (range, value) in iter {
1818            self.internal_add(range, value);
1819        }
1820    }
1821
1822    /// Extends the [`RangeMapBlaze`] with the contents of an owned [`RangeMapBlaze`].
1823    ///
1824    /// This method follows standard *right-to-left precedence*: If the maps contain overlapping ranges,
1825    /// values from `other` will overwrite those in `self`.
1826    ///
1827    /// Compared to [`RangeMapBlaze::extend_with`], this method can be more efficient because it can
1828    /// consume the internal data structures of `other` directly, avoiding some cloning.
1829    ///
1830    /// **See:** [Summary of Union and Extend-like Methods](#rangemapblaze-union--and-extend-like-methods).
1831    ///
1832    /// # Examples
1833    ///
1834    /// ```
1835    /// use range_set_blaze::RangeMapBlaze;
1836    /// let mut a = RangeMapBlaze::from_iter([(1..=4, "a")]);
1837    /// let mut b = RangeMapBlaze::from_iter([(3..=4, "b"), (5..=5, "c")]);
1838    /// a.extend_from(b);
1839    /// assert_eq!(a, RangeMapBlaze::from_iter([(1..=2, "a"), (3..=4, "b"), (5..=5, "c")]));
1840    /// ```
1841    #[inline]
1842    pub fn extend_from(&mut self, other: Self) {
1843        for (start, end_value) in other.btree_map {
1844            let range = start..=end_value.end;
1845            self.internal_add(range, end_value.value);
1846        }
1847    }
1848
1849    /// Extends the [`RangeMapBlaze`] with the contents of a borrowed [`RangeMapBlaze`].
1850    ///
1851    /// This method follows standard *right-to-left precedence*: If the maps contain overlapping ranges,
1852    /// values from `other` will overwrite those in `self`.
1853    ///
1854    /// This method is simple and predictable but not the most efficient option when
1855    /// the right-hand side is larger. For better performance when ownership is available,
1856    /// consider using [`RangeMapBlaze::extend_from`] or the `|=` operator.
1857    ///
1858    /// **See:** [Summary of Union and Extend-like Methods](#rangemapblaze-union--and-extend-like-methods).
1859    ///
1860    /// # Examples
1861    ///
1862    /// ```
1863    /// use range_set_blaze::RangeMapBlaze;
1864    /// let mut a = RangeMapBlaze::from_iter([(1..=4, "a")]);
1865    /// let mut b = RangeMapBlaze::from_iter([(3..=4, "b"), (5..=5, "c")]);
1866    /// a.extend_from(b);
1867    /// assert_eq!(a, RangeMapBlaze::from_iter([(1..=2, "a"), (3..=4, "b"), (5..=5, "c")]));
1868    /// ```
1869    #[inline]
1870    pub fn extend_with(&mut self, other: &Self) {
1871        for (start, end_value) in &other.btree_map {
1872            let range = *start..=end_value.end;
1873            self.internal_add(range, end_value.value.clone());
1874        }
1875    }
1876
1877    /// Removes the first element from the set and returns it, if any.
1878    /// The first element is always the minimum element in the set.
1879    ///
1880    /// Often, internally, the value must be cloned.
1881    ///
1882    /// # Examples
1883    ///
1884    /// ```
1885    /// use range_set_blaze::RangeMapBlaze;
1886    ///
1887    /// let mut map = RangeMapBlaze::new();
1888    ///
1889    /// map.insert(1, "a");
1890    /// map.insert(2, "b");
1891    /// while let Some((key, _val)) = map.pop_first() {
1892    ///     assert!(map.iter().all(|(k, _v)| k > key));
1893    /// }
1894    /// assert!(map.is_empty());
1895    /// ```
1896    pub fn pop_first(&mut self) -> Option<(T, V)>
1897    where
1898        V: Clone,
1899    {
1900        let entry = self.btree_map.first_entry()?;
1901        // We must remove the entry because the key will change
1902        let (start, end_value) = entry.remove_entry();
1903
1904        self.len -= T::SafeLen::one();
1905        if start == end_value.end {
1906            Some((start, end_value.value))
1907        } else {
1908            let value = end_value.value.clone();
1909            self.btree_map.insert(start.add_one(), end_value);
1910            Some((start, value))
1911        }
1912    }
1913
1914    /// Removes the last value from the set and returns it, if any.
1915    /// The last value is always the maximum value in the set.
1916    ///
1917    /// Often, internally, the value must be cloned.
1918    ///
1919    /// # Examples
1920    ///
1921    /// ```
1922    /// use range_set_blaze::RangeMapBlaze;
1923    ///
1924    /// let mut map = RangeMapBlaze::new();
1925    /// map.insert(1, "a");
1926    /// map.insert(2, "b");
1927    /// while let Some((key, _val)) = map.pop_last() {
1928    ///      assert!(map.iter().all(|(k, _v)| k < key));
1929    /// }
1930    /// assert!(map.is_empty());
1931    /// ```
1932    pub fn pop_last(&mut self) -> Option<(T, V)> {
1933        let mut entry = self.btree_map.last_entry()?;
1934        let start = *entry.key();
1935        self.len -= T::SafeLen::one();
1936        let end = entry.get().end;
1937        if start == end {
1938            let value = entry.remove_entry().1.value;
1939            Some((end, value))
1940        } else {
1941            let value = entry.get().value.clone();
1942            entry.get_mut().end.assign_sub_one();
1943            Some((end, value))
1944        }
1945    }
1946
1947    /// An iterator that visits the ranges and values in the [`RangeMapBlaze`],
1948    ///
1949    /// Also see [`RangeMapBlaze::iter`] and [`RangeMapBlaze::into_range_values`].
1950    ///
1951    /// # Examples
1952    ///
1953    /// ```
1954    /// use range_set_blaze::RangeMapBlaze;
1955    ///
1956    /// let map = RangeMapBlaze::from_iter([(30..=40, "c"), (15..=25, "b"), (10..=20, "a")]);
1957    /// let mut range_values = map.range_values();
1958    /// assert_eq!(range_values.next(), Some((10..=20, &"a")));
1959    /// assert_eq!(range_values.next(), Some((21..=25, &"b")));
1960    /// assert_eq!(range_values.next(), Some((30..=40, &"c")));
1961    /// assert_eq!(range_values.next(), None);
1962    /// ```
1963    ///
1964    /// Values returned by the iterator are returned in ascending order
1965    /// with right-to-left precedence.
1966    ///
1967    /// ```
1968    /// use range_set_blaze::RangeMapBlaze;
1969    ///
1970    /// let map = RangeMapBlaze::from_iter([(10..=20, "a"), (15..=25, "b"), (30..=40, "c")]);
1971    /// let mut range_values = map.range_values();
1972    /// assert_eq!(range_values.next(), Some((10..=14, &"a")));
1973    /// assert_eq!(range_values.next(), Some((15..=25, &"b")));
1974    /// assert_eq!(range_values.next(), Some((30..=40, &"c")));
1975    /// assert_eq!(range_values.next(), None);
1976    /// ```
1977    pub fn range_values(&self) -> RangeValuesIter<'_, T, V> {
1978        RangeValuesIter::new(&self.btree_map)
1979    }
1980
1981    /// An iterator that visits the ranges and values in the [`RangeMapBlaze`]. Double-ended.
1982    ///
1983    /// Also see [`RangeMapBlaze::iter`] and [`RangeMapBlaze::range_values`].
1984    ///
1985    /// # Examples
1986    ///
1987    /// ```
1988    /// extern crate alloc;
1989    /// use alloc::rc::Rc;
1990    /// use range_set_blaze::RangeMapBlaze;
1991    ///
1992    /// let map = RangeMapBlaze::from_iter([(30..=40, "c"), (15..=25, "b"), (10..=20, "a")]);
1993    /// let mut range_values = map.into_range_values();
1994    /// assert_eq!(range_values.next(), Some((10..=20, Rc::new("a"))));
1995    /// assert_eq!(range_values.next(), Some((21..=25, Rc::new("b"))));
1996    /// assert_eq!(range_values.next(), Some((30..=40, Rc::new("c"))));
1997    /// assert_eq!(range_values.next(), None);
1998    /// ```
1999    ///
2000    /// Values returned by the iterator are returned in ascending order
2001    /// with right-to-left precedence.
2002    ///
2003    /// ```
2004    /// # extern crate alloc;
2005    /// use alloc::rc::Rc;
2006    /// use range_set_blaze::RangeMapBlaze;
2007    ///
2008    /// let map = RangeMapBlaze::from_iter([(10..=20, "a"), (15..=25, "b"), (30..=40, "c")]);
2009    /// let mut range_values = map.into_range_values();
2010    /// assert_eq!(range_values.next(), Some((10..=14, Rc::new("a"))));
2011    /// assert_eq!(range_values.next(), Some((15..=25, Rc::new("b"))));
2012    /// assert_eq!(range_values.next(), Some((30..=40, Rc::new("c"))));
2013    /// assert_eq!(range_values.next(), None);
2014    /// ```
2015    pub fn into_range_values(self) -> IntoRangeValuesIter<T, V> {
2016        IntoRangeValuesIter::new(self.btree_map)
2017    }
2018
2019    /// An iterator that visits the ranges in the [`RangeMapBlaze`],
2020    /// i.e., the integers as sorted & disjoint ranges.
2021    ///
2022    /// Also see [`RangeMapBlaze::iter`] and [`RangeMapBlaze::into_range_values`].
2023    ///
2024    /// # Examples
2025    ///
2026    /// ```
2027    /// use range_set_blaze::RangeMapBlaze;
2028    ///
2029    /// let map = RangeMapBlaze::from_iter([(10..=20, "a"), (15..=25, "b"), (30..=40, "c")]);
2030    /// let mut ranges = map.ranges();
2031    /// assert_eq!(ranges.next(), Some(10..=25));
2032    /// assert_eq!(ranges.next(), Some(30..=40));
2033    /// assert_eq!(ranges.next(), None);
2034    /// ```
2035    ///
2036    /// Values returned by the iterator are returned in ascending order
2037    /// with right-to-left precedence.
2038    ///
2039    /// ```
2040    /// use range_set_blaze::RangeMapBlaze;
2041    ///
2042    /// let map = RangeMapBlaze::from_iter([(30..=40, "c"), (15..=25, "b"), (10..=20, "a")]);
2043    /// let mut ranges = map.ranges();
2044    /// assert_eq!(ranges.next(), Some(10..=25));
2045    /// assert_eq!(ranges.next(), Some(30..=40));
2046    /// assert_eq!(ranges.next(), None);
2047    /// ```
2048    pub fn ranges(&self) -> MapRangesIter<'_, T, V> {
2049        MapRangesIter::new(self.btree_map.iter())
2050    }
2051
2052    /// An iterator that visits the ranges in the [`RangeMapBlaze`],
2053    /// i.e., the integers as sorted & disjoint ranges.
2054    ///
2055    /// Also see [`RangeMapBlaze::iter`] and [`RangeMapBlaze::into_range_values`].
2056    ///
2057    /// # Examples
2058    ///
2059    /// ```
2060    /// use range_set_blaze::RangeMapBlaze;
2061    ///
2062    /// let map = RangeMapBlaze::from_iter([(10..=20, "a"), (15..=25, "b"), (30..=40, "c")]);
2063    /// let mut ranges = map.into_ranges();
2064    /// assert_eq!(ranges.next(), Some(10..=25));
2065    /// assert_eq!(ranges.next(), Some(30..=40));
2066    /// assert_eq!(ranges.next(), None);
2067    /// ```
2068    ///
2069    /// Values returned by the iterator are returned in ascending order
2070    /// with right-to-left precedence.
2071    ///
2072    /// ```
2073    /// use range_set_blaze::RangeMapBlaze;
2074    ///
2075    /// let map = RangeMapBlaze::from_iter([(30..=40, "c"), (15..=25, "b"), (10..=20, "a")]);
2076    /// let mut ranges = map.into_ranges();
2077    /// assert_eq!(ranges.next(), Some(10..=25));
2078    /// assert_eq!(ranges.next(), Some(30..=40));
2079    /// assert_eq!(ranges.next(), None);
2080    /// ```
2081    pub fn into_ranges(self) -> MapIntoRangesIter<T, V> {
2082        MapIntoRangesIter::new(self.btree_map.into_iter())
2083    }
2084
2085    /// Returns the number of sorted & disjoint ranges in the set.
2086    ///
2087    /// # Example
2088    ///
2089    /// ```
2090    /// use range_set_blaze::RangeMapBlaze;
2091    ///
2092    /// // We put in three ranges, but they are not sorted & disjoint.
2093    /// let map = RangeMapBlaze::from_iter([(10..=20,"a"), (15..=25,"a"), (30..=40,"b")]);
2094    /// // After RangeMapBlaze sorts & 'disjoint's them, we see two ranges.
2095    /// assert_eq!(map.ranges_len(), 2);
2096    /// assert_eq!(map.to_string(), r#"(10..=25, "a"), (30..=40, "b")"#);
2097    /// ```
2098    #[must_use]
2099    pub fn ranges_len(&self) -> usize {
2100        self.btree_map.len()
2101    }
2102
2103    /// ```
2104    /// use range_set_blaze::RangeMapBlaze;
2105    ///
2106    /// let map = RangeMapBlaze::from_iter([(10u16..=20, "a"), (15..=25, "b"), (30..=40, "c")]);
2107    /// let complement = map.complement_with(&"z");
2108    /// assert_eq!(complement.to_string(), r#"(0..=9, "z"), (26..=29, "z"), (41..=65535, "z")"#);
2109    /// ```
2110    #[must_use]
2111    pub fn complement_with(&self, value: &V) -> Self {
2112        self.ranges()
2113            .complement()
2114            .map(|r| (r, value.clone()))
2115            .collect()
2116    }
2117
2118    // FUTURE BTreeSet some of these as 'const' but it uses unstable. When stable, add them here and elsewhere.
2119
2120    /// Returns the number of sorted & disjoint ranges i
2121    /// n the set.
2122    ///
2123    /// # Example
2124    ///
2125    /// ```
2126    /// use range_set_blaze::RangeMapBlaze;
2127    ///
2128    /// // We put in four ranges, but they are not sorted & disjoint.
2129    /// let map = RangeMapBlaze::from_iter([(28..=35, "c"), (30..=40, "c"), (15..=25, "b"), (10..=20, "a")]);
2130    /// // After RangeMapBlaze sorts & 'disjoint's them, we see three ranges.
2131    /// assert_eq!(map.range_values_len(), 3);
2132    /// assert_eq!(map.to_string(), r#"(10..=20, "a"), (21..=25, "b"), (28..=40, "c")"#);
2133    /// ```
2134    #[must_use]
2135    pub fn range_values_len(&self) -> usize {
2136        self.btree_map.len()
2137    }
2138
2139    /// Retains only the elements specified by the predicate.
2140    ///
2141    /// In other words, remove all pairs `(k, v)` for which `f(&k, &mut v)` returns `false`.
2142    /// The elements are visited in ascending key order.
2143    ///
2144    /// Because if visits every element in every range, it is expensive compared to
2145    /// [`RangeMapBlaze::ranges_retain`].
2146    ///
2147    /// # Examples
2148    ///
2149    /// ```
2150    /// use range_set_blaze::RangeMapBlaze;
2151    ///
2152    /// let mut map: RangeMapBlaze<i32, i32> = (0..8).map(|x| (x, x*10)).collect();
2153    /// // Keep only the elements with even-numbered keys.
2154    /// map.retain(|&k, _| k % 2 == 0);
2155    /// assert!(map.into_iter().eq(vec![(0, 0), (2, 20), (4, 40), (6, 60)]));
2156    /// ```
2157    pub fn retain<F>(&mut self, f: F)
2158    where
2159        F: Fn(&T, &V) -> bool,
2160    {
2161        *self = self.iter().filter(|(k, v)| f(k, v)).collect();
2162    }
2163
2164    /// Retains only the `(range, value)` pairs specified by the predicate.
2165    ///
2166    /// In other words, removes all `(range, value)` pairs for which `f(&range, &value)`
2167    /// returns `false`. The `(range, value)` pairs are visited in ascending range order.
2168    ///
2169    /// # Examples
2170    ///
2171    /// ```
2172    /// use range_set_blaze::RangeMapBlaze;
2173    ///
2174    /// let mut map: RangeMapBlaze<i32, &str> = RangeMapBlaze::from_iter([(0..=3, "low"), (4..=7, "high")]);
2175    /// // Keep only the ranges with a specific value.
2176    /// map.ranges_retain(|range, &value| value == "low");
2177    /// assert_eq!(map, RangeMapBlaze::from_iter([(0..=3, "low")]));
2178    /// ```
2179    pub fn ranges_retain<F>(&mut self, mut f: F)
2180    where
2181        F: FnMut(&RangeInclusive<T>, &V) -> bool,
2182    {
2183        self.btree_map.retain(|start, end_value| {
2184            let range = *start..=end_value.end;
2185            if f(&range, &end_value.value) {
2186                true
2187            } else {
2188                self.len -= T::safe_len(&range);
2189                false
2190            }
2191        });
2192    }
2193}
2194
2195impl<T, V> IntoIterator for RangeMapBlaze<T, V>
2196where
2197    T: Integer,
2198    V: Eq + Clone,
2199{
2200    type Item = (T, V);
2201    type IntoIter = IntoIterMap<T, V>;
2202
2203    /// Gets an iterator for moving out the [`RangeSetBlaze`]'s integer contents.
2204    /// Double-ended.
2205    ///
2206    /// # Examples
2207    ///
2208    /// ```
2209    /// use range_set_blaze::RangeSetBlaze;
2210    ///
2211    /// let set = RangeSetBlaze::from_iter([1, 2, 3, 4]);
2212    ///
2213    /// let v: Vec<_> = set.into_iter().collect();
2214    /// assert_eq!(v, [1, 2, 3, 4]);
2215    ///
2216    /// let set = RangeSetBlaze::from_iter([1, 2, 3, 4]);
2217    /// let v: Vec<_> = set.into_iter().rev().collect();
2218    /// assert_eq!(v, [4, 3, 2, 1]);
2219    /// ```
2220    fn into_iter(self) -> IntoIterMap<T, V> {
2221        IntoIterMap::new(self.btree_map.into_iter())
2222    }
2223}
2224
2225// Implementing `IntoIterator` for `&RangeMapBlaze<T, V>` because BTreeMap does.
2226impl<'a, T: Integer, V: Eq + Clone> IntoIterator for &'a RangeMapBlaze<T, V> {
2227    type IntoIter = IterMap<T, &'a V, RangeValuesIter<'a, T, V>>;
2228    type Item = (T, &'a V);
2229
2230    fn into_iter(self) -> Self::IntoIter {
2231        self.iter()
2232    }
2233}
2234
2235impl<T: Integer, V: Eq + Clone> BitOr<Self> for RangeMapBlaze<T, V> {
2236    /// Unions the contents of two [`RangeMapBlaze`]'s.
2237    ///  
2238    /// This operator has *right precedence*: when overlapping ranges are present,
2239    /// values on the right-hand side take priority over those self.
2240    ///
2241    /// This method is optimized for three usage scenarios:
2242    /// when the left-hand side is much smaller, when the right-hand side is much smaller,
2243    /// and when both sides are of similar size.
2244    ///
2245    /// **Also See:** [Summary of Union and Extend-like Methods](#rangemapblaze-union--and-extend-like-methods).
2246    ///
2247    /// # Examples
2248    /// ```
2249    /// use range_set_blaze::RangeMapBlaze;
2250    /// let a = RangeMapBlaze::from_iter([(1..=2, "a"), (5..=100, "a")]);
2251    /// let b = RangeMapBlaze::from_iter([(2..=6, "b")]);
2252    /// let union = a | b;  // Alternatively, '&a | &b', etc.
2253    /// assert_eq!(union, RangeMapBlaze::from_iter([(1..=1, "a"), (2..=6, "b"), (7..=100, "a")]));
2254    /// ```
2255    type Output = Self;
2256    fn bitor(self, other: Self) -> Self {
2257        let b_len = other.ranges_len();
2258        if b_len == 0 {
2259            return self;
2260        }
2261        let a_len = self.ranges_len();
2262        if a_len == 0 {
2263            return other;
2264        }
2265        if much_greater_than(a_len, b_len) {
2266            return small_b_over_a(self, other);
2267        }
2268        if much_greater_than(b_len, a_len) {
2269            return small_a_under_b(self, other);
2270        }
2271        // Sizes are comparable, use the iterator union
2272        (self.into_range_values() | other.into_range_values()).into_range_map_blaze()
2273    }
2274}
2275
2276impl<T: Integer, V: Eq + Clone> BitOr<&Self> for RangeMapBlaze<T, V> {
2277    /// Unions the contents of two [`RangeMapBlaze`]'s.
2278    ///
2279    /// This operator has *right precedence*: when overlapping ranges are present,
2280    /// values on the right-hand side take priority over those self.
2281    ///
2282    /// This method is optimized for three usage scenarios:
2283    /// when the left-hand side is much smaller, when the right-hand side is much smaller,
2284    /// and when both sides are of similar size.
2285    ///
2286    /// **Also See:** [Summary of Union and Extend-like Methods](#rangemapblaze-union--and-extend-like-methods).
2287    ///
2288    /// # Examples
2289    /// ```
2290    /// use range_set_blaze::RangeMapBlaze;
2291    /// let a = RangeMapBlaze::from_iter([(1..=2, "a"), (5..=100, "a")]);
2292    /// let b = RangeMapBlaze::from_iter([(2..=6, "b")]);
2293    /// let union = a | &b; // Alternatively, 'a | b', etc.
2294    /// assert_eq!(union, RangeMapBlaze::from_iter([(1..=1, "a"), (2..=6, "b"), (7..=100, "a")]));
2295    /// ```
2296    type Output = Self;
2297    fn bitor(self, other: &Self) -> Self {
2298        let b_len = other.ranges_len();
2299        if b_len == 0 {
2300            return self;
2301        }
2302        let a_len = self.ranges_len();
2303        if a_len == 0 {
2304            return other.clone();
2305        }
2306        if much_greater_than(a_len, b_len) {
2307            return small_b_over_a(self, other.clone());
2308        }
2309        if much_greater_than(b_len, a_len) {
2310            return small_a_under_b(self, other.clone());
2311        }
2312
2313        // Sizes are comparable, use the iterator union
2314        (self.range_values() | other.range_values()).into_range_map_blaze()
2315    }
2316}
2317
2318impl<T: Integer, V: Eq + Clone> BitOr<RangeMapBlaze<T, V>> for &RangeMapBlaze<T, V> {
2319    type Output = RangeMapBlaze<T, V>;
2320    /// Unions the contents of two [`RangeMapBlaze`]'s.
2321    ///
2322    /// This operator has *right precedence*: when overlapping ranges are present,
2323    /// values on the right-hand side take priority over those self.
2324    ///
2325    /// This method is optimized for three usage scenarios:
2326    /// when the left-hand side is much smaller, when the right-hand side is much smaller,
2327    /// and when both sides are of similar size.
2328    ///
2329    /// **Also See:** [Summary of Union and Extend-like Methods](#rangemapblaze-union--and-extend-like-methods).
2330    ///
2331    /// # Examples
2332    /// ```
2333    /// use range_set_blaze::RangeMapBlaze;
2334    /// let a = RangeMapBlaze::from_iter([(1..=2, "a"), (5..=100, "a")]);
2335    /// let b = RangeMapBlaze::from_iter([(2..=6, "b")]);
2336    /// let union = &a | b;  // Alternatively, 'a | b', etc.
2337    /// assert_eq!(union, RangeMapBlaze::from_iter([(1..=1, "a"), (2..=6, "b"), (7..=100, "a")]));
2338    /// ```
2339    fn bitor(self, other: RangeMapBlaze<T, V>) -> RangeMapBlaze<T, V> {
2340        let a_len = self.ranges_len();
2341        if a_len == 0 {
2342            return other;
2343        }
2344        let b_len = other.ranges_len();
2345        if b_len == 0 {
2346            return self.clone();
2347        }
2348        if much_greater_than(b_len, a_len) {
2349            return small_a_under_b(self.clone(), other);
2350        }
2351        if much_greater_than(a_len, b_len) {
2352            return small_b_over_a(self.clone(), other);
2353        }
2354        // Sizes are comparable, use the iterator union
2355        (self.range_values() | other.range_values()).into_range_map_blaze()
2356    }
2357}
2358
2359impl<T: Integer, V: Eq + Clone> BitOr<&RangeMapBlaze<T, V>> for &RangeMapBlaze<T, V> {
2360    type Output = RangeMapBlaze<T, V>;
2361    /// Unions the contents of two [`RangeMapBlaze`]'s.
2362    ///
2363    /// This operator has *right precedence*: when overlapping ranges are present,
2364    /// values on the right-hand side take priority over those self.
2365    ///
2366    /// This method is optimized for three usage scenarios:
2367    /// when the left-hand side is much smaller, when the right-hand side is much smaller,
2368    /// and when both sides are of similar size.
2369    ///
2370    /// **Also See:** [Summary of Union and Extend-like Methods](#rangemapblaze-union--and-extend-like-methods).
2371    ///
2372    /// # Examples
2373    /// ```
2374    /// use range_set_blaze::RangeMapBlaze;
2375    /// let a = RangeMapBlaze::from_iter([(1..=2, "a"), (5..=100, "a")]);
2376    /// let b = RangeMapBlaze::from_iter([(2..=6, "b")]);
2377    /// let union = &a | &b; // Alternatively, 'a | b', etc.
2378    /// assert_eq!(union, RangeMapBlaze::from_iter([(1..=1, "a"), (2..=6, "b"), (7..=100, "a")]));
2379    /// ```
2380    fn bitor(self, other: &RangeMapBlaze<T, V>) -> RangeMapBlaze<T, V> {
2381        let a_len = self.ranges_len();
2382        if a_len == 0 {
2383            return other.clone();
2384        }
2385        let b_len = other.ranges_len();
2386        if b_len == 0 {
2387            return self.clone();
2388        }
2389        if much_greater_than(a_len, b_len) {
2390            return small_b_over_a(self.clone(), other.clone());
2391        }
2392        if much_greater_than(b_len, a_len) {
2393            return small_a_under_b(self.clone(), other.clone());
2394        }
2395        // Sizes are comparable, use the iterator union
2396        (self.range_values() | other.range_values()).into_range_map_blaze()
2397    }
2398}
2399
2400map_op!(
2401     BitAnd bitand,
2402    RangeMapBlaze<T, V>,          // RHS concrete type
2403
2404    /// Intersects the contents of two [`RangeMapBlaze`]'s.
2405    ///
2406    /// Either, neither, or both inputs may be borrowed.
2407    ///
2408    /// # Examples
2409    /// ```
2410    /// use range_set_blaze::prelude::*;
2411    ///
2412    /// let a = RangeMapBlaze::from_iter([(1..=2, "a"), (5..=100, "a")]);
2413    /// let b = RangeMapBlaze::from_iter([(2..=6, "b")]);
2414    /// let result = &a & &b; // Alternatively, 'a & b'.
2415    /// assert_eq!(result.to_string(), r#"(2..=2, "b"), (5..=6, "b")"#);
2416    /// ```
2417    "placeholder",
2418
2419    // owned ∩ owned
2420    |a, b| {
2421        b.into_range_values()
2422         .map_and_set_intersection(a.into_ranges())
2423         .into_range_map_blaze()
2424    },
2425
2426    // owned ∩ &borrowed
2427    |a, &b| {
2428        b.range_values()
2429         .map_and_set_intersection(a.into_ranges())
2430         .into_range_map_blaze()
2431    },
2432
2433    // &borrowed ∩ owned
2434    |&a, b| {
2435        b.into_range_values()
2436         .map_and_set_intersection(a.ranges())
2437         .into_range_map_blaze()
2438    },
2439
2440    // &borrowed ∩ &borrowed
2441    |&a, &b| {
2442        b.range_values()
2443         .map_and_set_intersection(a.ranges())
2444         .into_range_map_blaze()
2445    },
2446);
2447
2448map_op!(
2449     BitAnd bitand,
2450    RangeSetBlaze<T>,          // RHS concrete type
2451
2452/// Find the intersection between a [`RangeMapBlaze`] and a [`RangeSetBlaze`]. The result is a new [`RangeMapBlaze`].
2453///
2454/// Either, neither, or both inputs may be borrowed.
2455///
2456/// # Examples
2457/// ```
2458/// use range_set_blaze::prelude::*;
2459///
2460/// let a = RangeMapBlaze::from_iter([(1..=100, "a")]);
2461/// let b = RangeSetBlaze::from_iter([2..=6]);
2462/// let result = &a & &b; // Alternatively, 'a & b'.
2463/// assert_eq!(result.to_string(), r#"(2..=6, "a")"#);
2464/// ```
2465    "placeholder",
2466
2467    // owned ∩ owned
2468    |a, b| {
2469        a.into_range_values()
2470         .map_and_set_intersection(b.into_ranges())
2471         .into_range_map_blaze()
2472    },
2473
2474    // owned ∩ &borrowed
2475    |a, &b| {
2476        a.into_range_values()
2477         .map_and_set_intersection(b.ranges())
2478         .into_range_map_blaze()
2479    },
2480
2481    // &borrowed ∩ owned
2482    |&a, b| {
2483        a.range_values()
2484         .map_and_set_intersection(b.into_ranges())
2485         .into_range_map_blaze()
2486    },
2487
2488    // &borrowed ∩ &borrowed
2489    |&a, &b| {
2490        a.range_values()
2491         .map_and_set_intersection(b.ranges())
2492         .into_range_map_blaze()
2493    },
2494);
2495
2496map_op!(
2497    BitXor bitxor,                           // trait + method name
2498    RangeMapBlaze<T, V>,                     // RHS concrete type
2499
2500/// Symmetric difference the contents of two [`RangeMapBlaze`]'s.
2501///
2502/// Either, neither, or both inputs may be borrowed.
2503///
2504/// # Examples
2505/// ```
2506/// use range_set_blaze::prelude::*;
2507///
2508/// let a = RangeMapBlaze::from_iter([(1..=2, "a"), (5..=100, "a")]);
2509/// let b = RangeMapBlaze::from_iter([(2..=6, "b")]);
2510/// let result = &a ^ &b; // Alternatively, 'a ^ b'.
2511/// assert_eq!(result.to_string(), r#"(1..=1, "a"), (3..=4, "b"), (7..=100, "a")"#);
2512/// ```
2513    "placeholder",
2514
2515    // ── owned ^ owned ────────────────────────────────────────────
2516    |a, b| {
2517        SymDiffIterMap::new2(
2518            a.into_range_values(),
2519            b.into_range_values(),
2520        )
2521        .into_range_map_blaze()
2522    },
2523
2524    // ── owned ^ &borrowed ────────────────────────────────────────
2525    |a, &b| {
2526        SymDiffIterMap::new2(
2527            a.range_values(),
2528            b.range_values(),
2529        )
2530        .into_range_map_blaze()
2531    },
2532
2533    // ── &borrowed ^ owned ────────────────────────────────────────
2534    |&a, b| {
2535        SymDiffIterMap::new2(
2536            a.range_values(),
2537            b.range_values(),
2538        )
2539        .into_range_map_blaze()
2540    },
2541
2542    // ── &borrowed ^ &borrowed ────────────────────────────────────
2543    |&a, &b| {
2544        SymDiffIterMap::new2(
2545            a.range_values(),
2546            b.range_values(),
2547        )
2548        .into_range_map_blaze()
2549    },
2550);
2551
2552map_op!(
2553    Sub sub,                                 // trait + method name
2554    RangeMapBlaze<T, V>,         // RHS concrete type
2555
2556    /// **Difference** of two [`RangeMapBlaze`] values (`a - b`).
2557    ///
2558    /// Either, neither, or both inputs may be borrowed.
2559    ///
2560    /// # Example
2561    /// ```
2562    /// use range_set_blaze::prelude::*;
2563    ///
2564    /// let a = RangeMapBlaze::from_iter([(1..=2, "a"), (5..=100, "a")]);
2565    /// let b = RangeMapBlaze::from_iter([(2..=6, "b")]);
2566    /// let result = &a - &b;                // or `a - b`
2567    /// assert_eq!(result.to_string(),
2568    ///            r#"(1..=1, "a"), (7..=100, "a")"#);
2569    /// ```
2570    "placeholder",
2571
2572    // ── owned − owned ────────────────────────────────────────────
2573    |a, b| {
2574        a.into_range_values()
2575         .map_and_set_difference(b.ranges())
2576         .into_range_map_blaze()
2577    },
2578
2579    // ── owned − &borrowed ────────────────────────────────────────
2580    |a, &b| {
2581        a.into_range_values()
2582         .map_and_set_difference(b.ranges())
2583         .into_range_map_blaze()
2584    },
2585
2586    // ── &borrowed − owned ────────────────────────────────────────
2587    |&a, b| {
2588        a.range_values()
2589         .map_and_set_difference(b.into_ranges())
2590         .into_range_map_blaze()
2591    },
2592
2593    // ── &borrowed − &borrowed ────────────────────────────────────
2594    |&a, &b| {
2595        a.range_values()
2596         .map_and_set_difference(b.ranges())
2597         .into_range_map_blaze()
2598    },
2599);
2600
2601map_op!(
2602    Sub sub,                                 // trait + method name
2603    RangeSetBlaze<T>,         // RHS concrete type
2604
2605/// Find the difference between a [`RangeMapBlaze`] and a [`RangeSetBlaze`]. The result is a new [`RangeMapBlaze`].
2606///
2607/// Either, neither, or both inputs may be borrowed.
2608///
2609/// # Examples
2610/// ```
2611/// use range_set_blaze::prelude::*;
2612///
2613/// let a = RangeMapBlaze::from_iter([(1..=100, "a")]);
2614/// let b = RangeSetBlaze::from_iter([2..=6]);
2615/// let result = &a - &b; // Alternatively, 'a - b'.
2616/// assert_eq!(result.to_string(), r#"(1..=1, "a"), (7..=100, "a")"#);
2617/// ```
2618    "placeholder",
2619
2620    // ── owned − owned ────────────────────────────────────────────
2621    |a, b| {
2622        a.into_range_values()
2623         .map_and_set_difference(b.ranges())
2624         .into_range_map_blaze()
2625    },
2626
2627    // ── owned − &borrowed ────────────────────────────────────────
2628    |a, &b| {
2629        a.into_range_values()
2630         .map_and_set_difference(b.ranges())
2631         .into_range_map_blaze()
2632    },
2633
2634    // ── &borrowed − owned ────────────────────────────────────────
2635    |&a, b| {
2636        a.range_values()
2637         .map_and_set_difference(b.into_ranges())
2638         .into_range_map_blaze()
2639    },
2640
2641    // ── &borrowed − &borrowed ────────────────────────────────────
2642    |&a, &b| {
2643        a.range_values()
2644         .map_and_set_difference(b.ranges())
2645         .into_range_map_blaze()
2646    },
2647);
2648
2649map_unary_op!(
2650    Not not,                                   // trait + method
2651    crate::set::RangeSetBlaze<T>,              // output type
2652
2653    /// Takes the complement of a [`RangeMapBlaze`].
2654    ///
2655    /// Produces a [`RangeSetBlaze`] containing all integers *not* present
2656    /// in the map’s key ranges.
2657    ///
2658    /// # Example
2659    /// ```
2660    /// use range_set_blaze::prelude::*;
2661    /// let map =
2662    ///     RangeMapBlaze::from_iter([(10u8..=20, "a"), (15..=25, "b"),
2663    ///                               (30..=40, "c")]);
2664    /// let complement = !&map;                // or `!map`
2665    /// assert_eq!(complement.to_string(), "0..=9, 26..=29, 41..=255");
2666    /// ```
2667    "placeholder",
2668
2669    // body for &map
2670    |&m| {
2671        m.ranges()
2672         .complement()
2673         .into_range_set_blaze()
2674    }
2675);
2676
2677impl<T, V> Extend<(T, V)> for RangeMapBlaze<T, V>
2678where
2679    T: Integer,
2680    V: Eq + Clone,
2681{
2682    /// Extends the [`RangeMapBlaze`] with the contents of an iterator of integer-value pairs.
2683    ///
2684    /// This method has *right-to-left precedence*: later values in the iterator take priority
2685    /// over earlier ones, matching the behavior of standard `BTreeMap::extend`.
2686    ///
2687    /// Each integer is treated as a singleton range. Adjacent integers with the same value
2688    /// are merged before insertion. For alternatives that skip merging or accept full ranges,
2689    /// see [`RangeMapBlaze::extend_simple`] and [`RangeMapBlaze::extend`].
2690    ///
2691    /// **See:** [Summary of Union and Extend-like Methods](#rangemapblaze-union--and-extend-like-methods).
2692    ///
2693    /// # Examples
2694    /// ```
2695    /// use range_set_blaze::RangeMapBlaze;
2696    /// let mut a = RangeMapBlaze::from_iter([(3, "a"), (4, "e"), (5, "f"), (5, "g")]);
2697    /// a.extend([(1..=4, "b")]);
2698    /// assert_eq!(a, RangeMapBlaze::from_iter([(1..=4, "b"), (5..=5, "g")]));
2699    ///
2700    /// let mut a = RangeMapBlaze::from_iter([(3, "a"), (4, "e"), (5, "f"), (5, "g")]);
2701    /// let mut b = RangeMapBlaze::from_iter([(1..=4, "b")]);
2702    /// a |= b;
2703    /// assert_eq!(a, RangeMapBlaze::from_iter([(1..=4, "b"), (5..=5, "g")]));
2704    /// ```
2705    #[inline]
2706    fn extend<I>(&mut self, iter: I)
2707    where
2708        I: IntoIterator<Item = (T, V)>,
2709    {
2710        let iter = iter.into_iter();
2711
2712        // We gather adjacent values into ranges via UnsortedPriorityMap, but ignore the priority.
2713        for priority in UnsortedPriorityMap::new(iter.map(|(r, v)| (r..=r, Rc::new(v)))) {
2714            let (range, value) = priority.into_range_value();
2715            let value: V = Rc::try_unwrap(value).unwrap_or_else(|_| unreachable!());
2716            self.internal_add(range, value);
2717        }
2718    }
2719}
2720
2721impl<T, V> Extend<(RangeInclusive<T>, V)> for RangeMapBlaze<T, V>
2722where
2723    T: Integer,
2724    V: Eq + Clone,
2725{
2726    /// Extends the [`RangeMapBlaze`] with the contents of an iterator of range-value pairs.
2727    ///
2728    /// This method has *right-to-left precedence* — like `BTreeMap` and all other
2729    /// `RangeMapBlaze` methods.
2730    ///
2731    /// It first merges any adjacent or overlapping ranges with the same value, then adds them one by one.
2732    /// For alternatives that skip merging or that accept integer-value pairs, see
2733    /// [`RangeMapBlaze::extend_simple`] and the `(integer, value)` overload.
2734    ///
2735    /// **See:** [Summary of Union and Extend-like Methods](#rangemapblaze-union--and-extend-like-methods).
2736    /// # Examples
2737    /// ```
2738    /// use range_set_blaze::RangeMapBlaze;
2739    /// let mut a = RangeMapBlaze::from_iter([(1..=4, "a")]);
2740    /// a.extend([(3..=5, "b"), (5..=5, "c")]);
2741    /// assert_eq!(a, RangeMapBlaze::from_iter([(1..=2, "a"), (3..=4, "b"), (5..=5, "c")]));
2742    ///
2743    /// // `extend_simple` is a more efficient for the case where the ranges a likely disjoint.
2744    /// let mut a = RangeMapBlaze::from_iter([(1..=4, "a")]);
2745    /// a.extend_simple([(3..=5, "b"), (5..=5, "c")]);
2746    /// assert_eq!(a, RangeMapBlaze::from_iter([(1..=2, "a"), (3..=4, "b"), (5..=5, "c")]));
2747    ///
2748    /// let mut a = RangeMapBlaze::from_iter([(1..=4, "a")]);
2749    /// let mut b = RangeMapBlaze::from_iter([(3..=5, "b"), (5..=5, "c")]);
2750    /// a |= b;
2751    /// assert_eq!(a, RangeMapBlaze::from_iter([(1..=2, "a"), (3..=4, "b"), (5..=5, "c")]));
2752    /// ```
2753    #[inline]
2754    fn extend<I>(&mut self, iter: I)
2755    where
2756        I: IntoIterator<Item = (RangeInclusive<T>, V)>,
2757    {
2758        let iter = iter.into_iter();
2759
2760        // We gather adjacent values into ranges via UnsortedPriorityMap, but ignore the priority.
2761        for priority in UnsortedPriorityMap::new(iter.map(|(r, v)| (r, Rc::new(v)))) {
2762            let (range, value) = priority.into_range_value();
2763            let value = Rc::try_unwrap(value).unwrap_or_else(|_| unreachable!());
2764            self.internal_add(range, value);
2765        }
2766    }
2767}
2768
2769impl<T, V, const N: usize> From<[(T, V); N]> for RangeMapBlaze<T, V>
2770where
2771    T: Integer,
2772    V: Eq + Clone,
2773{
2774    /// For compatibility with [`BTreeMap`] you may create a [`RangeSetBlaze`] from an array of integers.
2775    ///
2776    /// *For more about constructors and performance, see [`RangeSetBlaze` Constructors](struct.RangeSetBlaze.html#rangesetblaze-constructors).*
2777    ///
2778    /// [`BTreeMap`]: alloc::collections::BTreeMap
2779    ///
2780    /// # Examples
2781    ///
2782    /// ```
2783    /// use range_set_blaze::RangeSetBlaze;
2784    ///
2785    /// let a0 = RangeSetBlaze::from([3, 2, 1, 100, 1]);
2786    /// let a1: RangeSetBlaze<i32> = [3, 2, 1, 100, 1].into();
2787    /// assert!(a0 == a1 && a0.to_string() == "1..=3, 100..=100")
2788    /// ```
2789    fn from(arr: [(T, V); N]) -> Self {
2790        arr.into_iter().collect()
2791    }
2792}
2793
2794// implement Index trait
2795impl<T: Integer, V: Eq + Clone> Index<T> for RangeMapBlaze<T, V> {
2796    type Output = V;
2797
2798    /// Returns a reference to the value corresponding to the supplied key.
2799    ///
2800    /// # Panics
2801    ///
2802    /// Panics if the key is not present in the `BTreeMap`.
2803    #[inline]
2804    #[allow(clippy::manual_assert)] // We use "if...panic!" for coverage auditing.
2805    fn index(&self, index: T) -> &Self::Output {
2806        self.get(index).unwrap_or_else(|| {
2807            panic!("no entry found for key");
2808        })
2809    }
2810}
2811
2812// LATER define value_per_range and into_value_per_range
2813
2814impl<T, V> PartialOrd for RangeMapBlaze<T, V>
2815where
2816    T: Integer,
2817    V: Eq + Clone + Ord,
2818{
2819    /// We define a partial ordering on `RangeMapBlaze`. Following the convention of
2820    /// [`BTreeMap`], the ordering is lexicographic, *not* by subset/superset.
2821    ///
2822    /// [`BTreeMap`]: alloc::collections::BTreeMap
2823    ///
2824    /// # Examples
2825    /// ```
2826    /// use range_set_blaze::prelude::*;
2827    ///
2828    /// let a = RangeMapBlaze::from_iter([(1..=3, "a"), (5..=100, "a")]);
2829    /// let b = RangeMapBlaze::from_iter([(2..=2, "b")] );
2830    /// assert!(a < b); // Lexicographic comparison
2831    /// // More lexicographic comparisons
2832    /// assert!(a <= b);
2833    /// assert!(b > a);
2834    /// assert!(b >= a);
2835    /// assert!(a != b);
2836    /// assert!(a == a);
2837    /// use core::cmp::Ordering;
2838    /// assert_eq!(a.cmp(&b), Ordering::Less);
2839    ///
2840    /// // Floats aren't comparable, but we can convert them to comparable bits.
2841    /// let a = RangeMapBlaze::from_iter([(2..=3, 1.0f32.to_bits()), (5..=100, 2.0f32.to_bits())]);
2842    /// let b = RangeMapBlaze::from_iter([(2..=2, f32::NAN.to_bits())] );
2843    /// assert_eq!(a.partial_cmp(&b), Some(Ordering::Less));
2844    /// ```
2845    #[inline]
2846    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
2847        Some(self.cmp(other))
2848    }
2849}
2850
2851impl<T, V> Ord for RangeMapBlaze<T, V>
2852where
2853    T: Integer,
2854    V: Eq + Clone + Ord,
2855{
2856    /// We define an ordering on `RangeMapBlaze`. Following the convention of
2857    /// [`BTreeMap`], the ordering is lexicographic, *not* by subset/superset.
2858    ///
2859    /// [`BTreeMap`]: alloc::collections::BTreeMap
2860    ///
2861    /// # Examples
2862    /// ```
2863    /// use range_set_blaze::prelude::*;
2864    ///
2865    /// let a = RangeMapBlaze::from_iter([(1..=3, "a"), (5..=100, "a")]);
2866    /// let b = RangeMapBlaze::from_iter([(2..=2, "b")] );
2867    /// assert!(a < b); // Lexicographic comparison
2868    /// // More lexicographic comparisons
2869    /// assert!(a <= b);
2870    /// assert!(b > a);
2871    /// assert!(b >= a);
2872    /// assert!(a != b);
2873    /// assert!(a == a);
2874    /// use core::cmp::Ordering;
2875    /// assert_eq!(a.cmp(&b), Ordering::Less);
2876    ///
2877    /// // Floats aren't comparable, but we can convert them to comparable bits.
2878    /// let a = RangeMapBlaze::from_iter([(2..=3, 1.0f32.to_bits()), (5..=100, 2.0f32.to_bits())]);
2879    /// let b = RangeMapBlaze::from_iter([(2..=2, f32::NAN.to_bits())] );
2880    /// assert_eq!(a.partial_cmp(&b), Some(Ordering::Less));
2881    /// ```
2882    #[inline]
2883    fn cmp(&self, other: &Self) -> Ordering {
2884        // fast by ranges:
2885        let mut a = self.range_values();
2886        let mut b = other.range_values();
2887        let mut a_rx = a.next();
2888        let mut b_rx = b.next();
2889        loop {
2890            // compare Some/None
2891            match (a_rx, &b_rx) {
2892                (Some(_), None) => return Ordering::Greater,
2893                (None, Some(_)) => return Ordering::Less,
2894                (None, None) => return Ordering::Equal,
2895                (Some((a_r, a_v)), Some((b_r, b_v))) => {
2896                    // if tie, compare starts
2897                    match a_r.start().cmp(b_r.start()) {
2898                        Ordering::Greater => return Ordering::Greater,
2899                        Ordering::Less => return Ordering::Less,
2900                        Ordering::Equal => { /* keep going */ }
2901                    }
2902
2903                    // if tie, compare values
2904                    match a_v.cmp(b_v) {
2905                        Ordering::Less => return Ordering::Less,
2906                        Ordering::Greater => return Ordering::Greater,
2907                        Ordering::Equal => { /* keep going */ }
2908                    }
2909
2910                    // if tie, compare ends
2911                    match a_r.end().cmp(b_r.end()) {
2912                        Ordering::Less => {
2913                            a_rx = a.next();
2914                            b_rx = Some(((*a_r.end()).add_one()..=*b_r.end(), b_v));
2915                        }
2916                        Ordering::Greater => {
2917                            a_rx = Some(((*b_r.end()).add_one()..=*a_r.end(), a_v));
2918                            b_rx = b.next();
2919                        }
2920                        Ordering::Equal => {
2921                            a_rx = a.next();
2922                            b_rx = b.next();
2923                        }
2924                    }
2925                }
2926            }
2927        }
2928    }
2929}
2930
2931impl<T: Integer, V: Eq + Clone> Eq for RangeMapBlaze<T, V> {}
2932
2933impl<T: Integer, V: Eq + Clone> BitOrAssign<&Self> for RangeMapBlaze<T, V> {
2934    /// Adds the contents of another [`RangeMapBlaze`] to this one.
2935    ///
2936    /// This operator has *right precedence*: when overlapping ranges are present,
2937    /// values on the right-hand side take priority over those self.
2938    ///
2939    /// To get *left precedence*, swap the operands.
2940    ///
2941    /// This method is optimized for three usage scenarios:
2942    /// when the left-hand side is much smaller, when the right-hand side is much smaller,
2943    /// and when both sides are of similar size
2944    ///
2945    /// **Also See:** [Summary of Union and Extend-like Methods](#rangemapblaze-union--and-extend-like-methods).
2946    ///
2947    /// # Examples
2948    /// ```
2949    /// use range_set_blaze::RangeMapBlaze;
2950    /// let mut a = RangeMapBlaze::from_iter([(3, "a"), (4, "e"), (5, "f"), (5, "g")]);
2951    /// let mut b = RangeMapBlaze::from_iter([(1..=4, "b")]);
2952    /// a |= &b;
2953    /// assert_eq!(a, RangeMapBlaze::from_iter([(1..=4, "b"), (5..=5, "g")]));
2954    /// ```
2955    fn bitor_assign(&mut self, other: &Self) {
2956        let original_self = mem::take(self); // Take ownership of self
2957        *self = original_self | other; // Use the union operator to combine
2958    }
2959}
2960
2961impl<T: Integer, V: Eq + Clone> BitOrAssign<Self> for RangeMapBlaze<T, V> {
2962    /// Adds the contents of another [`RangeMapBlaze`] to this one.
2963    ///
2964    /// This operator has *right precedence*: when overlapping ranges are present,
2965    /// values on the right-hand side take priority over those self.
2966    /// To get *left precedence*, swap the operands.
2967    ///
2968    /// This method is optimized for three usage scenarios:
2969    /// when the left-hand side is much smaller, when the right-hand side is much smaller,
2970    /// and when both sides are of similar size
2971    ///
2972    /// **Also See:** [Summary of Union and Extend-like Methods](#rangemapblaze-union--and-extend-like-methods).
2973    ///
2974    /// # Examples
2975    /// ```
2976    /// use range_set_blaze::RangeMapBlaze;
2977    /// let mut a = RangeMapBlaze::from_iter([(3, "a"), (4, "e"), (5, "f"), (5, "g")]);
2978    /// let mut b = RangeMapBlaze::from_iter([(1..=4, "b")]);
2979    /// a |= &b;
2980    /// assert_eq!(a, RangeMapBlaze::from_iter([(1..=4, "b"), (5..=5, "g")]));
2981    /// ```
2982    fn bitor_assign(&mut self, other: Self) {
2983        *self = mem::take(self) | other;
2984    }
2985}
2986
2987#[inline]
2988fn much_greater_than(a_len: usize, b_len: usize) -> bool {
2989    let a_len_log2_plus_one: usize = a_len
2990        .checked_ilog2()
2991        .map_or(0, |log| log.try_into().expect("log2 fits usize"))
2992        + 1;
2993    b_len * a_len_log2_plus_one < STREAM_OVERHEAD * a_len + b_len
2994}
2995
2996#[inline]
2997fn small_b_over_a<T: Integer, V: Eq + Clone>(
2998    mut a: RangeMapBlaze<T, V>,
2999    b: RangeMapBlaze<T, V>,
3000) -> RangeMapBlaze<T, V> {
3001    debug_assert!(much_greater_than(a.ranges_len(), b.ranges_len()));
3002    for (start, end_value) in b.btree_map {
3003        a.internal_add(start..=(end_value.end), end_value.value);
3004    }
3005    a
3006}
3007
3008#[inline]
3009fn small_a_under_b<T: Integer, V: Eq + Clone>(
3010    a: RangeMapBlaze<T, V>,
3011    mut b: RangeMapBlaze<T, V>,
3012) -> RangeMapBlaze<T, V> {
3013    debug_assert!(much_greater_than(b.ranges_len(), a.ranges_len()));
3014    let difference = a - &b;
3015    b.extend_simple(
3016        difference
3017            .btree_map
3018            .into_iter()
3019            .map(|(start, v)| (start..=v.end, v.value)),
3020    );
3021    b
3022}