Skip to main content

i8051_disassembler/render/
data.rs

1use crate::address::AddressValue;
2
3pub struct DataHeuristics {
4    /// Bytes per `.db` row. Also the unit for row-repeat.
5    pub block_size: usize,
6
7    /// Collapse N+ identical block_size rows into one `.rept` (hexdump `*`).
8    /// None disables multi-byte row folding.
9    pub min_repeat_rows: Option<usize>,
10
11    /// RLE rules applied to runs in the body of the span.
12    pub interior: Vec<RunRule>,
13
14    /// Trim at the start of a mapped chunk (None = leave leading bytes literal).
15    pub leading: Option<EdgeTrim>,
16
17    /// Trim at the end of a mapped chunk (None = leave trailing bytes literal).
18    pub trailing: Option<EdgeTrim>,
19
20    /// When the entire span is zeros and length is at least this value, emit one
21    /// skip run for the whole span. `usize::MAX` disables the fast path.
22    pub all_zero_single_ds_min: usize,
23
24    /// When set, run compression only applies to the address-aligned middle of a
25    /// homogeneous run spanning at least this many `block_size` blocks.
26    pub min_aligned_blocks: Option<usize>,
27
28    /// Emit zero skip runs as multiple `.ds block_size` lines instead of one
29    /// `.ds N` for the full run length.
30    pub zero_skip_windowed: bool,
31}
32
33#[derive(Clone)]
34pub struct RunRule {
35    /// `Some(v)` matches a run of value `v`; `None` is the catch-all
36    /// (any repeated byte), evaluated only after all `Some` rules.
37    pub value: Option<u8>,
38    /// Minimum run length before this rule fires; shorter runs stay inline.
39    /// `None` means always literal.
40    pub min_run: Option<usize>,
41}
42
43#[derive(Clone)]
44pub struct EdgeTrim {
45    /// Run rules for this edge — may use different values / lower thresholds
46    /// than `interior` (edge padding is unambiguous, so trim sooner).
47    pub rules: Vec<RunRule>,
48    /// Literal bytes kept flush against the boundary, outside the fill run.
49    /// This is the DOS-ROM tail: e.g. 4 for a u32 checksum, 2 for a u16 sig.
50    pub reserve: usize,
51}
52
53pub enum Edge {
54    Leading,
55    Trailing,
56}
57
58impl Default for DataHeuristics {
59    fn default() -> Self {
60        Self {
61            block_size: 16,
62            min_repeat_rows: None,
63            interior: vec![
64                RunRule {
65                    value: Some(0x00),
66                    min_run: Some(8),
67                },
68                RunRule {
69                    value: Some(0xFF),
70                    min_run: Some(64),
71                },
72            ],
73            leading: None,
74            trailing: Some(EdgeTrim {
75                rules: vec![
76                    RunRule {
77                        value: Some(0xFF),
78                        min_run: Some(16),
79                    },
80                    RunRule {
81                        value: Some(0x00),
82                        min_run: Some(4),
83                    },
84                ],
85                reserve: 4,
86            }),
87            all_zero_single_ds_min: 8,
88            min_aligned_blocks: None,
89            zero_skip_windowed: false,
90        }
91    }
92}
93
94#[derive(Debug, Clone, Copy, PartialEq, Eq)]
95enum RuleDecision {
96    Compress,
97    ForceLiteral,
98    NoMatch,
99}
100
101impl DataHeuristics {
102    pub fn iterate<'a>(
103        &self,
104        address: AddressValue,
105        edge: Option<Edge>,
106        bytes: &'a [u8],
107    ) -> impl Iterator<Item = DataChunk<'a, u8>> {
108        self.segment(address, edge, bytes).into_iter()
109    }
110
111    /// Split a literal span into `.db` rows of `block_size`.
112    pub fn literal_rows<'a>(&self, bytes: &'a [u8]) -> Vec<&'a [u8]> {
113        bytes.chunks(self.block_size.max(1)).collect()
114    }
115
116    fn segment<'a>(
117        &self,
118        _address: AddressValue,
119        _edge: Option<Edge>,
120        bytes: &'a [u8],
121    ) -> Vec<DataChunk<'a, u8>> {
122        let mut out = Vec::new();
123        let len = bytes.len();
124        if len == 0 {
125            return out;
126        }
127
128        // reserve carves literal head/tail; runs are only detected in the window
129        let head = self.leading.as_ref().map_or(0, |e| e.reserve).min(len);
130        let tail = self
131            .trailing
132            .as_ref()
133            .map_or(0, |e| e.reserve)
134            .min(len - head);
135        let win_start = head;
136        let win_end = len - tail;
137
138        let mut lit_start = 0usize; // pending literal span start (absolute, incl. reserved head)
139        let mut i = win_start;
140
141        while i < win_end {
142            let value = bytes[i];
143            let mut j = i + 1;
144            while j < win_end && bytes[j] == value {
145                j += 1;
146            }
147            let run_len = j - i;
148            let at_start = i == win_start;
149            let at_end = j == win_end;
150
151            if self.should_compress(value, run_len, at_start, at_end) {
152                push_literal(&mut out, bytes, lit_start, i);
153                out.push(DataChunk::Run(value, run_len));
154                i = j;
155                lit_start = j;
156                continue;
157            }
158
159            if let Some(count) = self.block_run_at(bytes, i, win_end) {
160                let unit_len = self.block_size;
161                push_literal(&mut out, bytes, lit_start, i);
162                out.push(DataChunk::BlockRun(&bytes[i..i + unit_len], count));
163                i += unit_len * count;
164                lit_start = i;
165                continue;
166            }
167
168            // equal-run wasn't compressible: leave it in the pending literal span
169            i = j;
170        }
171
172        // flush trailing in-window literal + reserved tail as one span
173        push_literal(&mut out, bytes, lit_start, len);
174        out
175    }
176
177    fn should_compress(&self, value: u8, run_len: usize, at_start: bool, at_end: bool) -> bool {
178        let decide = |rules: &[RunRule]| rule_decision(rules, value, run_len);
179
180        // edge rule sets (relaxed thresholds) take precedence over interior;
181        // a matching `Literal` rule short-circuits to "don't compress"
182        if at_start && let Some(edge) = &self.leading {
183            match decide(&edge.rules) {
184                RuleDecision::Compress => return true,
185                RuleDecision::ForceLiteral => return false,
186                RuleDecision::NoMatch => {}
187            }
188        }
189        if at_end && let Some(edge) = &self.trailing {
190            match decide(&edge.rules) {
191                RuleDecision::Compress => return true,
192                RuleDecision::ForceLiteral => return false,
193                RuleDecision::NoMatch => {}
194            }
195        }
196        matches!(decide(&self.interior), RuleDecision::Compress)
197    }
198
199    fn block_run_at(&self, bytes: &[u8], i: usize, end: usize) -> Option<usize> {
200        let min_rows = self.min_repeat_rows?;
201        let bs = self.block_size;
202        if bs == 0 || min_rows == 0 || i + bs.checked_mul(min_rows)? > end {
203            return None;
204        }
205        let unit = &bytes[i..i + bs];
206        let mut count = 1;
207        let mut pos = i + bs;
208        while pos + bs <= end && &bytes[pos..pos + bs] == unit {
209            count += 1;
210            pos += bs;
211        }
212        (count >= min_rows).then_some(count)
213    }
214}
215
216fn rule_decision(rules: &[RunRule], value: u8, run_len: usize) -> RuleDecision {
217    // exact-value rules before the `None` catch-all
218    for rule in rules.iter().filter(|r| r.value == Some(value)) {
219        if let Some(min_run) = rule.min_run {
220            if run_len >= min_run {
221                return RuleDecision::Compress;
222            }
223        } else {
224            return RuleDecision::ForceLiteral;
225        }
226    }
227    for rule in rules.iter().filter(|r| r.value.is_none()) {
228        if let Some(min_run) = rule.min_run {
229            if run_len >= min_run {
230                return RuleDecision::Compress;
231            }
232        } else {
233            return RuleDecision::ForceLiteral;
234        }
235    }
236    RuleDecision::NoMatch
237}
238
239fn push_literal<'a>(out: &mut Vec<DataChunk<'a, u8>>, bytes: &'a [u8], start: usize, end: usize) {
240    if start < end {
241        out.push(DataChunk::Literal(&bytes[start..end]));
242    }
243}
244
245/// A processed chunk of data.
246#[derive(Debug, Clone, PartialEq, Eq)]
247pub enum DataChunk<'a, T> {
248    /// A row sequence of literals.
249    Literal(&'a [T]),
250    /// A run of a single value.
251    Run(T, usize),
252    /// A run of a single value that is a multiple of the block size.
253    BlockRun(&'a [T], usize),
254}
255
256#[cfg(test)]
257mod tests {
258    use super::*;
259    use DataChunk::*;
260
261    fn rule(value: Option<u8>, min_run: usize) -> RunRule {
262        RunRule {
263            value,
264            min_run: Some(min_run),
265        }
266    }
267
268    fn rule_literal(value: Option<u8>) -> RunRule {
269        RunRule {
270            value,
271            min_run: None,
272        }
273    }
274
275    fn heur(
276        interior: Vec<RunRule>,
277        leading: Option<EdgeTrim>,
278        trailing: Option<EdgeTrim>,
279    ) -> DataHeuristics {
280        DataHeuristics {
281            block_size: 4,
282            interior,
283            leading,
284            trailing,
285            ..Default::default()
286        }
287    }
288
289    fn run<'a>(h: &DataHeuristics, b: &'a [u8]) -> Vec<DataChunk<'a, u8>> {
290        h.iterate(0, None, b).collect()
291    }
292
293    #[test]
294    fn empty_yields_nothing() {
295        assert!(run(&heur(vec![], None, None), &[]).is_empty());
296    }
297
298    #[test]
299    fn all_literal_one_span() {
300        let h = heur(vec![rule(Some(0x00), 4)], None, None);
301        assert_eq!(run(&h, &[1, 2, 3, 4, 5]), vec![Literal(&[1, 2, 3, 4, 5])]);
302    }
303
304    #[test]
305    fn interior_run_splits_literals() {
306        let h = heur(vec![rule(Some(0x00), 4)], None, None);
307        assert_eq!(
308            run(&h, &[1, 2, 0, 0, 0, 0, 0, 3]),
309            vec![Literal(&[1, 2]), Run(0x00, 5), Literal(&[3])]
310        );
311    }
312
313    #[test]
314    fn short_run_stays_literal() {
315        let h = heur(vec![rule(Some(0x00), 4)], None, None);
316        assert_eq!(run(&h, &[1, 0, 0, 2]), vec![Literal(&[1, 0, 0, 2])]);
317    }
318
319    #[test]
320    fn min_run_boundary() {
321        let h = heur(vec![rule(Some(0xFF), 8)], None, None);
322        // 7 bytes: below min, whole thing literal
323        assert_eq!(
324            run(&h, &[1, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 2]),
325            vec![Literal(&[1, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 2])]
326        );
327        // 8 bytes: compresses
328        assert_eq!(
329            run(&h, &[1, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 2]),
330            vec![Literal(&[1]), Run(0xFF, 8), Literal(&[2])]
331        );
332    }
333
334    #[test]
335    fn catch_all_matches_any() {
336        let h = heur(vec![rule(None, 4)], None, None);
337        assert_eq!(run(&h, &[0x42, 0x42, 0x42, 0x42, 0x42]), vec![Run(0x42, 5)]);
338    }
339
340    #[test]
341    fn literal_rule_short_circuits() {
342        let h = heur(vec![rule_literal(Some(0x20)), rule(None, 1)], None, None);
343        assert_eq!(run(&h, &[0x20; 6]), vec![Literal(&[0x20; 6])]);
344    }
345
346    #[test]
347    fn trailing_reserve_preserves_checksum() {
348        let trailing = EdgeTrim {
349            rules: vec![rule(Some(0xFF), 4)],
350            reserve: 2,
351        };
352        let h = heur(vec![], None, Some(trailing));
353        let bytes = [10, 11, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xAA, 0xBB];
354        assert_eq!(
355            run(&h, &bytes),
356            vec![Literal(&[10, 11]), Run(0xFF, 6), Literal(&[0xAA, 0xBB])]
357        );
358    }
359
360    #[test]
361    fn leading_reserve_preserves_signature() {
362        let leading = EdgeTrim {
363            rules: vec![rule(Some(0x00), 2)],
364            reserve: 2,
365        };
366        let h = heur(vec![], Some(leading), None);
367        let bytes = [0xAA, 0x55, 0, 0, 0, 0, 10];
368        assert_eq!(
369            run(&h, &bytes),
370            vec![Literal(&[0xAA, 0x55]), Run(0x00, 4), Literal(&[10])]
371        );
372    }
373
374    #[test]
375    fn edge_rule_relaxes_threshold() {
376        let interior = vec![rule(Some(0xFF), 64)];
377        let trailing = EdgeTrim {
378            rules: vec![rule(Some(0xFF), 4)],
379            reserve: 0,
380        };
381        let h = heur(interior, None, Some(trailing));
382        // interior min 64 would not fire, trailing min 4 does
383        assert_eq!(
384            run(&h, &[1, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]),
385            vec![Literal(&[1]), Run(0xFF, 5)]
386        );
387    }
388
389    #[test]
390    fn literal_rows_pack() {
391        let h = DataHeuristics::default();
392        let bytes = (0..40).collect::<Vec<_>>();
393        let rows = h.literal_rows(&bytes);
394        assert_eq!(rows.len(), 3);
395        assert_eq!(rows[0].len(), 16);
396        assert_eq!(rows[1].len(), 16);
397        assert_eq!(rows[2].len(), 8);
398    }
399
400    #[test]
401    fn block_run_folds() {
402        let mut h = heur(vec![], None, None);
403        h.block_size = 2;
404        h.min_repeat_rows = Some(3);
405        assert_eq!(
406            run(&h, &[0xDE, 0xAD, 0xDE, 0xAD, 0xDE, 0xAD]),
407            vec![BlockRun(&[0xDE, 0xAD], 3)]
408        );
409    }
410
411    #[test]
412    fn single_value_run_wins() {
413        let mut h = heur(vec![rule(Some(0xFF), 4)], None, None);
414        h.block_size = 2;
415        h.min_repeat_rows = Some(2);
416        assert_eq!(run(&h, &[0xFF; 6]), vec![Run(0xFF, 6)]);
417    }
418}