int-interval 0.8.1

A small, no_std half-open interval algebra library for primitive integer types.
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
use crate::res::{OneTwo, ZeroOneTwo};

#[cfg(test)]
mod tests_for_basic;
#[cfg(test)]
mod tests_for_between;
#[cfg(test)]
mod tests_for_checked_minkowski;
#[cfg(test)]
mod tests_for_convex_hull;
#[cfg(test)]
mod tests_for_difference;
#[cfg(test)]
mod tests_for_intersection;
#[cfg(test)]
mod tests_for_symmetric_difference;
#[cfg(test)]
mod tests_for_union;

#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)]
pub struct I8CO {
    start: i8,
    end_excl: i8,
}

// ------------------------------------------------------------
// low-level api: construction / accessors / predicates
// ------------------------------------------------------------
mod basic {

    use super::*;

    impl I8CO {
        #[inline]
        pub const fn try_new(start: i8, end_excl: i8) -> Option<Self> {
            if start < end_excl {
                Some(Self { start, end_excl })
            } else {
                None
            }
        }

        #[inline]
        pub const unsafe fn new_unchecked(start: i8, end_excl: i8) -> Self {
            debug_assert!(start < end_excl);
            Self { start, end_excl }
        }

        /// Constructs an `I8CO` interval from a midpoint and length (`u8`).
        ///
        /// # Parameters
        /// - `mid`: the desired midpoint of the interval
        /// - `len`: the desired length of the interval in units, must be `1..=u8::MAX`
        ///
        /// # Returns
        /// - `Some(I8CO)` if the interval `[start, end_excl)` can be represented in `i8`
        /// - `None` if `len = 0` or the computed `start` / `end_excl` would overflow `i8`
        ///
        /// # Guarantees
        /// - Returned interval satisfies `start < end_excl`
        /// - Maximum accepted input length is `u8::MAX`
        #[inline]
        pub const fn checked_from_midpoint_len(mid: i8, len: u8) -> Option<Self> {
            if len == 0 {
                return None;
            }

            let half = (len / 2) as i8;

            let Some(start) = mid.checked_sub(half) else {
                return None;
            };
            let Some(end_incl) = mid.checked_add(half) else {
                return None;
            };
            let Some(end_excl) = end_incl.checked_add((len % 2) as i8) else {
                return None;
            };

            // # Safety
            // This function uses `unsafe { Self::new_unchecked(start, end_excl) }` internally.
            // The safety is guaranteed by the following checks:
            // 1. `mid.checked_sub(half)` ensures `start` does not underflow `i8`.
            // 2. `mid.checked_add(the_other_half)` ensures `end_excl` does not overflow `i8`.
            // 3. Because `half >= 0` and `the_other_half > 0`, we have `start < end_excl`.
            // 4. Therefore, the half-open interval invariant `[start, end_excl)` is preserved.
            Some(unsafe { Self::new_unchecked(start, end_excl) })
        }

        /// Constructs an `I8CO` interval from a midpoint and length (`u8`) with saturating semantics.
        ///
        /// # Parameters
        /// - `mid`: the desired midpoint of the interval
        /// - `len`: the desired length of the interval in units, must be `1..=u8::MAX`
        ///
        /// # Behavior
        /// - Values are saturated at `i8::MIN` / `i8::MAX` to prevent overflow.
        /// - If `len = 0`, returns `None`.
        ///
        /// # Guarantees
        /// - Returned interval satisfies `start < end_excl`
        /// - Maximum accepted input length is `u8::MAX`
        /// - Fully compatible with codegen for other signed integer interval types
        #[inline]
        pub const fn saturating_from_midpoint_len(mid: i8, len: u8) -> Option<Self> {
            if len == 0 {
                return None;
            }

            let half = (len / 2) as i8;

            let start = mid.saturating_sub(half);
            let end_incl = mid.saturating_add(half);
            let end_excl = end_incl.saturating_add((len % 2) as i8);

            Self::try_new(start, end_excl)
        }
    }

    impl I8CO {
        #[inline]
        pub const fn start(self) -> i8 {
            self.start
        }

        #[inline]
        pub const fn end_excl(self) -> i8 {
            self.end_excl
        }

        #[inline]
        pub const fn end_incl(self) -> i8 {
            // i8_low_bound =< start < end_excl
            self.end_excl - 1
        }

        #[inline]
        pub const fn len(self) -> u8 {
            const SIGN_MASK: u8 = 1 << (i8::BITS - 1);
            ((self.end_excl as u8) ^ SIGN_MASK) - ((self.start as u8) ^ SIGN_MASK)
        }

        /// Returns the midpoint of the interval `[start, end_excl)`,
        /// using floor division if the length is even.
        ///
        /// # Guarantees
        /// - `midpoint()` ∈ `[self.start, self.end_excl - 1]`
        /// - Works for intervals with maximum length (entire `i8` range)
        #[inline]
        pub const fn midpoint(self) -> i8 {
            self.start + (self.len() / 2) as i8
        }

        #[inline]
        pub const fn contains(self, x: i8) -> bool {
            self.start <= x && x < self.end_excl
        }

        #[inline]
        pub const fn contains_interval(self, other: Self) -> bool {
            self.start <= other.start && other.end_excl <= self.end_excl
        }

        #[inline]
        pub const fn iter(self) -> core::ops::Range<i8> {
            self.start..self.end_excl
        }

        #[inline]
        pub const fn to_range(self) -> core::ops::Range<i8> {
            self.start..self.end_excl
        }

        #[inline]
        pub const fn intersects(self, other: Self) -> bool {
            !(self.end_excl <= other.start || other.end_excl <= self.start)
        }

        #[inline]
        pub const fn is_adjacent(self, other: Self) -> bool {
            self.end_excl == other.start || other.end_excl == self.start
        }

        #[inline]
        pub const fn is_contiguous_with(self, other: Self) -> bool {
            self.intersects(other) || self.is_adjacent(other)
        }
    }
}

// ------------------------------------------------------------
// interval algebra api: intersection / convex_hull / between / union / difference / symmetric_difference
// ------------------------------------------------------------

mod interval_algebra {

    use super::*;

    impl I8CO {
        /// Returns the intersection of two intervals.
        ///
        /// If the intervals do not overlap, returns `None`.
        #[inline]
        pub const fn intersection(self, other: Self) -> Option<Self> {
            let start = if self.start >= other.start {
                self.start
            } else {
                other.start
            };

            let end_excl = if self.end_excl <= other.end_excl {
                self.end_excl
            } else {
                other.end_excl
            };

            Self::try_new(start, end_excl)
        }

        /// Returns the convex hull (smallest interval containing both) of two intervals.
        ///
        /// Always returns a valid `I8CO`.
        #[inline]
        pub const fn convex_hull(self, other: Self) -> Self {
            let start = if self.start <= other.start {
                self.start
            } else {
                other.start
            };

            let end_excl = if self.end_excl >= other.end_excl {
                self.end_excl
            } else {
                other.end_excl
            };

            Self { start, end_excl }
        }

        /// Returns the interval strictly between two intervals.
        ///
        /// If the intervals are contiguous or overlap, returns `None`.
        #[inline]
        pub const fn between(self, other: Self) -> Option<Self> {
            let (left, right) = if self.start <= other.start {
                (self, other)
            } else {
                (other, self)
            };

            Self::try_new(left.end_excl, right.start)
        }

        /// Returns the union of two intervals.
        ///
        /// - If intervals are contiguous or overlapping, returns `One` containing the merged interval.
        /// - Otherwise, returns `Two` containing both intervals in ascending order.
        #[inline]
        pub const fn union(self, other: Self) -> OneTwo<Self> {
            if self.is_contiguous_with(other) {
                OneTwo::One(self.convex_hull(other))
            } else if self.start <= other.start {
                OneTwo::Two(self, other)
            } else {
                OneTwo::Two(other, self)
            }
        }

        /// Returns the difference of two intervals (self - other).
        ///
        /// - If no overlap, returns `One(self)`.
        /// - If partial overlap, returns `One` or `Two` depending on remaining segments.
        /// - If fully contained, returns `Zero`.
        #[inline]
        pub const fn difference(self, other: Self) -> ZeroOneTwo<Self> {
            match self.intersection(other) {
                None => ZeroOneTwo::One(self),
                Some(inter) => {
                    let left = Self::try_new(self.start, inter.start);
                    let right = Self::try_new(inter.end_excl, self.end_excl);

                    match (left, right) {
                        (None, None) => ZeroOneTwo::Zero,
                        (Some(x), None) | (None, Some(x)) => ZeroOneTwo::One(x),
                        (Some(x), Some(y)) => ZeroOneTwo::Two(x, y),
                    }
                }
            }
        }

        /// Returns the symmetric difference of two intervals.
        ///
        /// Equivalent to `(self - other) ∪ (other - self)`.
        /// - If intervals do not overlap, returns `Two(self, other)` in order.
        /// - If intervals partially overlap, returns remaining non-overlapping segments as `One` or `Two`.
        #[inline]
        pub const fn symmetric_difference(self, other: Self) -> ZeroOneTwo<Self> {
            match self.intersection(other) {
                None => {
                    if self.start <= other.start {
                        ZeroOneTwo::Two(self, other)
                    } else {
                        ZeroOneTwo::Two(other, self)
                    }
                }
                Some(inter) => {
                    let hull = self.convex_hull(other);
                    let left = Self::try_new(hull.start, inter.start);
                    let right = Self::try_new(inter.end_excl, hull.end_excl);

                    match (left, right) {
                        (None, None) => ZeroOneTwo::Zero,
                        (Some(x), None) | (None, Some(x)) => ZeroOneTwo::One(x),
                        (Some(x), Some(y)) => ZeroOneTwo::Two(x, y),
                    }
                }
            }
        }
    }
}

// ------------------------------------------------------------
// Module: Minkowski arithmetic for I8CO
// Provides checked and saturating Minkowski operations for intervals
// ------------------------------------------------------------

pub mod minkowski {
    use super::*;

    type Min = i8;
    type Max = i8;

    #[inline]
    const fn min_max4(a: i8, b: i8, c: i8, d: i8) -> (Min, Max) {
        let (min1, max1) = if a < b { (a, b) } else { (b, a) };
        let (min2, max2) = if c < d { (c, d) } else { (d, c) };
        let min = if min1 < min2 { min1 } else { min2 };
        let max = if max1 > max2 { max1 } else { max2 };
        (min, max)
    }

    #[inline]
    const fn min_max2(a: i8, b: i8) -> (Min, Max) {
        if a < b { (a, b) } else { (b, a) }
    }

    pub mod checked {
        use super::*;

        // --------------------------------------------------------
        // Interval-to-interval
        // --------------------------------------------------------
        impl I8CO {
            #[inline]
            pub const fn checked_minkowski_add(self, other: Self) -> Option<Self> {
                let Some(start) = self.start.checked_add(other.start) else {
                    return None;
                };
                let Some(end_excl) = self.end_excl.checked_add(other.end_incl()) else {
                    return None;
                };

                // SAFETY:
                // `checked_add` guarantees both endpoint computations succeed without overflow.
                // For half-open intervals, let `a_last = self.end_incl()` and `b_last = other.end_incl()`.
                // Since `self.start <= a_last` and `other.start <= b_last`, we have
                // `self.start + other.start <= a_last + b_last < self.end_excl + other.end_incl()`,
                // hence the computed bounds satisfy `start < end_excl`.
                Some(unsafe { Self::new_unchecked(start, end_excl) })
            }

            #[inline]
            pub const fn checked_minkowski_sub(self, other: Self) -> Option<Self> {
                let Some(start) = self.start.checked_sub(other.end_incl()) else {
                    return None;
                };
                let Some(end_excl) = self.end_excl.checked_sub(other.start) else {
                    return None;
                };

                // SAFETY:
                // `checked_sub` guarantees both endpoint computations succeed without overflow.
                // For interval subtraction, the minimum is attained at `self.start - other.end_incl()`
                // and the exclusive upper bound is `self.end_excl - other.start`.
                // Because `other.start <= other.end_incl()`, we get
                // `self.start - other.end_incl() < self.end_excl - other.start`,
                // so the resulting half-open interval is valid.
                Some(unsafe { Self::new_unchecked(start, end_excl) })
            }

            #[inline]
            pub const fn checked_minkowski_mul_hull(self, other: Self) -> Option<Self> {
                let a = self.start;
                let b = self.end_incl();
                let c = other.start;
                let d = other.end_incl();

                let Some(p1) = a.checked_mul(c) else {
                    return None;
                };
                let Some(p2) = a.checked_mul(d) else {
                    return None;
                };
                let Some(p3) = b.checked_mul(c) else {
                    return None;
                };
                let Some(p4) = b.checked_mul(d) else {
                    return None;
                };

                let (start, end_incl) = min_max4(p1, p2, p3, p4);

                let Some(end_excl) = end_incl.checked_add(1) else {
                    return None;
                };

                // SAFETY:
                // All four corner products are computed with `checked_mul`, so no intermediate
                // multiplication overflows. For multiplication over a closed integer rectangle
                // `[a, b] × [c, d]`, every attainable extremum occurs at a corner, so
                // `min_max4(p1, p2, p3, p4)` yields the true inclusive lower/upper bounds.
                // Therefore `start <= end_incl` holds by construction.
                // `checked_add(1)` then safely converts the inclusive upper bound to the exclusive
                // upper bound, and implies `end_excl = end_incl + 1`, hence `start < end_excl`.
                Some(unsafe { Self::new_unchecked(start, end_excl) })
            }

            #[inline]
            pub const fn checked_minkowski_div_hull(self, other: Self) -> Option<Self> {
                if other.start <= 0 && other.end_incl() >= 0 {
                    return None;
                }

                let a = self.start;
                let b = self.end_incl();
                let c = other.start;
                let d = other.end_incl();

                let Some(p1) = a.checked_div(c) else {
                    return None;
                };
                let Some(p2) = a.checked_div(d) else {
                    return None;
                };
                let Some(p3) = b.checked_div(c) else {
                    return None;
                };
                let Some(p4) = b.checked_div(d) else {
                    return None;
                };

                let (start, end_incl) = min_max4(p1, p2, p3, p4);

                let Some(end_excl) = end_incl.checked_add(1) else {
                    return None;
                };

                // SAFETY:
                // The guard `other.start <= 0 && other.end_incl() >= 0` rejects any divisor interval
                // that contains zero, so division by zero cannot occur anywhere in the divisor set.
                // Each corner quotient is computed with `checked_div`, so exceptional signed cases
                // such as `MIN / -1` are also rejected.
                // On each connected component of the divisor domain that excludes zero, integer division
                // is monotone with respect to the rectangle corners relevant to the extremum search;
                // thus the global inclusive bounds over the interval pair are captured by the four
                // corner quotients and recovered by `min_max4`, giving `start <= end_incl`.
                // `checked_add(1)` safely converts the inclusive upper bound to half-open form, so
                // the final bounds satisfy `start < end_excl`.
                Some(unsafe { Self::new_unchecked(start, end_excl) })
            }
        }

        // --------------------------------------------------------
        // Scalar
        // --------------------------------------------------------
        impl I8CO {
            #[inline]
            pub const fn checked_minkowski_add_scalar(self, n: i8) -> Option<Self> {
                let Some(start) = self.start.checked_add(n) else {
                    return None;
                };
                let Some(end_excl) = self.end_excl.checked_add(n) else {
                    return None;
                };

                // SAFETY:
                // `checked_add` guarantees both translated bounds are computed without overflow.
                // Adding the same scalar to both endpoints preserves the interval width exactly,
                // so a valid half-open interval remains valid and still satisfies `start < end_excl`.
                Some(unsafe { Self::new_unchecked(start, end_excl) })
            }

            #[inline]
            pub const fn checked_minkowski_sub_scalar(self, n: i8) -> Option<Self> {
                let Some(start) = self.start.checked_sub(n) else {
                    return None;
                };
                let Some(end_excl) = self.end_excl.checked_sub(n) else {
                    return None;
                };

                // SAFETY:
                // `checked_sub` guarantees both translated bounds are computed without overflow.
                // Subtracting the same scalar from both endpoints preserves the interval width exactly,
                // so the strict half-open ordering is unchanged and `start < end_excl` still holds.
                Some(unsafe { Self::new_unchecked(start, end_excl) })
            }

            #[inline]
            pub const fn checked_minkowski_mul_scalar_hull(self, n: i8) -> Option<Self> {
                let Some(a) = self.start.checked_mul(n) else {
                    return None;
                };
                let Some(b) = self.end_incl().checked_mul(n) else {
                    return None;
                };

                let (start, end_incl) = min_max2(a, b);

                let Some(end_excl) = end_incl.checked_add(1) else {
                    return None;
                };

                // SAFETY:
                // Both endpoint products are computed with `checked_mul`, so no signed overflow occurs.
                // Multiplication by a scalar maps the closed source interval endpoints to the two extreme
                // candidates; `min_max2` therefore recovers the true inclusive lower/upper bounds whether
                // `n` is positive, zero, or negative, giving `start <= end_incl`.
                // `checked_add(1)` safely converts the inclusive upper bound into the exclusive upper bound,
                // which guarantees the final half-open interval satisfies `start < end_excl`.
                Some(unsafe { Self::new_unchecked(start, end_excl) })
            }

            #[inline]
            pub const fn checked_minkowski_div_scalar_hull(self, n: i8) -> Option<Self> {
                if n == 0 {
                    return None;
                }

                let Some(a) = self.start.checked_div(n) else {
                    return None;
                };
                let Some(b) = self.end_incl().checked_div(n) else {
                    return None;
                };

                let (start, end_incl) = min_max2(a, b);

                let Some(end_excl) = end_incl.checked_add(1) else {
                    return None;
                };

                // SAFETY:
                // The guard `n != 0` excludes division by zero, and `checked_div` additionally rejects
                // the only overflowing signed case (`MIN / -1`).
                // Division by a fixed nonzero scalar sends the source closed interval endpoints to the
                // two extreme candidates for the image interval, so `min_max2` yields the true inclusive
                // lower/upper bounds and ensures `start <= end_incl`.
                // `checked_add(1)` safely restores half-open representation, therefore the constructed
                // interval satisfies `start < end_excl`.
                Some(unsafe { Self::new_unchecked(start, end_excl) })
            }
        }
    }

    // ========================================================
    // SATURATING
    // ========================================================
    pub mod saturating {
        use super::*;

        impl I8CO {
            #[inline]
            pub const fn saturating_minkowski_add(self, other: Self) -> Option<Self> {
                let start = self.start.saturating_add(other.start);
                let end_excl = self.end_excl.saturating_add(other.end_incl());
                Self::try_new(start, end_excl)
            }

            #[inline]
            pub const fn saturating_minkowski_sub(self, other: Self) -> Option<Self> {
                let start = self.start.saturating_sub(other.end_incl());
                let end_excl = self.end_excl.saturating_sub(other.start);
                Self::try_new(start, end_excl)
            }

            #[inline]
            pub const fn saturating_minkowski_mul_hull(self, other: Self) -> Option<Self> {
                let a = self.start.saturating_mul(other.start);
                let b = self.start.saturating_mul(other.end_incl());
                let c = self.end_incl().saturating_mul(other.start);
                let d = self.end_incl().saturating_mul(other.end_incl());

                let (start, end_incl) = min_max4(a, b, c, d);

                let end_excl = end_incl.saturating_add(1);
                Self::try_new(start, end_excl)
            }

            #[inline]
            pub const fn saturating_minkowski_div_hull(self, other: Self) -> Option<Self> {
                if other.start <= 0 && other.end_incl() >= 0 {
                    return None;
                }

                let a = self.start / other.start;
                let b = self.start / other.end_incl();
                let c = self.end_incl() / other.start;
                let d = self.end_incl() / other.end_incl();

                let (start, end_incl) = min_max4(a, b, c, d);

                let end_excl = end_incl.saturating_add(1);
                Self::try_new(start, end_excl)
            }
        }

        impl I8CO {
            #[inline]
            pub const fn saturating_minkowski_add_scalar(self, n: i8) -> Option<Self> {
                let start = self.start.saturating_add(n);
                let end_excl = self.end_excl.saturating_add(n);
                Self::try_new(start, end_excl)
            }

            #[inline]
            pub const fn saturating_minkowski_sub_scalar(self, n: i8) -> Option<Self> {
                let start = self.start.saturating_sub(n);
                let end_excl = self.end_excl.saturating_sub(n);
                Self::try_new(start, end_excl)
            }

            #[inline]
            pub const fn saturating_minkowski_mul_scalar_hull(self, n: i8) -> Option<Self> {
                let a = self.start.saturating_mul(n);
                let b = self.end_incl().saturating_mul(n);

                let (start, end_incl) = min_max2(a, b);

                let end_excl = end_incl.saturating_add(1);
                Self::try_new(start, end_excl)
            }

            #[inline]
            pub const fn saturating_minkowski_div_scalar_hull(self, n: i8) -> Option<Self> {
                if n == 0 {
                    return None;
                }

                let a = self.start / n;
                let b = self.end_incl() / n;

                let (start, end_incl) = min_max2(a, b);

                let end_excl = end_incl.saturating_add(1);
                Self::try_new(start, end_excl)
            }
        }
    }
}

crate::traits::impl_co_forwarding!(I8CO, i8, u8);