Skip to main content

gamut_core/
segment.rs

1//! Byte-tiling: the format-agnostic shape of a "every input byte maps to exactly one typed
2//! segment" report, and the predicate that checks it.
3//!
4//! A format crate's byte-accounting walk (`gamut_isobmff::walk_segments`, which `gamut-heic` and
5//! `gamut-avif` share; a deconstruct report) decomposes its input into [`Segment`]s tagged with
6//! the format's own `kind` enum. What makes such a list *total* is the same in every format: the
7//! segments are non-empty, contiguous, non-overlapping, start at `0` and end at the input length.
8//! [`covers`] states that once, so the formats keep their kinds and walks and share only the
9//! law. [`tiles`] is the same predicate over bare ranges, for a report whose segments carry
10//! their extents in another form (e.g. `u64` offsets for files past `usize`).
11//!
12//! The walks themselves stay in the format crates: each stops on its own format's rules, and
13//! those rules are what a format crate's tests pin.
14
15use core::ops::Range;
16
17/// One contiguous run of an input, tagged by what it holds.
18///
19/// `K` is the format's own classification (e.g. `gamut_isobmff::SegmentKind`); this type adds
20/// nothing to it but the half-open byte range it occupies. A list of these is total over an
21/// input of `len` bytes exactly when [`covers`] says so.
22#[derive(Debug, Clone, PartialEq, Eq, Hash)]
23pub struct Segment<K> {
24    /// The half-open byte range this segment occupies within the input (`start..end`).
25    pub range: Range<usize>,
26    /// What the bytes in [`range`](Self::range) are.
27    pub kind: K,
28}
29
30/// Whether `segments` tile `0..len` exactly: every segment is non-empty, the first starts at
31/// `0`, each one starts where the previous one ended (no gap, no overlap), and the last ends at
32/// `len`.
33///
34/// An empty list tiles only an empty input (`len == 0`). This is the every-byte invariant of a
35/// byte-accounting report; see [`tiles`] for the same predicate over bare ranges.
36#[must_use]
37pub fn covers<K>(segments: &[Segment<K>], len: usize) -> bool {
38    tiles(segments.iter().map(|s| s.range.clone()), len)
39}
40
41/// Whether `ranges`, in order, tile `0..len` exactly — the predicate behind [`covers`], over
42/// bare half-open ranges of any unsigned offset type (`usize` for an in-memory input, `u64` for
43/// a file addressed past `usize`).
44///
45/// Every range must be non-empty (`start < end`) and start where the previous one ended, the
46/// first at `0`; the last must end at `len`. An empty sequence tiles only `len == 0`. The ranges
47/// are consumed in the order given and are not sorted: an out-of-order list is not a tiling.
48#[must_use]
49pub fn tiles<T>(ranges: impl IntoIterator<Item = Range<T>>, len: T) -> bool
50where
51    T: Copy + PartialOrd + From<u8>,
52{
53    let mut at = T::from(0);
54    for range in ranges {
55        if range.start != at || range.is_empty() {
56            return false;
57        }
58        at = range.end;
59    }
60    at == len
61}
62
63#[cfg(test)]
64mod tests {
65    use super::*;
66
67    /// Builds segments with unit kinds from `(start, end)` pairs — the kind plays no part in
68    /// tiling. Pairs rather than range literals so a reversed range can be written at all.
69    fn segs(bounds: &[(usize, usize)]) -> Vec<Segment<()>> {
70        bounds
71            .iter()
72            .map(|&(start, end)| Segment {
73                range: start..end,
74                kind: (),
75            })
76            .collect()
77    }
78
79    #[test]
80    fn contiguous_segments_ending_at_len_cover() {
81        assert!(covers(&segs(&[(0, 3), (3, 4), (4, 10)]), 10));
82        assert!(covers(&segs(&[(0, 1)]), 1));
83    }
84
85    #[test]
86    fn an_empty_list_covers_only_an_empty_input() {
87        assert!(covers::<()>(&[], 0));
88        assert!(!covers::<()>(&[], 1));
89    }
90
91    #[test]
92    fn a_first_segment_not_at_zero_does_not_cover() {
93        assert!(!covers(&segs(&[(1, 10)]), 10));
94    }
95
96    #[test]
97    fn a_gap_does_not_cover() {
98        assert!(!covers(&segs(&[(0, 3), (4, 10)]), 10));
99    }
100
101    #[test]
102    fn an_overlap_does_not_cover() {
103        assert!(!covers(&segs(&[(0, 4), (3, 10)]), 10));
104    }
105
106    #[test]
107    fn an_empty_segment_does_not_cover() {
108        // Chained correctly, but a zero-length segment classifies no byte.
109        assert!(!covers(&segs(&[(0, 3), (3, 3), (3, 10)]), 10));
110        assert!(!covers(&segs(&[(0, 0)]), 0));
111    }
112
113    #[test]
114    fn a_reversed_segment_does_not_cover() {
115        // `start > end` chains back to the start of a following segment but claims no byte.
116        assert!(!covers(&segs(&[(0, 5), (5, 2), (2, 10)]), 10));
117    }
118
119    #[test]
120    fn a_short_tail_does_not_cover() {
121        assert!(!covers(&segs(&[(0, 3), (3, 9)]), 10));
122    }
123
124    #[test]
125    fn a_long_tail_does_not_cover() {
126        assert!(!covers(&segs(&[(0, 3), (3, 11)]), 10));
127    }
128
129    #[test]
130    fn out_of_order_segments_do_not_cover() {
131        assert!(!covers(&segs(&[(3, 10), (0, 3)]), 10));
132    }
133
134    #[test]
135    fn tiles_accepts_u64_offsets() {
136        let big = u64::from(u32::MAX) + 7;
137        assert!(tiles([0..8u64, 8..big], big));
138        assert!(!tiles([0..8u64, 9..big], big));
139    }
140}