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