common-range-tools 1.0.0

Library to find Common Range Intersections
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
//! The [crate::utils] module represents the static methods that drive most of the overlap and consolidation intenrals.
//! The static methods are exposed for general use and testing.

use crate::{CpCmp, GetBeginEnd, GetBeginEndOption, Mrs, builder::IncDecCpCmp};
use std::{
    cmp::Ordering,
    mem,
    ops::{
        Bound::{Excluded, Included, Unbounded},
        RangeBounds,
    },
};

/// This enum is used to represent positional relationships between 2 ranges.
///  - before a range: [RangeRelation::Before]
///  - overlap with a range: [RangeRelation::Overlap]
///  - after a range: [RangeRelation::Overlap]
///
/// The additional states, represent the initialization of the set.
///  - empty or no data: [RangeRelation::Invalid]
///  - last or final: [RangeRelation::Last]
pub enum RangeRelation<T> {
    /// Range a is before range b
    Before(T),

    /// Range a and b overlap
    Overlap(T),

    /// Range a is after range b
    After(T),

    /// Represents final set of data
    Last(T),

    /// Denotes a was not valid
    Invalid(T),
}

impl<T> RangeRelation<T> {
    /// Unwraps the Value.
    pub fn unwrap(self) -> T {
        match self {
            RangeRelation::After(v)
            | RangeRelation::Before(v)
            | RangeRelation::Last(v)
            | RangeRelation::Invalid(v)
            | RangeRelation::Overlap(v) => return v,
        }
    }
    /// Unwraps the state of [RangeRelation::Invalid] or panics!.
    pub fn invalid(self) -> T {
        match self {
            RangeRelation::Invalid(data) => data,
            _ => panic!("Not Last!"),
        }
    }

    /// Unwraps the state of [RangeRelation::Last] or panics!
    pub fn last(self) -> T {
        match self {
            RangeRelation::Last(data) => data,
            _ => panic!("Not Last!"),
        }
    }

    /// Unwraps the state of [RangeRelation::Before] or panics!
    pub fn before(self) -> T {
        match self {
            RangeRelation::Before(data) => data,
            _ => panic!("Not Before!"),
        }
    }

    /// Unwraps the state of [RangeRelation::Overlap] or panics!
    pub fn overlap(self) -> T {
        match self {
            RangeRelation::Overlap(data) => data,
            _ => panic!("Not Overlap!"),
        }
    }

    /// Unwraps the state of [RangeRelation::After] or panics!
    pub fn after(self) -> T {
        match self {
            RangeRelation::After(data) => data,
            _ => panic!("Not After!"),
        }
    }

    /// Returns true if [RangeRelation::Last].
    pub fn is_last(&self) -> bool {
        match self {
            RangeRelation::Last(_) => true,
            _ => false,
        }
    }

    /// Returns true if [RangeRelation::Invalid].
    pub fn is_invalid(&self) -> bool {
        match self {
            RangeRelation::Invalid(_) => true,
            _ => false,
        }
    }

    /// Returns true if [RangeRelation::Overlap].
    pub fn is_overlap(&self) -> bool {
        match self {
            RangeRelation::Overlap(_) => true,
            _ => false,
        }
    }

    /// Returns true if [RangeRelation::Before].
    pub fn is_before(&self) -> bool {
        match self {
            RangeRelation::Before(_) => true,
            _ => false,
        }
    }

    /// Returns true if [RangeRelation::After].
    pub fn is_after(&self) -> bool {
        match self {
            RangeRelation::After(_) => true,
            _ => false,
        }
    }
}
/// Compares the positional relationship between a and b.
///
/// - [RangeRelation::Invalid] a was not a valid range.
/// - [RangeRelation::Before] a is before b.
/// - [RangeRelation::After] a is after b.
/// - [RangeRelation::Overlap] a and b overlap to some degree.
pub fn range_relation<T, R: GetBeginEnd<T>, N: GetBeginEnd<T>, C: CpCmp<T>>(
    a: &R,
    b: &N,
    t: &C,
) -> RangeRelation<()> {
    if t.is_invalid_set(a.get_begin(), a.get_end()) {
        return RangeRelation::Invalid(());
    } else if t.lt(a.get_end(), b.get_begin()) {
        return RangeRelation::Before(());
    } else if t.lt(b.get_end(), a.get_begin()) {
        return RangeRelation::After(());
    }

    return RangeRelation::Overlap(());
}

/// **Range to value Conversion**
///
/// This method takes a [std::ops::RangeBounds] and returns the calculted values for the type.
///
/// For conversion of start values
///   - [std::ops::Bound::Unbounded] becomes $t::MIN
///   - [std::ops::Bound::Included] value is not changed
///   - [std::ops::Bound::Excluded] value is incremented
///
/// For conversion of end values
///   - [std::ops::Bound::Unbounded] becomes $t::MAX
///   - [std::ops::Bound::Included] value is not changed
///   - [std::ops::Bound::Excluded] value is decremented
///
/// See [IncDecCpCmp] for more details.
///
/// Example of range to number conversion.
///
pub fn range_bounds_to_values<T, V>(
    range: &impl RangeBounds<T>,
    rebound: &V,
    cmp: &impl IncDecCpCmp<T, V>,
) -> Option<(T, T)> {
    if let Some(begin) = cmp.rebound_start(range.start_bound(), rebound)
        && let Some(end) = cmp.rebound_end(range.end_bound(), rebound)
    {
        return Some((begin, end));
    } else {
        return None;
    }
}

/// Compares range a and b and returns the **Forward Consolidation Order** [std::cmp::Ordering] value.
///
/// The sort order is meant to represent **Forward Consolidation Order** not tradtional range sort order.
/// **Forward Consolidation Order** is represented as earliest largest ranges first.
///
/// Put another way:
/// - GetBeginEnd.get_begin() asc
/// - GetBeginEnd.get_end() desc
///
/// # Panics!
/// If the [RangeBounds] cannot be converted to a computable range!
pub fn sort_forward<T, V, R: RangeBounds<T>, S: RangeBounds<T>, C: IncDecCpCmp<T, V>>(
    x: &R,
    y: &S,
    rebound: &V,
    t: &C,
) -> Ordering {
    let a: Mrs<T> = (range_bounds_to_values(x, rebound, t)).unwrap().into();
    let b: Mrs<T> = (range_bounds_to_values(y, rebound, t)).unwrap().into();
    if t.lt(b.get_begin(), a.get_begin()) {
        return Ordering::Greater;
    } else if t.lt(a.get_begin(), b.get_begin()) {
        return Ordering::Less;

    // anything below this point both begin values are the same
    } else if t.lt(a.get_end(), b.get_end()) {
        return Ordering::Greater;
    } else if t.lt(b.get_end(), a.get_end()) {
        return Ordering::Less;
    }
    // if we get here, begin and end are equal
    return Ordering::Equal;
}

/// Compares range a and b and returns the **Reverse Consolidation Order** [std::cmp::Ordering] value.
///
/// The sort order is meant to represent **Reverse Consolidation Order** not tradtional range sort order.
/// **Reverse Consolidation Order** is represented as latest largest ranges first.
///
/// Put another way:
/// - GetBeginEnd.get_end() desc
/// - GetBeginEnd.get_begin() asc
///
/// # Panics!
/// If the [RangeBounds] cannot be converted to a computable range!
pub fn sort_reverse<T, V, R: RangeBounds<T>, S: RangeBounds<T>, C: IncDecCpCmp<T, V>>(
    x: &R,
    y: &S,
    rebound: &V,
    t: &C,
) -> Ordering {
    let a: Mrs<T> = (range_bounds_to_values(x, rebound, t)).unwrap().into();
    let b: Mrs<T> = (range_bounds_to_values(y, rebound, t)).unwrap().into();
    if t.lt(a.get_end(), b.get_end()) {
        return Ordering::Greater;
    } else if t.lt(b.get_end(), a.get_end()) {
        return Ordering::Less;
    } else if t.lt(b.get_begin(), a.get_begin()) {
        return Ordering::Greater;
    } else if t.lt(a.get_begin(), b.get_begin()) {
        return Ordering::Less;
    }

    // anything below this point both begin values are the same

    // if we get here, begin and end are equal
    return Ordering::Equal;
}

fn contains<T, R: GetBeginEnd<T>, C: CpCmp<T>>(check: &R, value: &T, t: &C) -> bool {
    return t.contains(check.get_begin(), check.get_end(), value);
}

pub fn reduce_next<T, C: CpCmp<T>, R: GetBeginEnd<T>>(
    begin: &T,
    end: &T,
    src: &[R],
    t: &C,
) -> (T, T) {
    let mut target = end;

    for r in src {
        let (start, finish) = r.to_tuple_ref();
        if !t.overlap(begin, end, start, finish) {
            continue;
        }
        let mut min = finish;
        if t.lt(begin, start) {
            min = start;
        }
        if t.lt(min, target) {
            target = min
        }
    }
    return (t.cp(begin), t.cp(target));
}

pub fn next_smallest_range<T, V, C: IncDecCpCmp<T, V>, R: GetBeginEnd<T>>(
    begin: &T,
    end: &T,
    src: &[R],
    step: &V,
    t: &C,
) -> (T, T) {
    return retool_end(reduce_next(begin, end, src, t), src, step, t);
}

/// Computes the final value from a result of [crate::reduce_next].
pub fn retool_end<T, V, C: IncDecCpCmp<T, V>, R: GetBeginEnd<T>>(
    res: (T, T),
    src: &[R],
    step: &V,
    t: &C,
) -> (T, T) {
    let (begin, end) = res;

    let mut shrank = None;
    let mut driver = &end;
    let mut exact: usize = 0;
    let mut min_end = None;
    for r in src {
        let (c, d) = r.to_tuple_ref();

        if t.overlap(&begin, &end, c, d) {
            if t.lt(&begin, c)
                && let Some(n) = t.dec(&c, step)
                && !t.is_invalid_set(&begin, &n)
            {
                match &shrank {
                    Some(cmp) => {
                        if t.lt(&n, cmp) {
                            shrank = Some(n);
                        }
                    }
                    None => shrank = Some(n),
                }
                continue;
            }
            exact += 1;
            driver = d;
            match min_end {
                Some(n) => {
                    if t.lt(d, n) {
                        min_end = Some(d);
                    }
                }
                None => min_end = Some(d),
            }
        }
    }
    if shrank.is_some() {
        return (begin, shrank.unwrap());
    } else if exact == 1 {
        return (begin, t.cp(driver));
    } else if let Some(n) = min_end {
        return (begin, t.cp(n));
    }
    return (begin, end);
}

/// Computes the final value from a result of [crate::reduce_back].
pub fn retool_begin<T, V, C: IncDecCpCmp<T, V>, R: GetBeginEnd<T>>(
    res: (T, T),
    src: &[R],
    step: &V,
    t: &C,
) -> (T, T) {
    let (begin, end) = res;

    let mut shrank = None;
    let mut driver = &begin;
    let mut exact: usize = 0;
    let mut max_begin = None;
    for r in src {
        let (c, d) = r.to_tuple_ref();

        if t.overlap(&begin, &end, c, d) {
            if t.lt(d, &end)
                && let Some(n) = t.inc(&d, step)
                && !t.is_invalid_set(&n, &end)
            {
                match &shrank {
                    Some(cmp) => {
                        if t.lt(cmp, &n) {
                            shrank = Some(n);
                        }
                    }
                    None => shrank = Some(n),
                }
                continue;
            }
            exact += 1;
            driver = c;
            match max_begin {
                Some(n) => {
                    if t.lt(n, c) {
                        max_begin = Some(c);
                    }
                }
                None => max_begin = Some(c),
            }
        }
    }
    if shrank.is_some() {
        return (shrank.unwrap(), end);
    } else if exact == 1 {
        return (t.cp(driver), end);
    } else if let Some(n) = max_begin {
        return (t.cp(n), end);
    }
    return (begin, end);
}

/// Given the current begin and end, returns the smallest next range from src.
pub fn previous_smallest_range<T, V, C: IncDecCpCmp<T, V>, R: GetBeginEnd<T>>(
    begin: &T,
    end: &T,
    src: &[R],
    step: &V,
    t: &C,
) -> (T, T) {
    return retool_begin(reduce_back(begin, end, src, t), src, step, t);
}

/// Given the current begin and end, returns the smallest back range from src.
pub fn reduce_back<T, C: CpCmp<T>, R: GetBeginEnd<T>>(
    begin: &T,
    end: &T,
    src: &[R],
    t: &C,
) -> (T, T) {
    let mut target = begin;

    for r in src {
        let (start, finish) = r.to_tuple_ref();
        if !t.overlap(begin, end, start, finish) {
            continue;
        }
        let mut min = start;
        if t.lt(finish, end) {
            min = finish;
        }
        if t.lt(target, min) {
            target = min;
        }
    }

    return (t.cp(target), t.cp(end));
}

/// Returns an [Option] wrapped tuple representing the smallest begin and largest end values found in src.
pub fn min_max<'r, T, R: GetBeginEnd<T>, C: CpCmp<T>>(
    src: &'r [R],
    t: &C,
) -> Option<(&'r T, &'r T)> {
    let mut check: Option<(&T, &T)> = None;

    for span in src {
        let (start, finish) = span.to_tuple_ref();
        match check {
            Some((begin, end)) => {
                let mut a = begin;
                let mut z = end;
                if t.lt(end, finish) {
                    z = finish;
                }
                if t.lt(start, begin) {
                    a = start;
                }
                check = Some((a, z))
            }
            _ => check = Some((start, finish)),
        }
    }
    if let Some((begin, end)) = check {
        return Some((begin, end));
    }

    return None;
}

/// Looks for the first most range, if found returns an Option<(T,T)>.
pub fn first_range_begin_end<T, V, C: IncDecCpCmp<T, V>, R: GetBeginEnd<T>>(
    src: &[R],
    step: &V,
    t: &C,
) -> Option<(T, T)> {
    if let Some((begin, end)) = min_max(src, t) {
        return Some(next_smallest_range(begin, end, src, step, t));
    }

    return None;
}

/// Looks for the last most range, if found returns an Option<(T,T)>.
pub fn last_range_begin_end<T, V, C: IncDecCpCmp<T, V>, R: GetBeginEnd<T>>(
    src: &[R],
    step: &V,
    t: &C,
) -> Option<(T, T)> {
    let check = min_max(src, t);
    if let Some((begin, end)) = check {
        return Some(previous_smallest_range(begin, end, src, step, t));
    }

    return None;
}

/// Searches for the next smallest range valid range of (T,T) overlaps with begin.
/// If no range overlaps with end, it finds the next smallest range after begin.
/// Returns None when no matches were found.
pub fn next_range_begin_end<T, V, C: IncDecCpCmp<T, V>, R: GetBeginEnd<T>>(
    begin: &T,
    src: &[R],
    step: &V,
    t: &C,
) -> Option<(T, T)> {
    let mut target: Option<&T> = None;
    let mut alt: Option<(&T, &T)> = None;
    for check in src {
        let (start, finish) = check.to_tuple_ref();
        if contains(check, begin, t) {
            match target {
                Some(cmp) => {
                    if t.lt(finish, cmp) {
                        target = Some(finish)
                    }
                }
                _ => target = Some(finish),
            }
        } else {
            if t.lt(begin, start) {
                match alt {
                    Some((cmp, _)) => {
                        if t.lt(start, cmp) {
                            alt = Some((start, finish))
                        }
                    }
                    _ => alt = Some((start, finish)),
                }
            }
        }
    }
    if let Some(end) = target {
        return Some(next_smallest_range(begin, end, src, step, t));
    } else if let Some((begin, end)) = alt {
        return Some(next_smallest_range(begin, end, src, step, t));
    }
    return None;
}

/// Searches for the previous smallest range valid range of (T,T) overlaps with end.
/// If no range overlaps with end, it finds the previous smallest range before begin.
/// Returns None when no matches were found.
pub fn previous_range_begin_end<T, V, C: IncDecCpCmp<T, V>, R: GetBeginEnd<T>>(
    end: &T,
    src: &[R],
    step: &V,
    t: &C,
) -> Option<(T, T)> {
    let mut target: Option<&T> = None;
    let mut alt: Option<(&T, &T)> = None;
    let mut valid = Vec::new();
    for check in src {
        valid.push(check);
        let (start, finish) = check.to_tuple_ref();
        if contains(check, end, t) {
            match target {
                Some(cmp) => {
                    if t.lt(start, cmp) {
                        target = Some(start)
                    }
                }
                _ => target = Some(start),
            }
        } else {
            if t.lt(finish, end) {
                match alt {
                    Some((x, y)) => {
                        let mut a = x;
                        let mut b = y;
                        if t.lt(y, finish) {
                            b = finish
                        }
                        if t.lt(start, a) {
                            a = start
                        }
                        alt = Some((a, b));
                    }
                    _ => alt = Some((start, finish)),
                }
            }
        }
    }
    if let Some(begin) = target {
        return Some(previous_smallest_range(begin, end, src, step, t));
    } else if let Some((begin, end)) = alt {
        return Some(previous_smallest_range(begin, end, src, step, t));
    }
    return None;
}

/// Given 2 instances of [GetBeginEnd] it returns a range that contains both.
pub fn grow<
    T,
    Q: GetBeginEnd<T>,
    R: GetBeginEnd<T>,
    S: GetBeginEnd<T>,
    C: CpCmp<T>,
    F: GetBeginEndOption<T, Q>,
>(
    x: &R,
    y: &S,
    t: &C,
    f: &F,
) -> Q {
    let a;
    if t.lt(x.get_begin(), y.get_begin()) {
        a = t.cp(x.get_begin())
    } else {
        a = t.cp(y.get_begin())
    }
    let z;
    if t.lt(x.get_end(), y.get_end()) {
        z = t.cp(y.get_end());
    } else {
        z = t.cp(x.get_end());
    }
    return f.new_range((a, z));
}

/// This function is the stateless implementation of [crate::Consolidate].
pub fn consolidate<
    T,
    V,
    R: GetBeginEnd<T>,
    S: RangeBounds<T>,
    C: IncDecCpCmp<T, V>,
    F: GetBeginEndOption<T, R>,
    I: Iterator<Item = S>,
>(
    last: &mut Option<(R, Vec<(usize, S)>)>,
    iter: &mut I,
    t: &C,
    rebound: &V,
    f: &F,
    mut offset: usize,
) -> (usize, Option<RangeRelation<(R, Vec<(usize, S)>)>>) {
    // this value will become our next offset when we are called again!
    for range in iter {
        let r = range_bounds_to_values(&range, rebound, t);
        let mut ar;
        match r {
            Some(src) => ar = (f.new_range(src), vec![(offset, range)]),
            None => {
                let a;
                match range.start_bound() {
                    Included(s) => a = t.cp(s),
                    Excluded(s) => a = t.cp(s),
                    Unbounded => a = t.min(),
                }
                let b;
                match range.start_bound() {
                    Included(s) => b = t.cp(s),
                    Excluded(s) => b = t.cp(s),
                    Unbounded => b = t.max(),
                }
                match mem::replace(last, None) {
                    Some((good, mut list)) => {
                        let bad = f.new_range((a, b));
                        let r = grow(&good, &bad, t, f);
                        list.push((offset, range));
                        ar = (r, list);
                    }
                    None => ar = (f.new_range((a, b)), vec![(offset, range)]),
                }
                offset += 1;
                return (offset, Some(RangeRelation::Invalid(ar)));
            }
        }

        offset += 1;

        let nv = mem::replace(last, None);
        if let Some((src, mut list)) = nv {
            match range_relation(&src, &ar.0, t) {
                RangeRelation::Overlap(_) => {
                    let nr = grow(&src, &ar.0, t, f);
                    list.append(&mut ar.1);
                    if t.is_invalid_set(nr.get_begin(), nr.get_end()) {
                        *last = None;
                        return (offset, Some(RangeRelation::Invalid((nr, list))));
                    } else {
                        *last = Some((nr, list));
                    }
                }
                RangeRelation::Before(_) => {
                    *last = Some(ar);
                    return (offset, Some(RangeRelation::Before((src, list))));
                }
                RangeRelation::After(_) => {
                    *last = Some(ar);
                    return (offset, Some(RangeRelation::After((src, list))));
                }
                RangeRelation::Invalid(_) => {
                    *last = Some(ar);
                    return (offset, Some(RangeRelation::Invalid((src, list))));
                }
                _ => {}
            }
        } else {
            *last = Some(ar);
        }
    }
    if last.is_some() {
        let res = mem::replace(last, None);
        return (offset, Some(RangeRelation::Last(res.unwrap())));
    }
    return (offset, None);
}