Skip to main content

mf4_rs/
block_layout.rs

1//! Block layout visualization for MDF4 files.
2//!
3//! Walks every block in a memory-mapped MDF file, records the byte range it
4//! occupies and the links it carries, and renders the result as a flat table,
5//! an indented tree, or JSON. Useful for inspecting how data is laid out on
6//! disk, verifying link chains and comparing structure against the MDF 4.1
7//! specification.
8
9use std::collections::{HashMap, HashSet};
10use std::fmt::Write as _;
11use std::fs;
12
13use byteorder::{ByteOrder, LittleEndian};
14use serde::{Deserialize, Serialize};
15
16use crate::blocks::channel_block::ChannelBlock;
17use crate::blocks::channel_group_block::ChannelGroupBlock;
18use crate::blocks::common::{BlockHeader, BlockParse};
19use crate::blocks::conversion::ConversionBlock;
20use crate::blocks::data_group_block::DataGroupBlock;
21use crate::blocks::data_list_block::DataListBlock;
22use crate::blocks::header_block::HeaderBlock;
23use crate::blocks::identification_block::IdentificationBlock;
24use crate::blocks::metadata_block::MetadataBlock;
25use crate::blocks::source_block::SourceBlock;
26use crate::blocks::text_block::TextBlock;
27use crate::error::MdfError;
28
29/// A named link inside a block.
30#[derive(Debug, Clone, Serialize, Deserialize)]
31pub struct LinkInfo {
32    /// Human-readable name of the link field (e.g. `first_dg_addr`).
33    pub name: String,
34    /// Absolute file offset the link points to. `0` means null.
35    pub target: u64,
36    /// Block ID at that offset if it could be resolved (e.g. `##TX`).
37    pub target_type: Option<String>,
38}
39
40/// A single block visited while walking the file.
41#[derive(Debug, Clone, Serialize, Deserialize)]
42pub struct BlockInfo {
43    /// Absolute file offset where the block starts.
44    pub offset: u64,
45    /// Byte immediately after the block (`offset + size`).
46    pub end_offset: u64,
47    /// Total size of the block in bytes (`block_len` from its header, or 64
48    /// for the identification block).
49    pub size: u64,
50    /// MDF block ID (`##HD`, `##DG`, …) or `##ID` for the identification
51    /// block.
52    pub block_type: String,
53    /// Short description of the block's role (e.g. `Channel 'Time'`).
54    pub description: String,
55    /// All links carried by the block, in their on-disk order.
56    pub links: Vec<LinkInfo>,
57    /// Additional free-form details (e.g. record layout of a `##DT`).
58    pub extra: Option<String>,
59}
60
61/// A stretch of the file that was not covered by any visited block.
62#[derive(Debug, Clone, Serialize, Deserialize)]
63pub struct GapInfo {
64    pub start: u64,
65    pub end: u64,
66    pub size: u64,
67}
68
69/// Full layout of an MDF file.
70#[derive(Debug, Clone, Serialize, Deserialize)]
71pub struct FileLayout {
72    pub file_size: u64,
73    /// Blocks sorted by offset.
74    pub blocks: Vec<BlockInfo>,
75    /// Byte ranges inside the file that no visited block covered.
76    pub gaps: Vec<GapInfo>,
77}
78
79impl FileLayout {
80    /// Build a layout by reading an MDF file from disk into memory.
81    #[cfg(not(target_arch = "wasm32"))]
82    pub fn from_file(path: &str) -> Result<Self, MdfError> {
83        let data = fs::read(path)?;
84        Self::from_bytes(&data)
85    }
86
87    /// Build a layout by walking an in-memory MDF image.
88    pub fn from_bytes(data: &[u8]) -> Result<Self, MdfError> {
89        let mut walker = Walker::new(data);
90        walker.walk()?;
91        let mut blocks = walker.blocks;
92        blocks.sort_by_key(|b| b.offset);
93        let gaps = compute_gaps(data.len() as u64, &blocks);
94        Ok(FileLayout {
95            file_size: data.len() as u64,
96            blocks,
97            gaps,
98        })
99    }
100
101    /// Render a flat, sorted listing followed by per-block link sections.
102    pub fn to_text(&self) -> String {
103        let mut out = String::new();
104        let _ = writeln!(
105            out,
106            "MDF block layout (file size: {} bytes / 0x{:x})",
107            self.file_size, self.file_size
108        );
109        let _ = writeln!(out);
110        let _ = writeln!(out, "Blocks ({} total), sorted by offset:", self.blocks.len());
111        let _ = writeln!(
112            out,
113            "{:<12}  {:<12}  {:>10}  {:<6}  description",
114            "offset", "end", "size", "type"
115        );
116        let _ = writeln!(
117            out,
118            "{:-<12}  {:-<12}  {:->10}  {:-<6}  {:-<60}",
119            "", "", "", "", ""
120        );
121        for b in &self.blocks {
122            let _ = writeln!(
123                out,
124                "0x{:010x}  0x{:010x}  {:>10}  {:<6}  {}",
125                b.offset, b.end_offset, b.size, b.block_type, b.description
126            );
127            if let Some(extra) = &b.extra {
128                let _ = writeln!(out, "{:<44}{}", "", extra);
129            }
130        }
131
132        if !self.gaps.is_empty() {
133            let _ = writeln!(out);
134            let _ = writeln!(out, "Unreferenced byte ranges (gaps):");
135            for g in &self.gaps {
136                let _ = writeln!(
137                    out,
138                    "  0x{:010x} .. 0x{:010x}  ({} bytes)",
139                    g.start, g.end, g.size
140                );
141            }
142        }
143
144        let _ = writeln!(out);
145        let _ = writeln!(out, "Block links:");
146        for b in &self.blocks {
147            if b.links.is_empty() {
148                continue;
149            }
150            let _ = writeln!(
151                out,
152                "  {} @ 0x{:010x} ({})",
153                b.block_type, b.offset, b.description
154            );
155            for link in &b.links {
156                if link.target == 0 {
157                    let _ = writeln!(out, "    {:<28} -> (null)", link.name);
158                } else {
159                    let type_label = link.target_type.as_deref().unwrap_or("?");
160                    let _ = writeln!(
161                        out,
162                        "    {:<28} -> 0x{:010x} ({})",
163                        link.name, link.target, type_label
164                    );
165                }
166            }
167        }
168        out
169    }
170
171    /// Render the link graph as an indented tree starting at `##ID`.
172    pub fn to_tree(&self) -> String {
173        let by_offset: HashMap<u64, &BlockInfo> =
174            self.blocks.iter().map(|b| (b.offset, b)).collect();
175        let mut out = String::new();
176        let mut visited = HashSet::new();
177        if let Some(root) = by_offset.get(&0) {
178            render_tree_node(root, &by_offset, &mut visited, &mut out, "", true, true, None);
179        }
180        // Any block unreachable from ##ID (shouldn't normally happen) gets
181        // appended as extra roots so nothing is silently dropped.
182        for b in &self.blocks {
183            if !visited.contains(&b.offset) {
184                render_tree_node(b, &by_offset, &mut visited, &mut out, "", true, true, None);
185            }
186        }
187        out
188    }
189
190    /// Serialize the layout to a pretty JSON string.
191    pub fn to_json(&self) -> Result<String, MdfError> {
192        serde_json::to_string_pretty(self)
193            .map_err(|e| MdfError::BlockSerializationError(format!("layout JSON: {e}")))
194    }
195
196    /// Write the text listing to `path`.
197    #[cfg(not(target_arch = "wasm32"))]
198    pub fn write_text_to_file(&self, path: &str) -> Result<(), MdfError> {
199        fs::write(path, self.to_text())?;
200        Ok(())
201    }
202
203    /// Write the tree view to `path`.
204    #[cfg(not(target_arch = "wasm32"))]
205    pub fn write_tree_to_file(&self, path: &str) -> Result<(), MdfError> {
206        fs::write(path, self.to_tree())?;
207        Ok(())
208    }
209
210    /// Write JSON to `path`.
211    #[cfg(not(target_arch = "wasm32"))]
212    pub fn write_json_to_file(&self, path: &str) -> Result<(), MdfError> {
213        fs::write(path, self.to_json()?)?;
214        Ok(())
215    }
216}
217
218fn compute_gaps(file_size: u64, blocks: &[BlockInfo]) -> Vec<GapInfo> {
219    let mut gaps = Vec::new();
220    let mut cursor = 0u64;
221    for b in blocks {
222        if b.offset > cursor {
223            gaps.push(GapInfo {
224                start: cursor,
225                end: b.offset,
226                size: b.offset - cursor,
227            });
228        }
229        if b.end_offset > cursor {
230            cursor = b.end_offset;
231        }
232    }
233    if cursor < file_size {
234        gaps.push(GapInfo {
235            start: cursor,
236            end: file_size,
237            size: file_size - cursor,
238        });
239    }
240    gaps
241}
242
243fn render_tree_node(
244    node: &BlockInfo,
245    by_offset: &HashMap<u64, &BlockInfo>,
246    visited: &mut HashSet<u64>,
247    out: &mut String,
248    prefix: &str,
249    is_last: bool,
250    is_root: bool,
251    link_label: Option<&str>,
252) {
253    let connector = if is_root {
254        ""
255    } else if is_last {
256        "`-- "
257    } else {
258        "|-- "
259    };
260    let label = match link_label {
261        Some(l) => format!("({}) ", l),
262        None => String::new(),
263    };
264    let already = visited.contains(&node.offset);
265    let _ = writeln!(
266        out,
267        "{}{}{}{} @ 0x{:010x} [{}]{}",
268        prefix,
269        connector,
270        label,
271        node.block_type,
272        node.offset,
273        node.description,
274        if already { " (already listed)" } else { "" }
275    );
276    if already {
277        return;
278    }
279    visited.insert(node.offset);
280
281    let child_prefix = if is_root {
282        String::new()
283    } else if is_last {
284        format!("{}    ", prefix)
285    } else {
286        format!("{}|   ", prefix)
287    };
288
289    // Resolve children: keep only links that point at a block we actually
290    // visited (so we render in the original link order).
291    let children: Vec<(usize, &LinkInfo)> = node
292        .links
293        .iter()
294        .enumerate()
295        .filter(|(_, l)| l.target != 0 && by_offset.contains_key(&l.target))
296        .collect();
297    let count = children.len();
298    for (idx, (_, link)) in children.into_iter().enumerate() {
299        let child = by_offset[&link.target];
300        let last_child = idx + 1 == count;
301        render_tree_node(
302            child,
303            by_offset,
304            visited,
305            out,
306            &child_prefix,
307            last_child,
308            false,
309            Some(link.name.as_str()),
310        );
311    }
312}
313
314// ---------------------------------------------------------------------------
315// Walker implementation
316// ---------------------------------------------------------------------------
317
318struct Walker<'a> {
319    data: &'a [u8],
320    visited: HashSet<u64>,
321    blocks: Vec<BlockInfo>,
322    dg_counter: usize,
323    cg_counter: usize,
324    cn_counter: usize,
325}
326
327impl<'a> Walker<'a> {
328    fn new(data: &'a [u8]) -> Self {
329        Self {
330            data,
331            visited: HashSet::new(),
332            blocks: Vec::new(),
333            dg_counter: 0,
334            cg_counter: 0,
335            cn_counter: 0,
336        }
337    }
338
339    /// Return the file bytes starting at `offset`, verifying that at least
340    /// `needed` bytes are available. Prevents slice panics on truncated or
341    /// malformed files with out-of-range link addresses.
342    fn bytes_at(&self, offset: usize, needed: usize) -> Result<&'a [u8], MdfError> {
343        if offset
344            .checked_add(needed)
345            .is_none_or(|end| end > self.data.len())
346        {
347            return Err(MdfError::TooShortBuffer {
348                actual: self.data.len(),
349                expected: offset.saturating_add(needed),
350                file: file!(),
351                line: line!(),
352            });
353        }
354        Ok(&self.data[offset..])
355    }
356
357    fn walk(&mut self) -> Result<(), MdfError> {
358        // ##ID (not a standard block header - exactly 64 bytes at offset 0).
359        let id = IdentificationBlock::from_bytes(self.bytes_at(0, 64)?)?;
360        self.blocks.push(BlockInfo {
361            offset: 0,
362            end_offset: 64,
363            size: 64,
364            block_type: "##ID".to_string(),
365            description: format!(
366                "Identification: version='{}', program='{}'",
367                id.version_identifier.trim(),
368                id.program_identifier.trim_end()
369            ),
370            links: Vec::new(),
371            extra: Some(format!(
372                "version_number={}, standard_unfinalized_flags=0x{:04x}, custom_unfinalized_flags=0x{:04x}",
373                id.version_number, id.standard_unfinalized_flags, id.custom_unfinalized_flags
374            )),
375        });
376        self.visited.insert(0);
377
378        self.walk_header(64)?;
379        Ok(())
380    }
381
382    fn peek_id(&self, offset: u64) -> Option<String> {
383        if offset == 0 {
384            return None;
385        }
386        let o = offset as usize;
387        if o + 4 > self.data.len() {
388            return None;
389        }
390        Some(String::from_utf8_lossy(&self.data[o..o + 4]).to_string())
391    }
392
393    fn walk_header(&mut self, offset: u64) -> Result<(), MdfError> {
394        if !self.visited.insert(offset) {
395            return Ok(());
396        }
397        let o = offset as usize;
398        let hd = HeaderBlock::from_bytes(self.bytes_at(o, 104)?)?;
399
400        let links = vec![
401            self.make_link("first_dg_addr", hd.first_dg_addr),
402            self.make_link("file_history_addr", hd.file_history_addr),
403            self.make_link("channel_tree_addr", hd.channel_tree_addr),
404            self.make_link("first_attachment_addr", hd.first_attachment_addr),
405            self.make_link("first_event_addr", hd.first_event_addr),
406            self.make_link("comment_addr", hd.comment_addr),
407        ];
408        self.blocks.push(BlockInfo {
409            offset,
410            end_offset: offset + 104,
411            size: 104,
412            block_type: "##HD".to_string(),
413            description: format!("Header Block (abs_time={} ns, tz={} min)", hd.abs_time, hd.tz_offset),
414            links,
415            extra: Some(format!(
416                "flags=0x{:02x}, time_flags=0x{:02x}, time_quality=0x{:02x}",
417                hd.flags, hd.time_flags, hd.time_quality
418            )),
419        });
420
421        // Comment before data groups, so text blocks appear in file order.
422        self.walk_text_like(hd.comment_addr)?;
423
424        let mut dg_addr = hd.first_dg_addr;
425        while dg_addr != 0 {
426            let next = self.walk_data_group(dg_addr)?;
427            dg_addr = next;
428        }
429        Ok(())
430    }
431
432    fn walk_data_group(&mut self, offset: u64) -> Result<u64, MdfError> {
433        if !self.visited.insert(offset) {
434            return Ok(0);
435        }
436        let o = offset as usize;
437        let dg = DataGroupBlock::from_bytes(self.bytes_at(o, 64)?)?;
438        let size = dg.header.block_len;
439
440        let links = vec![
441            self.make_link("next_dg_addr", dg.next_dg_addr),
442            self.make_link("first_cg_addr", dg.first_cg_addr),
443            self.make_link("data_block_addr", dg.data_block_addr),
444            self.make_link("comment_addr", dg.comment_addr),
445        ];
446
447        let index = self.dg_counter;
448        self.dg_counter += 1;
449        self.blocks.push(BlockInfo {
450            offset,
451            end_offset: offset + size,
452            size,
453            block_type: "##DG".to_string(),
454            description: format!("Data Group #{} (record_id_len={})", index, dg.record_id_len),
455            links,
456            extra: None,
457        });
458
459        self.walk_text_like(dg.comment_addr)?;
460
461        // Walk all channel groups first so we know the record layout before we
462        // describe the data block.
463        let mut first_cg_record_size: Option<usize> = None;
464        let mut first_cg_invalidation: u32 = 0;
465        let mut cg_addr = dg.first_cg_addr;
466        let mut cg_count = 0;
467        while cg_addr != 0 {
468            let (next, record_size, inval) =
469                self.walk_channel_group(cg_addr, dg.record_id_len)?;
470            if cg_count == 0 {
471                first_cg_record_size = Some(record_size);
472                first_cg_invalidation = inval;
473            }
474            cg_addr = next;
475            cg_count += 1;
476        }
477
478        if dg.data_block_addr != 0 {
479            self.walk_data_region(
480                dg.data_block_addr,
481                first_cg_record_size,
482                first_cg_invalidation,
483                dg.record_id_len,
484            )?;
485        }
486
487        Ok(dg.next_dg_addr)
488    }
489
490    fn walk_channel_group(
491        &mut self,
492        offset: u64,
493        record_id_len: u8,
494    ) -> Result<(u64, usize, u32), MdfError> {
495        if !self.visited.insert(offset) {
496            return Ok((0, 0, 0));
497        }
498        let o = offset as usize;
499        let cg = ChannelGroupBlock::from_bytes(self.bytes_at(o, 104)?)?;
500        let size = cg.header.block_len;
501        let record_size = record_id_len as usize
502            + cg.samples_byte_nr as usize
503            + cg.invalidation_bytes_nr as usize;
504
505        let mut links = vec![
506            self.make_link("next_cg_addr", cg.next_cg_addr),
507            self.make_link("first_ch_addr", cg.first_ch_addr),
508            self.make_link("acq_name_addr", cg.acq_name_addr),
509            self.make_link("acq_source_addr", cg.acq_source_addr),
510            self.make_link("first_sample_reduction_addr", cg.first_sample_reduction_addr),
511            self.make_link("comment_addr", cg.comment_addr),
512        ];
513        if cg.header.links_nr >= 7 {
514            links.push(self.make_link("master_cg_addr", cg.master_cg_addr));
515        }
516
517        let index = self.cg_counter;
518        self.cg_counter += 1;
519        self.blocks.push(BlockInfo {
520            offset,
521            end_offset: offset + size,
522            size,
523            block_type: "##CG".to_string(),
524            description: format!(
525                "Channel Group #{} (cycles={}, record={}B = {}B data + {}B inval + {}B record_id)",
526                index,
527                cg.cycles_nr,
528                record_size,
529                cg.samples_byte_nr,
530                cg.invalidation_bytes_nr,
531                record_id_len
532            ),
533            links,
534            extra: Some(format!("flags=0x{:04x}, record_id={}", cg.flags, cg.record_id)),
535        });
536
537        self.walk_text_like(cg.acq_name_addr)?;
538        self.walk_source(cg.acq_source_addr)?;
539        self.walk_text_like(cg.comment_addr)?;
540
541        let mut ch_addr = cg.first_ch_addr;
542        while ch_addr != 0 {
543            let next = self.walk_channel(ch_addr)?;
544            ch_addr = next;
545        }
546
547        Ok((cg.next_cg_addr, record_size, cg.invalidation_bytes_nr))
548    }
549
550    fn walk_channel(&mut self, offset: u64) -> Result<u64, MdfError> {
551        if !self.visited.insert(offset) {
552            return Ok(0);
553        }
554        let o = offset as usize;
555        let cn = ChannelBlock::from_bytes(self.bytes_at(o, 160)?)?;
556        let size = cn.header.block_len;
557
558        let name = read_text_at(self.data, cn.name_addr).unwrap_or_default();
559
560        let links = vec![
561            self.make_link("next_ch_addr", cn.next_ch_addr),
562            self.make_link("component_addr", cn.component_addr),
563            self.make_link("name_addr", cn.name_addr),
564            self.make_link("source_addr", cn.source_addr),
565            self.make_link("conversion_addr", cn.conversion_addr),
566            self.make_link("data", cn.data),
567            self.make_link("unit_addr", cn.unit_addr),
568            self.make_link("comment_addr", cn.comment_addr),
569        ];
570
571        let index = self.cn_counter;
572        self.cn_counter += 1;
573        self.blocks.push(BlockInfo {
574            offset,
575            end_offset: offset + size,
576            size,
577            block_type: "##CN".to_string(),
578            description: format!(
579                "Channel #{} '{}' (ch_type={}, sync={}, dtype={:?}, {}b @ byte={} bit={})",
580                index,
581                name,
582                cn.channel_type,
583                cn.sync_type,
584                cn.data_type,
585                cn.bit_count,
586                cn.byte_offset,
587                cn.bit_offset
588            ),
589            links,
590            extra: Some(format!(
591                "flags=0x{:08x}, pos_invalidation_bit={}, precision={}",
592                cn.flags, cn.pos_invalidation_bit, cn.precision
593            )),
594        });
595
596        self.walk_text_like(cn.name_addr)?;
597        self.walk_source(cn.source_addr)?;
598        self.walk_conversion(cn.conversion_addr)?;
599        self.walk_text_like(cn.unit_addr)?;
600        self.walk_text_like(cn.comment_addr)?;
601
602        // VLSD channels reuse the `data` field to point at SD/DL chains.
603        if cn.channel_type == 1 && cn.data != 0 {
604            self.walk_data_region(cn.data, None, 0, 0)?;
605        }
606
607        Ok(cn.next_ch_addr)
608    }
609
610    fn walk_conversion(&mut self, offset: u64) -> Result<(), MdfError> {
611        if offset == 0 {
612            return Ok(());
613        }
614        if !self.visited.insert(offset) {
615            return Ok(());
616        }
617        let o = offset as usize;
618        let cc = ConversionBlock::from_bytes(self.bytes_at(o, 24)?)?;
619        let size = cc.header.block_len;
620
621        let mut links = vec![
622            self.make_link("cc_tx_name", cc.cc_tx_name.unwrap_or(0)),
623            self.make_link("cc_md_unit", cc.cc_md_unit.unwrap_or(0)),
624            self.make_link("cc_md_comment", cc.cc_md_comment.unwrap_or(0)),
625            self.make_link("cc_cc_inverse", cc.cc_cc_inverse.unwrap_or(0)),
626        ];
627        for (i, l) in cc.cc_ref.iter().enumerate() {
628            links.push(self.make_link(&format!("cc_ref[{}]", i), *l));
629        }
630
631        let extra = format!(
632            "cc_val_count={}, cc_ref_count={}, cc_flags=0x{:04x}",
633            cc.cc_val_count, cc.cc_ref_count, cc.cc_flags
634        );
635
636        self.blocks.push(BlockInfo {
637            offset,
638            end_offset: offset + size,
639            size,
640            block_type: "##CC".to_string(),
641            description: format!("Conversion ({:?})", cc.cc_type),
642            links,
643            extra: Some(extra),
644        });
645
646        self.walk_text_like(cc.cc_tx_name.unwrap_or(0))?;
647        self.walk_text_like(cc.cc_md_unit.unwrap_or(0))?;
648        self.walk_text_like(cc.cc_md_comment.unwrap_or(0))?;
649        self.walk_conversion(cc.cc_cc_inverse.unwrap_or(0))?;
650        for l in &cc.cc_ref {
651            let id = self.peek_id(*l);
652            match id.as_deref() {
653                Some("##TX") | Some("##MD") => self.walk_text_like(*l)?,
654                Some("##CC") => self.walk_conversion(*l)?,
655                _ => {}
656            }
657        }
658        Ok(())
659    }
660
661    fn walk_source(&mut self, offset: u64) -> Result<(), MdfError> {
662        if offset == 0 {
663            return Ok(());
664        }
665        if !self.visited.insert(offset) {
666            return Ok(());
667        }
668        let o = offset as usize;
669        let si = SourceBlock::from_bytes(self.bytes_at(o, 24)?)?;
670        let size = si.header.block_len;
671
672        let links = vec![
673            self.make_link("name_addr", si.name_addr),
674            self.make_link("path_addr", si.path_addr),
675            self.make_link("comment_addr", si.comment_addr),
676        ];
677        self.blocks.push(BlockInfo {
678            offset,
679            end_offset: offset + size,
680            size,
681            block_type: "##SI".to_string(),
682            description: format!(
683                "Source (type={}, bus_type={}, flags=0x{:02x})",
684                si.source_type, si.bus_type, si.flags
685            ),
686            links,
687            extra: None,
688        });
689
690        self.walk_text_like(si.name_addr)?;
691        self.walk_text_like(si.path_addr)?;
692        self.walk_text_like(si.comment_addr)?;
693        Ok(())
694    }
695
696    fn walk_text_like(&mut self, offset: u64) -> Result<(), MdfError> {
697        if offset == 0 {
698            return Ok(());
699        }
700        if !self.visited.insert(offset) {
701            return Ok(());
702        }
703        let o = offset as usize;
704        if o + 24 > self.data.len() {
705            return Ok(());
706        }
707        let header = BlockHeader::from_bytes(&self.data[o..o + 24])?;
708        match header.id.as_str() {
709            "##TX" => {
710                let tx = TextBlock::from_bytes(&self.data[o..])?;
711                let preview = preview_string(&tx.text, 48);
712                self.blocks.push(BlockInfo {
713                    offset,
714                    end_offset: offset + header.block_len,
715                    size: header.block_len,
716                    block_type: "##TX".to_string(),
717                    description: format!("Text: \"{}\" ({} chars)", preview, tx.text.chars().count()),
718                    links: Vec::new(),
719                    extra: None,
720                });
721            }
722            "##MD" => {
723                let md = MetadataBlock::from_bytes(&self.data[o..])?;
724                let preview = preview_string(&md.xml.replace('\n', " "), 48);
725                self.blocks.push(BlockInfo {
726                    offset,
727                    end_offset: offset + header.block_len,
728                    size: header.block_len,
729                    block_type: "##MD".to_string(),
730                    description: format!("Metadata (XML, {} chars): {}", md.xml.len(), preview),
731                    links: Vec::new(),
732                    extra: None,
733                });
734            }
735            _ => {
736                // Unknown ID - record the raw block so we don't pretend it
737                // isn't there.
738                self.blocks.push(BlockInfo {
739                    offset,
740                    end_offset: offset + header.block_len,
741                    size: header.block_len,
742                    block_type: header.id.clone(),
743                    description: "Unknown block (not walked further)".to_string(),
744                    links: Vec::new(),
745                    extra: None,
746                });
747            }
748        }
749        Ok(())
750    }
751
752    fn walk_data_region(
753        &mut self,
754        offset: u64,
755        record_size: Option<usize>,
756        invalidation_bytes_nr: u32,
757        record_id_len: u8,
758    ) -> Result<(), MdfError> {
759        if offset == 0 {
760            return Ok(());
761        }
762        let id = self.peek_id(offset).unwrap_or_default();
763        match id.as_str() {
764            "##DT" | "##DV" | "##RD" | "##RV" => {
765                self.record_simple_data_block(offset, &id, record_size, invalidation_bytes_nr, record_id_len)?;
766            }
767            "##SD" => {
768                self.record_signal_data_block(offset)?;
769            }
770            "##DL" => {
771                self.walk_data_list(offset, record_size, invalidation_bytes_nr, record_id_len)?;
772            }
773            "" => {}
774            other => {
775                // Unrecognised data block id - record it flat.
776                if self.visited.insert(offset) {
777                    let o = offset as usize;
778                    if o + 24 <= self.data.len() {
779                        let header = BlockHeader::from_bytes(&self.data[o..o + 24])?;
780                        self.blocks.push(BlockInfo {
781                            offset,
782                            end_offset: offset + header.block_len,
783                            size: header.block_len,
784                            block_type: other.to_string(),
785                            description: "Unknown data block".to_string(),
786                            links: Vec::new(),
787                            extra: None,
788                        });
789                    }
790                }
791            }
792        }
793        Ok(())
794    }
795
796    fn record_simple_data_block(
797        &mut self,
798        offset: u64,
799        id: &str,
800        record_size: Option<usize>,
801        invalidation_bytes_nr: u32,
802        record_id_len: u8,
803    ) -> Result<(), MdfError> {
804        if !self.visited.insert(offset) {
805            return Ok(());
806        }
807        let o = offset as usize;
808        let header = BlockHeader::from_bytes(self.bytes_at(o, 24)?)?;
809        let size = header.block_len;
810        let payload = size.saturating_sub(24);
811
812        let extra = match record_size {
813            Some(rs) if rs > 0 => {
814                let records = payload as usize / rs;
815                let leftover = payload as usize % rs;
816                Some(format!(
817                    "payload={} bytes, header=24 bytes, record layout = {}B (record_id={}B + data + invalidation={}B), records={}{}",
818                    payload,
819                    rs,
820                    record_id_len,
821                    invalidation_bytes_nr,
822                    records,
823                    if leftover > 0 {
824                        format!(", trailing={}B", leftover)
825                    } else {
826                        String::new()
827                    }
828                ))
829            }
830            _ => Some(format!("payload={} bytes (header=24 bytes)", payload)),
831        };
832
833        self.blocks.push(BlockInfo {
834            offset,
835            end_offset: offset + size,
836            size,
837            block_type: id.to_string(),
838            description: format!("Data block ({} payload bytes)", payload),
839            links: Vec::new(),
840            extra,
841        });
842        Ok(())
843    }
844
845    fn record_signal_data_block(&mut self, offset: u64) -> Result<(), MdfError> {
846        if !self.visited.insert(offset) {
847            return Ok(());
848        }
849        let o = offset as usize;
850        let header = BlockHeader::from_bytes(self.bytes_at(o, 24)?)?;
851        let size = header.block_len;
852        self.blocks.push(BlockInfo {
853            offset,
854            end_offset: offset + size,
855            size,
856            block_type: "##SD".to_string(),
857            description: format!("Signal data (VLSD stream, {} payload bytes)", size.saturating_sub(24)),
858            links: Vec::new(),
859            extra: None,
860        });
861        Ok(())
862    }
863
864    fn walk_data_list(
865        &mut self,
866        offset: u64,
867        record_size: Option<usize>,
868        invalidation_bytes_nr: u32,
869        record_id_len: u8,
870    ) -> Result<(), MdfError> {
871        if !self.visited.insert(offset) {
872            return Ok(());
873        }
874        let o = offset as usize;
875        let dl = DataListBlock::from_bytes(self.bytes_at(o, 24)?)?;
876        let size = dl.header.block_len;
877
878        let mut links = vec![self.make_link("next", dl.next)];
879        for (i, l) in dl.data_links.iter().enumerate() {
880            links.push(self.make_link(&format!("data_links[{}]", i), *l));
881        }
882
883        let desc = format!(
884            "Data List ({} fragments{})",
885            dl.data_block_nr,
886            if dl.flags & 1 != 0 {
887                format!(", equal_length={}B", dl.data_block_len.unwrap_or(0))
888            } else {
889                String::new()
890            }
891        );
892
893        self.blocks.push(BlockInfo {
894            offset,
895            end_offset: offset + size,
896            size,
897            block_type: "##DL".to_string(),
898            description: desc,
899            links,
900            extra: Some(format!("flags=0x{:02x}", dl.flags)),
901        });
902
903        for l in dl.data_links.iter() {
904            self.walk_data_region(*l, record_size, invalidation_bytes_nr, record_id_len)?;
905        }
906        if dl.next != 0 {
907            self.walk_data_region(dl.next, record_size, invalidation_bytes_nr, record_id_len)?;
908        }
909        Ok(())
910    }
911
912    fn make_link(&self, name: &str, target: u64) -> LinkInfo {
913        LinkInfo {
914            name: name.to_string(),
915            target,
916            target_type: self.peek_id(target),
917        }
918    }
919}
920
921fn read_text_at(data: &[u8], addr: u64) -> Option<String> {
922    if addr == 0 {
923        return None;
924    }
925    let o = addr as usize;
926    if o + 24 > data.len() {
927        return None;
928    }
929    let id = &data[o..o + 4];
930    if id != b"##TX" {
931        return None;
932    }
933    let block_len = LittleEndian::read_u64(&data[o + 8..o + 16]);
934    let end = o + block_len as usize;
935    if end > data.len() {
936        return None;
937    }
938    let raw = &data[o + 24..end];
939    Some(
940        String::from_utf8_lossy(raw)
941            .trim_matches('\0')
942            .to_string(),
943    )
944}
945
946fn preview_string(s: &str, max_chars: usize) -> String {
947    if s.chars().count() <= max_chars {
948        s.to_string()
949    } else {
950        let taken: String = s.chars().take(max_chars).collect();
951        format!("{}...", taken)
952    }
953}