Skip to main content

mid_tools/
partition_map.rs

1use std::{
2    borrow::{Borrow, Cow},
3    cmp::Ordering,
4    collections::{btree_map, BTreeMap},
5    fmt, mem,
6    ops::{self, Bound, Deref},
7};
8
9#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
10pub struct Partition<T> {
11    pub start: Option<T>,
12    pub end: Option<T>,
13}
14
15impl<T: fmt::Debug> fmt::Debug for Partition<T> {
16    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
17        match (&self.start, &self.end) {
18            (None, None) => fmt::Debug::fmt(&(..), f),
19            (None, Some(e)) => fmt::Debug::fmt(&(..e), f),
20            (Some(s), None) => fmt::Debug::fmt(&(s..), f),
21            (Some(s), Some(e)) => fmt::Debug::fmt(&(s..e), f),
22        }
23    }
24}
25
26impl<T> From<Partition<T>> for (Option<T>, Option<T>) {
27    #[inline]
28    fn from(Partition { start, end }: Partition<T>) -> Self { (start, end) }
29}
30
31impl<K: ToOwned> Partition<&K> {
32    #[must_use]
33    pub fn to_owned(self) -> Partition<K::Owned> {
34        let Self { start, end } = self;
35        Partition {
36            start: start.map(ToOwned::to_owned),
37            end: end.map(ToOwned::to_owned),
38        }
39    }
40}
41
42impl<T: Copy> Partition<&T> {
43    #[must_use]
44    pub fn copied(self) -> Partition<T> {
45        let Self { start, end } = self;
46        Partition {
47            start: start.copied(),
48            end: end.copied(),
49        }
50    }
51}
52
53impl<T> Partition<T> {
54    #[inline]
55    #[must_use]
56    pub fn bounds(self) -> (Option<T>, Option<T>) { (self.start, self.end) }
57
58    #[must_use]
59    pub fn as_ref(&self) -> Partition<&T> {
60        let Self { start, end } = self;
61        Partition {
62            start: start.as_ref(),
63            end: end.as_ref(),
64        }
65    }
66}
67
68impl<T: Deref> Partition<T> {
69    #[must_use]
70    pub fn as_deref(&self) -> Partition<&T::Target> {
71        let Self { start, end } = self;
72        Partition {
73            start: start.as_deref(),
74            end: end.as_deref(),
75        }
76    }
77}
78
79pub trait PartitionBounds<T>: Into<Partition<T>> {
80    /// The start of the range (inclusive), if any
81    fn start(&self) -> Option<&T>;
82
83    /// The end of the range (exclusive), if any
84    fn end(&self) -> Option<&T>;
85}
86
87impl<T> From<ops::Range<T>> for Partition<T> {
88    #[inline]
89    fn from(ops::Range { start, end }: ops::Range<T>) -> Self {
90        Partition {
91            start: Some(start),
92            end: Some(end),
93        }
94    }
95}
96
97impl<T> PartitionBounds<T> for ops::Range<T> {
98    fn start(&self) -> Option<&T> { Some(&self.start) }
99
100    fn end(&self) -> Option<&T> { Some(&self.end) }
101}
102
103impl<T> From<ops::RangeFrom<T>> for Partition<T> {
104    #[inline]
105    fn from(ops::RangeFrom { start }: ops::RangeFrom<T>) -> Self {
106        Partition {
107            start: Some(start),
108            end: None,
109        }
110    }
111}
112
113impl<T> PartitionBounds<T> for ops::RangeFrom<T> {
114    fn start(&self) -> Option<&T> { Some(&self.start) }
115
116    fn end(&self) -> Option<&T> { None }
117}
118
119impl<T> From<ops::RangeTo<T>> for Partition<T> {
120    #[inline]
121    fn from(ops::RangeTo { end }: ops::RangeTo<T>) -> Self {
122        Partition {
123            start: None,
124            end: Some(end),
125        }
126    }
127}
128
129impl<T> PartitionBounds<T> for ops::RangeTo<T> {
130    fn start(&self) -> Option<&T> { None }
131
132    fn end(&self) -> Option<&T> { Some(&self.end) }
133}
134
135impl<T> From<ops::RangeFull> for Partition<T> {
136    #[inline]
137    fn from(ops::RangeFull: ops::RangeFull) -> Self {
138        Self {
139            start: None,
140            end: None,
141        }
142    }
143}
144
145impl<T> PartitionBounds<T> for ops::RangeFull {
146    fn start(&self) -> Option<&T> { None }
147
148    fn end(&self) -> Option<&T> { None }
149}
150
151impl<T> From<(Option<T>, Option<T>)> for Partition<T> {
152    #[inline]
153    fn from((start, end): (Option<T>, Option<T>)) -> Self { Self { start, end } }
154}
155
156impl<T> PartitionBounds<T> for (Option<T>, Option<T>) {
157    fn start(&self) -> Option<&T> { self.0.as_ref() }
158
159    fn end(&self) -> Option<&T> { self.1.as_ref() }
160}
161
162impl<T> PartitionBounds<T> for Partition<T> {
163    fn start(&self) -> Option<&T> { self.start.as_ref() }
164
165    fn end(&self) -> Option<&T> { self.end.as_ref() }
166}
167
168#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
169pub struct PartitionMap<K, V> {
170    unbounded_start: V,
171    ranges_from: BTreeMap<K, V>,
172}
173
174// TODO: const Default?
175impl<K, V: Default> Default for PartitionMap<K, V> {
176    fn default() -> Self { Self::new(V::default()) }
177}
178
179impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for PartitionMap<K, V> {
180    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
181        self.partitions()
182            .fold(&mut f.debug_map(), |d, (k, v)| d.entry(&k, &v))
183            .finish()
184    }
185}
186
187impl<K, V> PartitionMap<K, V> {
188    #[inline]
189    #[must_use]
190    pub const fn new(unbounded_start: V) -> Self {
191        Self {
192            unbounded_start,
193            ranges_from: BTreeMap::new(),
194        }
195    }
196
197    #[inline]
198    #[must_use]
199    pub fn partitions(&self) -> Partitions<'_, K, V> { Partitions::new(self) }
200
201    #[inline]
202    #[must_use]
203    pub fn into_partitions(self) -> IntoPartitions<K, V> { IntoPartitions::new(self) }
204
205    #[inline]
206    #[must_use]
207    pub fn keys(&self) -> Keys<'_, K, V> { Keys(Partitions::new(self)) }
208
209    #[inline]
210    #[must_use]
211    pub fn values(&self) -> Values<'_, K, V> { Values(Partitions::new(self)) }
212}
213
214#[cfg(any(test, feature = "test"))]
215impl<K, V: PartialEq> PartitionMap<K, V> {
216    fn assert_invariants(&self) {
217        let mut last = &self.unbounded_start;
218
219        for val in self.ranges_from.values() {
220            assert!(val != mem::replace(&mut last, val));
221        }
222    }
223}
224
225impl<K: Ord, V> PartitionMap<K, V> {
226    #[inline]
227    pub fn sample<T: ?Sized + Ord>(&self, at: &T) -> &V
228    where K: Borrow<T> {
229        self.ranges_from
230            .range((Bound::Unbounded, Bound::Included(at)))
231            .next_back()
232            .map_or(&self.unbounded_start, |(_, v)| v)
233    }
234}
235
236impl<K: Copy + Ord, V> PartitionMap<&K, V> {
237    #[inline]
238    pub fn copied_keys(self) -> PartitionMap<K, V> {
239        let Self {
240            unbounded_start,
241            ranges_from,
242        } = self;
243
244        PartitionMap {
245            unbounded_start,
246            ranges_from: ranges_from.into_iter().map(|(&k, v)| (k, v)).collect(),
247        }
248    }
249}
250
251fn check_bounds<T: Ord, B: PartitionBounds<T>>(range: B) -> Option<(Option<T>, Option<T>)> {
252    let Partition { start, end } = range.into();
253
254    if let (Some(s), Some(e)) = (&start, &end) {
255        match s.cmp(e) {
256            Ordering::Less => (),
257            Ordering::Equal => return None,
258            Ordering::Greater => panic!("Invalid range, start is greater than end"),
259        }
260    }
261
262    Some((start, end))
263}
264
265impl<K: Clone + Ord, V: Clone + PartialEq> PartitionMap<K, V> {
266    pub fn from_iter_with_default<B: PartitionBounds<K>, I: IntoIterator<Item = (B, V)>>(
267        it: I,
268        default: V,
269    ) -> Self {
270        let mut me = Self::new(default);
271        me.extend(it);
272        me
273    }
274
275    fn set_internal<B: PartitionBounds<K>>(&mut self, range: B, value: V, over: &mut Vec<K>) {
276        let Some((start, end)) = check_bounds(range) else {
277            return;
278        };
279
280        debug_assert!(over.is_empty());
281        over.extend(
282            self.ranges_from
283                .range((as_closed(&start), as_closed(&end)))
284                .map(|(k, _)| k.clone()),
285        );
286
287        let end = end.map(|e| match over.pop() {
288            Some(o) => (e, Some(Cow::Owned(self.ranges_from.remove(&o).unwrap()))),
289            None => (e, None),
290        });
291
292        for key in over.drain(..) {
293            let ok = self.ranges_from.remove(&key).is_some();
294            debug_assert!(ok);
295        }
296
297        let start_value = start
298            .as_ref()
299            .and_then(|s| {
300                self.ranges_from
301                    .range((Bound::Unbounded, Bound::Excluded(s)))
302                    .next_back()
303            })
304            .map_or(&self.unbounded_start, |(_, v)| v);
305
306        let end = end.and_then(|(e, v)| {
307            let end_val = v.unwrap_or(Cow::Borrowed(start_value));
308            (end_val != Cow::Borrowed(&value)).then(|| (e, end_val.into_owned()))
309        });
310
311        if *start_value != value {
312            if let Some(start) = start {
313                let ok = self.ranges_from.insert(start, value).is_none();
314                debug_assert!(ok);
315            } else {
316                self.unbounded_start = value;
317            }
318        }
319
320        if let Some((end, value)) = end {
321            let ok = self.ranges_from.insert(end, value).is_none();
322            debug_assert!(ok);
323        }
324    }
325
326    #[inline]
327    pub fn set<B: PartitionBounds<K>>(&mut self, range: B, value: V) {
328        self.set_internal(range, value, &mut vec![]);
329
330        #[cfg(any(test, feature = "test"))]
331        self.assert_invariants();
332    }
333
334    // TODO: this could maybe be faster but like.  ghh
335    fn update_internal<B: PartitionBounds<K>, F: FnMut(Partition<&K>, &V) -> V>(
336        &mut self,
337        range: B,
338        mut f: F,
339        over: &mut Vec<(K, V)>,
340        set_over: &mut Vec<K>,
341    ) {
342        let Some((start, end)) = check_bounds(range) else {
343            return;
344        };
345
346        debug_assert!(over.is_empty());
347        over.extend(
348            self.ranges_from
349                .range((as_open(&start), as_open(&end)))
350                .map(|(k, v)| (k.clone(), v.clone())),
351        );
352
353        let mut start = start;
354        // TODO: maybe Cow this?  idk if it's worth performance-wise
355        let mut orig_value = start
356            .as_ref()
357            .and_then(|s| {
358                self.ranges_from
359                    .range((Bound::Unbounded, Bound::Included(s)))
360                    .next_back()
361            })
362            .map_or(&self.unbounded_start, |(_, v)| v)
363            .clone();
364
365        for (end, next_value) in over.drain(..) {
366            let end = Some(end);
367            debug_assert!(end > start);
368
369            let value = f(
370                Partition {
371                    start: start.as_ref(),
372                    end: end.as_ref(),
373                },
374                &orig_value,
375            );
376            if value != orig_value {
377                self.set_internal((start, end.clone()), value, set_over);
378            }
379
380            start = end;
381            orig_value = next_value;
382        }
383
384        if end.is_none() || end > start {
385            let value = f(
386                Partition {
387                    start: start.as_ref(),
388                    end: end.as_ref(),
389                },
390                &orig_value,
391            );
392            if value != orig_value {
393                self.set_internal((start, end), value, set_over);
394            }
395        }
396    }
397
398    pub fn update<B: PartitionBounds<K>, F: FnMut(Partition<&K>, &V) -> V>(
399        &mut self,
400        range: B,
401        f: F,
402    ) {
403        self.update_internal(range, f, &mut vec![], &mut vec![]);
404
405        #[cfg(any(test, feature = "test"))]
406        self.assert_invariants();
407    }
408
409    pub fn update_all<
410        I: IntoIterator<Item: PartitionBounds<K>>,
411        F: FnMut(Partition<&K>, &V) -> V,
412    >(
413        &mut self,
414        it: I,
415        mut f: F,
416    ) {
417        let mut over = vec![];
418        let mut set_over = vec![];
419
420        for range in it {
421            self.update_internal(range, &mut f, &mut over, &mut set_over);
422        }
423
424        #[cfg(any(test, feature = "test"))]
425        self.assert_invariants();
426    }
427
428    pub fn fold<F: FnMut((Partition<&K>, &V), &V) -> V>(
429        &mut self,
430        other: &PartitionMap<K, V>,
431        mut f: F,
432    ) {
433        let mut over = vec![];
434        let mut set_over = vec![];
435
436        for (part, value) in other.partitions() {
437            self.update_internal(
438                part.to_owned(),
439                |k, v| f((k, v), value),
440                &mut over,
441                &mut set_over,
442            );
443        }
444
445        #[cfg(any(test, feature = "test"))]
446        self.assert_invariants();
447    }
448
449    #[must_use]
450    pub fn folded<F: FnMut((Partition<&K>, &V), &V) -> V>(
451        mut self,
452        other: &PartitionMap<K, V>,
453        f: F,
454    ) -> Self {
455        self.fold(other, f);
456        self
457    }
458}
459
460#[expect(
461    clippy::ref_option,
462    reason = "This is a pattern-specific helper method"
463)]
464fn as_open<T>(opt: &Option<T>) -> ops::Bound<&T> {
465    opt.as_ref().map_or(Bound::Unbounded, Bound::Excluded)
466}
467
468#[expect(
469    clippy::ref_option,
470    reason = "This is a pattern-specific helper method"
471)]
472fn as_closed<T>(opt: &Option<T>) -> Bound<&T> {
473    opt.as_ref().map_or(Bound::Unbounded, Bound::Included)
474}
475
476impl<K: Clone + Ord, V: Clone + PartialEq, B: PartitionBounds<K>> Extend<(B, V)>
477    for PartitionMap<K, V>
478{
479    fn extend<T: IntoIterator<Item = (B, V)>>(&mut self, it: T) {
480        let mut over = vec![];
481
482        for (range, value) in it {
483            self.set_internal(range, value, &mut over);
484        }
485
486        #[cfg(any(test, feature = "test"))]
487        self.assert_invariants();
488    }
489}
490
491impl<K: Clone + Ord, V: Clone + Default + PartialEq, B: PartitionBounds<K>> FromIterator<(B, V)>
492    for PartitionMap<K, V>
493{
494    fn from_iter<I: IntoIterator<Item = (B, V)>>(it: I) -> Self {
495        Self::from_iter_with_default(it, V::default())
496    }
497}
498
499#[derive(Debug, Clone)]
500struct PartitionsInner<'a, K, V> {
501    start: Option<&'a K>,
502    value: &'a V,
503    iter: btree_map::Iter<'a, K, V>,
504}
505
506#[derive(Debug, Clone)]
507#[repr(transparent)]
508pub struct Partitions<'a, K, V>(Option<PartitionsInner<'a, K, V>>);
509
510impl<'a, K, V> Partitions<'a, K, V> {
511    #[inline]
512    fn new(map: &'a PartitionMap<K, V>) -> Self {
513        Self(Some(PartitionsInner {
514            start: None,
515            value: &map.unbounded_start,
516            iter: map.ranges_from.iter(),
517        }))
518    }
519}
520
521impl<'a, K, V> Iterator for Partitions<'a, K, V> {
522    type Item = (Partition<&'a K>, &'a V);
523
524    fn next(&mut self) -> Option<Self::Item> {
525        let this = self.0.as_mut()?;
526
527        Some(if let Some((end, next_val)) = this.iter.next() {
528            let start = this.start.replace(end);
529            let value = mem::replace(&mut this.value, next_val);
530            (
531                Partition {
532                    start,
533                    end: Some(end),
534                },
535                value,
536            )
537        } else {
538            let PartitionsInner {
539                start,
540                value,
541                iter: _,
542            } = self.0.take().unwrap_or_else(|| unreachable!());
543            (Partition { start, end: None }, value)
544        })
545    }
546}
547
548#[derive(Debug)]
549struct IntoPartitionsInner<K, V> {
550    start: Option<K>,
551    value: V,
552    iter: btree_map::IntoIter<K, V>,
553}
554
555#[derive(Debug)]
556#[repr(transparent)]
557pub struct IntoPartitions<K, V>(Option<IntoPartitionsInner<K, V>>);
558
559impl<K, V> IntoPartitions<K, V> {
560    #[inline]
561    fn new(map: PartitionMap<K, V>) -> Self {
562        Self(Some(IntoPartitionsInner {
563            start: None,
564            value: map.unbounded_start,
565            iter: map.ranges_from.into_iter(),
566        }))
567    }
568}
569
570impl<K: Clone, V> Iterator for IntoPartitions<K, V> {
571    type Item = (Partition<K>, V);
572
573    fn next(&mut self) -> Option<Self::Item> {
574        let this = self.0.as_mut()?;
575
576        Some(if let Some((end, next_val)) = this.iter.next() {
577            let start = this.start.replace(end.clone());
578            let value = mem::replace(&mut this.value, next_val);
579            (
580                Partition {
581                    start,
582                    end: Some(end),
583                },
584                value,
585            )
586        } else {
587            let IntoPartitionsInner {
588                start,
589                value,
590                iter: _,
591            } = self.0.take().unwrap_or_else(|| unreachable!());
592            (Partition { start, end: None }, value)
593        })
594    }
595}
596
597#[derive(Debug, Clone)]
598pub struct Keys<'a, K, V>(Partitions<'a, K, V>);
599
600impl<'a, K, V> Iterator for Keys<'a, K, V> {
601    type Item = Partition<&'a K>;
602
603    #[inline]
604    fn next(&mut self) -> Option<Self::Item> { self.0.next().map(|(p, _)| p) }
605}
606
607#[derive(Debug, Clone)]
608pub struct Values<'a, K, V>(Partitions<'a, K, V>);
609
610impl<'a, K, V> Iterator for Values<'a, K, V> {
611    type Item = &'a V;
612
613    #[inline]
614    fn next(&mut self) -> Option<Self::Item> { self.0.next().map(|(_, v)| v) }
615}
616
617#[cfg(test)]
618mod test {
619    use std::{cmp::Reverse, ops::Range};
620
621    use proptest::prelude::*;
622
623    use super::*;
624
625    type Map = PartitionMap<u64, char>;
626
627    fn assert_parts<'a, P: IntoIterator<Item = &'a (Partition<u64>, char)>>(map: &Map, parts: P) {
628        assert_eq!(
629            map.partitions().collect::<Vec<_>>(),
630            parts
631                .into_iter()
632                .map(|(Partition { start, end }, value)| (
633                    Partition {
634                        start: start.as_ref(),
635                        end: end.as_ref(),
636                    },
637                    value
638                ))
639                .collect::<Vec<_>>(),
640        );
641    }
642
643    fn intersect_regression_op(lhs: char, rhs: char) -> char {
644        if lhs == 'b' && rhs == 'b' {
645            'b'
646        } else {
647            'a'
648        }
649    }
650
651    #[test]
652    fn range_set_intersect_regression_update() {
653        let mut lhs = Map::new('a');
654        lhs.extend([part(1.., 'b')]);
655
656        lhs.update(..1, |_, v| intersect_regression_op(*v, 'b'));
657        lhs.update(1.., |_, v| intersect_regression_op(*v, 'a'));
658
659        assert_eq!(lhs, Map::new('a'));
660    }
661
662    #[test]
663    fn range_set_intersect_regression_fold() {
664        let mut lhs = Map::new('a');
665        lhs.extend([part(1.., 'b')]);
666        let mut rhs = Map::new('a');
667        rhs.extend([part(..1, 'b')]);
668
669        lhs.fold(&rhs, |(_, v), s| intersect_regression_op(*v, *s));
670
671        assert_eq!(lhs, Map::new('a'));
672    }
673
674    fn assert_sanity<'a, I: IntoIterator, P: IntoIterator<Item = &'a (Partition<u64>, char)>>(
675        u: char,
676        items: I,
677        parts: P,
678    ) where
679        Map: Extend<I::Item>,
680    {
681        let mut map = Map::new(u);
682        map.extend(items);
683        assert_parts(&map, parts);
684    }
685
686    fn assert_sanity_2<'a, A, B, P: IntoIterator<Item = &'a (Partition<u64>, char)>>(
687        u: char,
688        a: A,
689        b: B,
690        parts: P,
691    ) where
692        Map: Extend<A> + Extend<B>,
693    {
694        let mut map = Map::new(u);
695        map.extend([a]);
696        map.extend([b]);
697        assert_parts(&map, parts);
698    }
699
700    fn part<B: super::PartitionBounds<K>, K, V>(b: B, v: V) -> (Partition<K>, V) { (b.into(), v) }
701
702    #[test]
703    #[expect(
704        clippy::too_many_lines,
705        reason = "Gestures vaguely at exhaustive handwritten base cases"
706    )]
707    fn test_sanity() {
708        // -----[=====)-----
709        //  0   2 3   5 6
710        //    1     4     7
711
712        //      0 1 2 3 4 5 6 7
713        // 0,1 -[+)-[=====)-----
714        // 0,2 -[++)[=====)-----
715        // 0,3 -[++++)[===)-----
716        // 0,5 -[+++++++++)-----
717        // 0,6 -[+++++++++++)---
718        // 2,3 -----[)[===)-----
719        // 2,5 -----[+++++)-----
720        // 2,6 -----[+++++++)---
721        // 3,4 -----[)[+)[)-----
722        // 3,5 -----[)[+++)-----
723        // 3,6 -----[)[+++++)---
724        // 5,6 -----[====)[+)---
725        // 6,7 -----[=====)-[+)-
726
727        assert_sanity::<[(Range<u64>, char); 0], _>('a', [], &[part(.., 'a')]);
728        assert_sanity('a', [(2..5, 'b')], &[
729            part(..2, 'a'),
730            part(2..5, 'b'),
731            part(5.., 'a'),
732        ]);
733
734        for t in [0, 2, 3, 5, 6] {
735            assert_sanity('a', [(2..5, 'b'), (t..t, 'c')], &[
736                part(..2, 'a'),
737                part(2..5, 'b'),
738                part(5.., 'a'),
739            ]);
740        }
741
742        assert_sanity('a', [(2..5, 'b'), (0..1, 'c')], &[
743            part(..0, 'a'),
744            part(0..1, 'c'),
745            part(1..2, 'a'),
746            part(2..5, 'b'),
747            part(5.., 'a'),
748        ]);
749        assert_sanity('a', [(2..5, 'b'), (0..2, 'c')], &[
750            part(..0, 'a'),
751            part(0..2, 'c'),
752            part(2..5, 'b'),
753            part(5.., 'a'),
754        ]);
755        assert_sanity('a', [(2..5, 'b'), (0..3, 'c')], &[
756            part(..0, 'a'),
757            part(0..3, 'c'),
758            part(3..5, 'b'),
759            part(5.., 'a'),
760        ]);
761        assert_sanity('a', [(2..5, 'b'), (0..5, 'c')], &[
762            part(..0, 'a'),
763            part(0..5, 'c'),
764            part(5.., 'a'),
765        ]);
766        assert_sanity('a', [(2..5, 'b'), (0..6, 'c')], &[
767            part(..0, 'a'),
768            part(0..6, 'c'),
769            part(6.., 'a'),
770        ]);
771        assert_sanity('a', [(2..5, 'b'), (2..3, 'c')], &[
772            part(..2, 'a'),
773            part(2..3, 'c'),
774            part(3..5, 'b'),
775            part(5.., 'a'),
776        ]);
777        assert_sanity('a', [(2..5, 'b'), (2..5, 'c')], &[
778            part(..2, 'a'),
779            part(2..5, 'c'),
780            part(5.., 'a'),
781        ]);
782        assert_sanity('a', [(2..5, 'b'), (2..6, 'c')], &[
783            part(..2, 'a'),
784            part(2..6, 'c'),
785            part(6.., 'a'),
786        ]);
787        assert_sanity('a', [(2..5, 'b'), (3..4, 'c')], &[
788            part(..2, 'a'),
789            part(2..3, 'b'),
790            part(3..4, 'c'),
791            part(4..5, 'b'),
792            part(5.., 'a'),
793        ]);
794        assert_sanity('a', [(2..5, 'b'), (3..5, 'c')], &[
795            part(..2, 'a'),
796            part(2..3, 'b'),
797            part(3..5, 'c'),
798            part(5.., 'a'),
799        ]);
800        assert_sanity('a', [(2..5, 'b'), (3..6, 'c')], &[
801            part(..2, 'a'),
802            part(2..3, 'b'),
803            part(3..6, 'c'),
804            part(6.., 'a'),
805        ]);
806        assert_sanity('a', [(2..5, 'b'), (5..6, 'c')], &[
807            part(..2, 'a'),
808            part(2..5, 'b'),
809            part(5..6, 'c'),
810            part(6.., 'a'),
811        ]);
812        assert_sanity('a', [(2..5, 'b'), (6..7, 'c')], &[
813            part(..2, 'a'),
814            part(2..5, 'b'),
815            part(5..6, 'a'),
816            part(6..7, 'c'),
817            part(7.., 'a'),
818        ]);
819
820        assert_sanity('a', [(2..5, 'b'), (0..1, 'b')], &[
821            part(..0, 'a'),
822            part(0..1, 'b'),
823            part(1..2, 'a'),
824            part(2..5, 'b'),
825            part(5.., 'a'),
826        ]);
827        assert_sanity('a', [(2..5, 'b'), (0..2, 'b')], &[
828            part(..0, 'a'),
829            part(0..5, 'b'),
830            part(5.., 'a'),
831        ]);
832        assert_sanity('a', [(2..5, 'b'), (0..3, 'b')], &[
833            part(..0, 'a'),
834            part(0..5, 'b'),
835            part(5.., 'a'),
836        ]);
837        assert_sanity('a', [(2..5, 'b'), (0..5, 'b')], &[
838            part(..0, 'a'),
839            part(0..5, 'b'),
840            part(5.., 'a'),
841        ]);
842        assert_sanity('a', [(2..5, 'b'), (0..6, 'b')], &[
843            part(..0, 'a'),
844            part(0..6, 'b'),
845            part(6.., 'a'),
846        ]);
847        assert_sanity('a', [(2..5, 'b'), (2..3, 'b')], &[
848            part(..2, 'a'),
849            part(2..5, 'b'),
850            part(5.., 'a'),
851        ]);
852        assert_sanity('a', [(2..5, 'b'), (2..5, 'b')], &[
853            part(..2, 'a'),
854            part(2..5, 'b'),
855            part(5.., 'a'),
856        ]);
857        assert_sanity('a', [(2..5, 'b'), (2..6, 'b')], &[
858            part(..2, 'a'),
859            part(2..6, 'b'),
860            part(6.., 'a'),
861        ]);
862        assert_sanity('a', [(2..5, 'b'), (3..4, 'b')], &[
863            part(..2, 'a'),
864            part(2..5, 'b'),
865            part(5.., 'a'),
866        ]);
867        assert_sanity('a', [(2..5, 'b'), (3..5, 'b')], &[
868            part(..2, 'a'),
869            part(2..5, 'b'),
870            part(5.., 'a'),
871        ]);
872        assert_sanity('a', [(2..5, 'b'), (3..6, 'b')], &[
873            part(..2, 'a'),
874            part(2..6, 'b'),
875            part(6.., 'a'),
876        ]);
877        assert_sanity('a', [(2..5, 'b'), (5..6, 'b')], &[
878            part(..2, 'a'),
879            part(2..6, 'b'),
880            part(6.., 'a'),
881        ]);
882        assert_sanity('a', [(2..5, 'b'), (6..7, 'b')], &[
883            part(..2, 'a'),
884            part(2..5, 'b'),
885            part(5..6, 'a'),
886            part(6..7, 'b'),
887            part(7.., 'a'),
888        ]);
889
890        assert_sanity('a', [(2..5, 'b'), (0..1, 'a')], &[
891            part(..2, 'a'),
892            part(2..5, 'b'),
893            part(5.., 'a'),
894        ]);
895        assert_sanity('a', [(2..5, 'b'), (0..2, 'a')], &[
896            part(..2, 'a'),
897            part(2..5, 'b'),
898            part(5.., 'a'),
899        ]);
900        assert_sanity('a', [(2..5, 'b'), (0..3, 'a')], &[
901            part(..3, 'a'),
902            part(3..5, 'b'),
903            part(5.., 'a'),
904        ]);
905        assert_sanity('a', [(2..5, 'b'), (0..5, 'a')], &[part(.., 'a')]);
906        assert_sanity('a', [(2..5, 'b'), (0..6, 'a')], &[part(.., 'a')]);
907        assert_sanity('a', [(2..5, 'b'), (2..3, 'a')], &[
908            part(..3, 'a'),
909            part(3..5, 'b'),
910            part(5.., 'a'),
911        ]);
912        assert_sanity('a', [(2..5, 'b'), (2..5, 'a')], &[part(.., 'a')]);
913        assert_sanity('a', [(2..5, 'b'), (2..6, 'a')], &[part(.., 'a')]);
914        assert_sanity('a', [(2..5, 'b'), (3..4, 'a')], &[
915            part(..2, 'a'),
916            part(2..3, 'b'),
917            part(3..4, 'a'),
918            part(4..5, 'b'),
919            part(5.., 'a'),
920        ]);
921        assert_sanity('a', [(2..5, 'b'), (3..5, 'a')], &[
922            part(..2, 'a'),
923            part(2..3, 'b'),
924            part(3.., 'a'),
925        ]);
926        assert_sanity('a', [(2..5, 'b'), (3..6, 'a')], &[
927            part(..2, 'a'),
928            part(2..3, 'b'),
929            part(3.., 'a'),
930        ]);
931        assert_sanity('a', [(2..5, 'b'), (5..6, 'a')], &[
932            part(..2, 'a'),
933            part(2..5, 'b'),
934            part(5.., 'a'),
935        ]);
936        assert_sanity('a', [(2..5, 'b'), (6..7, 'a')], &[
937            part(..2, 'a'),
938            part(2..5, 'b'),
939            part(5.., 'a'),
940        ]);
941
942        // ---[===)---
943        //  0 1 2 3 4
944
945        //      0 1 2 3 4
946        // ..0 +)-[===)---
947        // ..1 ++)[===)---
948        // ..2 ++++)[=)---
949        // ..3 +++++++)---
950        // ..4 +++++++++)-
951        // ..  +++++++++++
952        // 0.. -[+++++++++
953        // 1.. ---[+++++++
954        // 2.. ---[)[+++++
955        // 3.. ---[==)[+++
956        // 4.. ---[===)-[+
957
958        assert_sanity_2('a', (1..3, 'b'), (..0, 'c'), &[
959            part(..0, 'c'),
960            part(0..1, 'a'),
961            part(1..3, 'b'),
962            part(3.., 'a'),
963        ]);
964        assert_sanity_2('a', (1..3, 'b'), (..1, 'c'), &[
965            part(..1, 'c'),
966            part(1..3, 'b'),
967            part(3.., 'a'),
968        ]);
969        assert_sanity_2('a', (1..3, 'b'), (..2, 'c'), &[
970            part(..2, 'c'),
971            part(2..3, 'b'),
972            part(3.., 'a'),
973        ]);
974        assert_sanity_2('a', (1..3, 'b'), (..3, 'c'), &[
975            part(..3, 'c'),
976            part(3.., 'a'),
977        ]);
978        assert_sanity_2('a', (1..3, 'b'), (..4, 'c'), &[
979            part(..4, 'c'),
980            part(4.., 'a'),
981        ]);
982        assert_sanity_2('a', (1..3, 'b'), (.., 'c'), &[part(.., 'c')]);
983        assert_sanity_2('a', (1..3, 'b'), (0.., 'c'), &[
984            part(..0, 'a'),
985            part(0.., 'c'),
986        ]);
987        assert_sanity_2('a', (1..3, 'b'), (1.., 'c'), &[
988            part(..1, 'a'),
989            part(1.., 'c'),
990        ]);
991        assert_sanity_2('a', (1..3, 'b'), (2.., 'c'), &[
992            part(..1, 'a'),
993            part(1..2, 'b'),
994            part(2.., 'c'),
995        ]);
996        assert_sanity_2('a', (1..3, 'b'), (3.., 'c'), &[
997            part(..1, 'a'),
998            part(1..3, 'b'),
999            part(3.., 'c'),
1000        ]);
1001        assert_sanity_2('a', (1..3, 'b'), (4.., 'c'), &[
1002            part(..1, 'a'),
1003            part(1..3, 'b'),
1004            part(3..4, 'a'),
1005            part(4.., 'c'),
1006        ]);
1007
1008        assert_sanity_2('a', (1..3, 'b'), (..0, 'b'), &[
1009            part(..0, 'b'),
1010            part(0..1, 'a'),
1011            part(1..3, 'b'),
1012            part(3.., 'a'),
1013        ]);
1014        assert_sanity_2('a', (1..3, 'b'), (..1, 'b'), &[
1015            part(..3, 'b'),
1016            part(3.., 'a'),
1017        ]);
1018        assert_sanity_2('a', (1..3, 'b'), (..2, 'b'), &[
1019            part(..3, 'b'),
1020            part(3.., 'a'),
1021        ]);
1022        assert_sanity_2('a', (1..3, 'b'), (..3, 'b'), &[
1023            part(..3, 'b'),
1024            part(3.., 'a'),
1025        ]);
1026        assert_sanity_2('a', (1..3, 'b'), (..4, 'b'), &[
1027            part(..4, 'b'),
1028            part(4.., 'a'),
1029        ]);
1030        assert_sanity_2('a', (1..3, 'b'), (.., 'b'), &[part(.., 'b')]);
1031        assert_sanity_2('a', (1..3, 'b'), (0.., 'b'), &[
1032            part(..0, 'a'),
1033            part(0.., 'b'),
1034        ]);
1035        assert_sanity_2('a', (1..3, 'b'), (1.., 'b'), &[
1036            part(..1, 'a'),
1037            part(1.., 'b'),
1038        ]);
1039        assert_sanity_2('a', (1..3, 'b'), (2.., 'b'), &[
1040            part(..1, 'a'),
1041            part(1.., 'b'),
1042        ]);
1043        assert_sanity_2('a', (1..3, 'b'), (3.., 'b'), &[
1044            part(..1, 'a'),
1045            part(1.., 'b'),
1046        ]);
1047        assert_sanity_2('a', (1..3, 'b'), (4.., 'b'), &[
1048            part(..1, 'a'),
1049            part(1..3, 'b'),
1050            part(3..4, 'a'),
1051            part(4.., 'b'),
1052        ]);
1053
1054        assert_sanity_2('a', (1..3, 'b'), (..0, 'a'), &[
1055            part(..1, 'a'),
1056            part(1..3, 'b'),
1057            part(3.., 'a'),
1058        ]);
1059        assert_sanity_2('a', (1..3, 'b'), (..1, 'a'), &[
1060            part(..1, 'a'),
1061            part(1..3, 'b'),
1062            part(3.., 'a'),
1063        ]);
1064        assert_sanity_2('a', (1..3, 'b'), (..2, 'a'), &[
1065            part(..2, 'a'),
1066            part(2..3, 'b'),
1067            part(3.., 'a'),
1068        ]);
1069        assert_sanity_2('a', (1..3, 'b'), (..3, 'a'), &[part(.., 'a')]);
1070        assert_sanity_2('a', (1..3, 'b'), (..4, 'a'), &[part(.., 'a')]);
1071        assert_sanity_2('a', (1..3, 'b'), (.., 'a'), &[part(.., 'a')]);
1072        assert_sanity_2('a', (1..3, 'b'), (0.., 'a'), &[part(.., 'a')]);
1073        assert_sanity_2('a', (1..3, 'b'), (1.., 'a'), &[part(.., 'a')]);
1074        assert_sanity_2('a', (1..3, 'b'), (2.., 'a'), &[
1075            part(..1, 'a'),
1076            part(1..2, 'b'),
1077            part(2.., 'a'),
1078        ]);
1079        assert_sanity_2('a', (1..3, 'b'), (3.., 'a'), &[
1080            part(..1, 'a'),
1081            part(1..3, 'b'),
1082            part(3.., 'a'),
1083        ]);
1084        assert_sanity_2('a', (1..3, 'b'), (4.., 'a'), &[
1085            part(..1, 'a'),
1086            part(1..3, 'b'),
1087            part(3.., 'a'),
1088        ]);
1089    }
1090
1091    type Part = (Partition<u64>, char);
1092
1093    fn check_part((Partition { start, end }, _): &Part) -> bool {
1094        start.zip(*end).is_none_or(|(s, e)| e >= s)
1095    }
1096
1097    fn test_extend_impl(c: char, v: Vec<Part>) {
1098        let mut map = Map::new(c);
1099        map.extend(v.clone());
1100
1101        let event_vec = {
1102            let mut e: Vec<_> = v
1103                .into_iter()
1104                .enumerate()
1105                .flat_map(|(i, (Partition { start, end }, value))| {
1106                    [
1107                        Some((start, i, Reverse(Some(value)))),
1108                        end.map(|e| (Some(e), i, Reverse(None))),
1109                    ]
1110                    .into_iter()
1111                    .flatten()
1112                })
1113                .collect();
1114            e.sort();
1115            e
1116        };
1117        let events =
1118            event_vec
1119                .iter()
1120                .fold(BTreeMap::<_, Vec<_>>::new(), |mut m, (t, i, Reverse(v))| {
1121                    m.entry(t).or_default().push((i, v));
1122                    m
1123                });
1124        let mut enabled = BTreeMap::new();
1125        let mut parts = vec![];
1126        let mut start = None;
1127        let mut value = &c;
1128
1129        for (time, curr_events) in events {
1130            for (index, event_val) in curr_events {
1131                match event_val {
1132                    Some(v) => assert!(enabled.insert(index, v).is_none()),
1133                    None => assert!(enabled.remove(&index).is_some()),
1134                }
1135            }
1136
1137            let next_val = enabled.last_key_value().map_or(&c, |(_, v)| *v);
1138            let time = time.as_ref();
1139
1140            if next_val != value {
1141                if time.is_some() {
1142                    parts.push((Partition { start, end: time }, value));
1143                }
1144
1145                start = time;
1146                value = next_val;
1147            }
1148        }
1149
1150        parts.push((Partition { start, end: None }, value));
1151
1152        assert_eq!(map.partitions().collect::<Vec<_>>(), parts);
1153    }
1154
1155    fn test_update_sanity_impl(c: char, v: Vec<Part>) {
1156        let mut ext = Map::new(c);
1157        ext.extend(v.clone());
1158
1159        let mut upd = Map::new(c);
1160        let mut over = vec![];
1161        let mut set_over = vec![];
1162        for (Partition { start, end }, value) in v {
1163            upd.update_internal((start, end), |_, _| value, &mut over, &mut set_over);
1164        }
1165    }
1166
1167    fn prop_part(
1168        t: impl Clone + Strategy<Value = u64>,
1169        c: impl Strategy<Value = char>,
1170    ) -> impl Strategy<Value = Part> {
1171        (prop::option::of(t.clone()), prop::option::of(t), c)
1172            .prop_map(|(start, end, value)| {
1173                let (start, end) = if start.zip(end).is_some_and(|(s, e)| e < s) {
1174                    (end, start)
1175                } else {
1176                    (start, end)
1177                };
1178
1179                (Partition { start, end }, value)
1180            })
1181            .prop_filter("Partitions must be valid", check_part)
1182    }
1183
1184    proptest! {
1185        #[test]
1186        fn test_extend(
1187            c in any::<char>(),
1188            v in prop::collection::vec(
1189                prop_part(any::<u64>(), any::<char>()),
1190                0..256,
1191            ),
1192        ) {
1193            test_extend_impl(c, v);
1194        }
1195
1196        #[test]
1197        fn test_update_sanity(
1198            c in any::<char>(),
1199            v in prop::collection::vec(
1200                prop_part(any::<u64>(), any::<char>()),
1201                0..256,
1202            ),
1203        ) {
1204            test_update_sanity_impl(c, v);
1205        }
1206
1207        #[test]
1208        fn test_extend_clobber(
1209            c in prop::char::range('a', 'z'),
1210            v in prop::collection::vec(
1211                prop_part(0_u64..16, prop::char::range('a', 'z')),
1212                0..512
1213            ),
1214        ) {
1215            test_extend_impl(c, v);
1216        }
1217    }
1218}