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