Skip to main content

mlt_core/dump/
render.rs

1//! Renders a [`DumpTree`] as an annotated hexdump.
2
3use std::io::{self, Write};
4
5#[cfg(feature = "unstable-v2")]
6use usize_cast::IntoUsize as _;
7
8use super::model::{BlobInfo, DecodeHint, DumpTree, Region, RegionKind};
9use crate::Decoder;
10use crate::decoder::RawStream;
11
12/// How data-payload blobs are shown.
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
14pub enum DataMode {
15    /// Raw hex plus best-effort decoded values (default).
16    #[default]
17    Both,
18    /// Raw hex only.
19    Blob,
20    /// Decoded values only.
21    Decoded,
22    /// A one-line summary, no payload bytes.
23    Hidden,
24}
25
26/// Rendering options for [`render`].
27#[derive(Debug, Clone, Copy)]
28pub struct RenderOpts {
29    /// Hex bytes per row.
30    pub width: usize,
31    /// Show the bit-level breakdown of packed bytes.
32    pub show_bits: bool,
33    /// Emit ANSI color escapes.
34    pub color: bool,
35    /// How to render data payloads.
36    pub data_mode: DataMode,
37    /// Truncate raw payload hex to this many bytes (`0` = unlimited).
38    pub max_blob: usize,
39}
40
41impl Default for RenderOpts {
42    fn default() -> Self {
43        Self {
44            width: 16,
45            show_bits: true,
46            color: false,
47            data_mode: DataMode::Both,
48            max_blob: 256,
49        }
50    }
51}
52
53/// Render `tree` as an annotated hexdump.
54/// `buf` must be the buffer that was passed to [`super::annotate_tile`].
55pub fn render(
56    tree: &DumpTree,
57    buf: &[u8],
58    opts: &RenderOpts,
59    w: &mut impl Write,
60) -> io::Result<()> {
61    if opts.width == 0 {
62        return Err(io::Error::new(
63            io::ErrorKind::InvalidInput,
64            "render width must be non-zero",
65        ));
66    }
67    let mut dec = Decoder::default();
68    let left_len = left_width(opts.width);
69    for region in &tree.regions {
70        render_region(w, buf, region, opts, left_len, &mut dec)?;
71    }
72    Ok(())
73}
74
75fn left_width(width: usize) -> usize {
76    // "{off:08x}  " + hex(width*3) + "  " + ascii(width)
77    8 + 2 + width * 3 + 2 + width
78}
79
80fn render_region(
81    w: &mut impl Write,
82    buf: &[u8],
83    region: &Region,
84    opts: &RenderOpts,
85    left_len: usize,
86    dec: &mut Decoder,
87) -> io::Result<()> {
88    let indent = "  ".repeat(region.depth);
89
90    if region.container {
91        let left = format!("{:08x}", region.offset);
92        let annot = format!(
93            "{indent}{} ({} B)",
94            paint(&region.label, opts, Paint::Label),
95            region.len
96        );
97        writeln!(w, "{left:<left_len$} | {annot}")?;
98        return Ok(());
99    }
100
101    let bytes = &buf[region.offset..region.offset + region.len];
102
103    match region.kind {
104        RegionKind::Meta => render_meta(w, region, bytes, opts, left_len, &indent),
105        RegionKind::DataBlob => render_blob(w, region, bytes, opts, left_len, &indent, dec),
106    }
107}
108
109fn render_meta(
110    w: &mut impl Write,
111    region: &Region,
112    bytes: &[u8],
113    opts: &RenderOpts,
114    left_len: usize,
115    indent: &str,
116) -> io::Result<()> {
117    let annot = match &region.value {
118        Some(v) => format!(
119            "{indent}{}: {}",
120            paint(&region.label, opts, Paint::Label),
121            paint(v, opts, Paint::Value)
122        ),
123        None => format!("{indent}{}", paint(&region.label, opts, Paint::Label)),
124    };
125    emit_bytes(w, region.offset, bytes, opts, left_len, &annot)?;
126
127    if opts.show_bits {
128        for bf in &region.bits {
129            let range = if bf.hi == bf.lo {
130                format!("bit {}", bf.hi)
131            } else {
132                format!("bits {}-{}", bf.hi, bf.lo)
133            };
134            let width = usize::from(bf.hi - bf.lo + 1);
135            let annot = format!(
136                "{indent}  └ {range} = {:0width$b} -> {}",
137                bf.raw,
138                bf.meaning,
139                width = width
140            );
141            writeln!(w, "{:<left_len$} | {}", "", paint(&annot, opts, Paint::Dim))?;
142        }
143    }
144    Ok(())
145}
146
147fn render_blob(
148    w: &mut impl Write,
149    region: &Region,
150    bytes: &[u8],
151    opts: &RenderOpts,
152    left_len: usize,
153    indent: &str,
154    dec: &mut Decoder,
155) -> io::Result<()> {
156    let summary = blob_summary(region, bytes);
157
158    if opts.data_mode == DataMode::Hidden {
159        let annot = format!("{indent}{}", paint(&summary, opts, Paint::Dim));
160        let left = format!("{:08x}", region.offset);
161        writeln!(w, "{left:<left_len$} | {annot}")?;
162        return Ok(());
163    }
164
165    // Raw hex (unless Decoded-only).
166    if matches!(opts.data_mode, DataMode::Both | DataMode::Blob) {
167        let annot = format!("{indent}{}", paint(&summary, opts, Paint::Dim));
168        let shown = if opts.max_blob == 0 || bytes.len() <= opts.max_blob {
169            bytes
170        } else {
171            &bytes[..opts.max_blob]
172        };
173        emit_bytes(w, region.offset, shown, opts, left_len, &annot)?;
174        if shown.len() < bytes.len() {
175            let note = format!(
176                "{indent}  ... {} more bytes omitted (--max-blob to change)",
177                bytes.len() - shown.len()
178            );
179            writeln!(w, "{:<left_len$} | {}", "", paint(&note, opts, Paint::Dim))?;
180        }
181    }
182
183    // Decoded values (unless Blob-only).
184    if matches!(opts.data_mode, DataMode::Both | DataMode::Decoded)
185        && let Some(info) = region.blob
186    {
187        let decoded = decode_blob(info, bytes, dec);
188        let annot = format!("{indent}  decoded: {}", paint(&decoded, opts, Paint::Value));
189        writeln!(w, "{:<left_len$} | {annot}", "")?;
190    }
191    Ok(())
192}
193
194/// One-line description of a data blob for its annotation column.
195fn blob_summary(region: &Region, bytes: &[u8]) -> String {
196    match region.blob {
197        Some(info) => format!(
198            "{} [{:?} {:?}/{:?}, {} values, {} B]",
199            region.label,
200            info.meta.stream_type,
201            info.meta.encoding.logical,
202            info.meta.encoding.physical,
203            info.meta.num_values,
204            bytes.len()
205        ),
206        None => format!("{} [{} B]", region.label, bytes.len()),
207    }
208}
209
210/// Best-effort decode of a stream payload for display.
211/// Never panics; decode errors are rendered inline.
212fn decode_blob(info: BlobInfo, data: &[u8], dec: &mut Decoder) -> String {
213    // Bound memory/time per blob; the decoded values are dropped immediately.
214    dec.reset_budget();
215    let meta = info.meta;
216    match info.hint {
217        DecodeHint::Presence => match RawStream::new(meta, data).decode_bitvec(dec) {
218            Ok(bits) => fmt_bits(bits.len(), |i| bits[i]),
219            Err(e) => format!("<undecodable: {e}>"),
220        },
221        #[cfg(feature = "unstable-v2")]
222        DecodeHint::PackedBits => {
223            let n = meta.num_values.into_usize();
224            let available = data.len() * 8;
225            if available < n {
226                return format!("<undecodable: needs {n} bits, got {available}>");
227            }
228            fmt_bits(n, |i| data[i / 8] >> (i % 8) & 1 == 1)
229        }
230        DecodeHint::Bool => fmt_res(RawStream::new(meta, data).decode_bools(dec)),
231        DecodeHint::I32 => fmt_res(RawStream::new(meta, data).decode_ints::<i32>(dec)),
232        DecodeHint::U32 => fmt_res(RawStream::new(meta, data).decode_ints::<u32>(dec)),
233        DecodeHint::I64 => fmt_res(RawStream::new(meta, data).decode_ints::<i64>(dec)),
234        #[cfg(feature = "unstable-v2")]
235        DecodeHint::Alp(params) => {
236            fmt_res(RawStream::new(meta, data).decode_alp_codes(params, dec))
237        }
238        DecodeHint::U64 => fmt_res(RawStream::new(meta, data).decode_ints::<u64>(dec)),
239        DecodeHint::F32 => fmt_res(RawStream::new(meta, data).decode_floats::<f32>(dec)),
240        DecodeHint::F64 => fmt_res(RawStream::new(meta, data).decode_floats::<f64>(dec)),
241        DecodeHint::Bytes => match std::str::from_utf8(data) {
242            Ok(s) => format!("utf-8 {:?}", truncate_str(s, 200)),
243            Err(_) => format!("<{} binary bytes>", data.len()),
244        },
245    }
246}
247
248/// Render the first 96 of `n` presence bits as a `0`/`1` string.
249fn fmt_bits(n: usize, bit: impl Fn(usize) -> bool) -> String {
250    let shown: String = (0..n.min(96))
251        .map(|i| if bit(i) { '1' } else { '0' })
252        .collect();
253    let more = if n > 96 { "…" } else { "" };
254    format!("{n} present-bits: {shown}{more}")
255}
256
257fn fmt_res<T: std::fmt::Display>(res: crate::MltResult<Vec<T>>) -> String {
258    match res {
259        Ok(v) => fmt_list(&v),
260        Err(e) => format!("<undecodable: {e}>"),
261    }
262}
263
264fn fmt_list<T: std::fmt::Display>(v: &[T]) -> String {
265    const MAX: usize = 48;
266    let shown = v
267        .iter()
268        .take(MAX)
269        .map(ToString::to_string)
270        .collect::<Vec<_>>()
271        .join(", ");
272    if v.len() > MAX {
273        format!("[{shown}, … ] ({} total)", v.len())
274    } else {
275        format!("[{shown}]")
276    }
277}
278
279fn truncate_str(s: &str, max: usize) -> String {
280    if s.chars().count() <= max {
281        s.to_string()
282    } else {
283        let head: String = s.chars().take(max).collect();
284        format!("{head}…")
285    }
286}
287
288/// Emit one or more hexdump rows for `bytes` starting at `offset`.
289/// The `annotation` is printed on the first row only.
290fn emit_bytes(
291    w: &mut impl Write,
292    offset: usize,
293    bytes: &[u8],
294    opts: &RenderOpts,
295    left_len: usize,
296    annotation: &str,
297) -> io::Result<()> {
298    if bytes.is_empty() {
299        let left = format!("{offset:08x}");
300        writeln!(w, "{left:<left_len$} | {annotation}")?;
301        return Ok(());
302    }
303    for (row, chunk) in bytes.chunks(opts.width).enumerate() {
304        let row_off = offset + row * opts.width;
305        let hex = chunk
306            .iter()
307            .map(|b| format!("{b:02x}"))
308            .collect::<Vec<_>>()
309            .join(" ");
310        let ascii: String = chunk
311            .iter()
312            .map(|&b| {
313                if (0x20..=0x7e).contains(&b) {
314                    b as char
315                } else {
316                    '.'
317                }
318            })
319            .collect();
320        let hexw = opts.width * 3;
321        let left = format!("{row_off:08x}  {hex:<hexw$}  {ascii}");
322        if row == 0 {
323            writeln!(w, "{left:<left_len$} | {annotation}")?;
324        } else {
325            writeln!(w, "{left:<left_len$} | ")?;
326        }
327    }
328    Ok(())
329}
330
331#[derive(Clone, Copy)]
332enum Paint {
333    Label,
334    Value,
335    Dim,
336}
337
338fn paint(s: &str, opts: &RenderOpts, kind: Paint) -> String {
339    if !opts.color {
340        return s.to_string();
341    }
342    let code = match kind {
343        Paint::Label => "1",  // bold
344        Paint::Value => "36", // cyan
345        Paint::Dim => "2",    // dim
346    };
347    format!("\x1b[{code}m{s}\x1b[0m")
348}