mf4_rs/blocks/
source_block.rs1use byteorder::{ByteOrder, LittleEndian};
2use crate::blocks::common::BlockHeader;
3use crate::error::MdfError;
4use crate::blocks::common::BlockParse;
5
6#[derive(Debug)]
18pub struct SourceBlock {
19 pub header: BlockHeader,
20 pub name_addr: u64,
22 pub path_addr: u64,
24 pub comment_addr: u64,
26
27 pub source_type: u8,
28 pub bus_type: u8,
29 pub flags: u8,
30 }
32
33impl BlockParse<'_> for SourceBlock {
34 const ID: &'static str = "##SI";
35 fn from_bytes(bytes: &[u8]) -> Result<Self, MdfError> {
37
38 let header = Self::parse_header(bytes)?;
39
40 let required = 24u64
44 .saturating_add(header.links_nr.saturating_mul(8))
45 .saturating_add(3);
46 if (bytes.len() as u64) < required {
47 return Err(MdfError::TooShortBuffer {
48 actual: bytes.len(),
49 expected: usize::try_from(required).unwrap_or(usize::MAX),
50 file: file!(),
51 line: line!(),
52 });
53 }
54 let link_count = header.links_nr as usize;
55
56 let mut name_addr = 0;
58 let mut path_addr = 0;
59 let mut comment_addr = 0;
60 for i in 0..link_count.min(3) {
61 let off = 24 + i * 8;
62 let link = LittleEndian::read_u64(&bytes[off..off + 8]);
63 match i {
64 0 => name_addr = link,
65 1 => path_addr = link,
66 2 => comment_addr = link,
67 _ => {}
68 }
69 }
70
71 let data_start = 24 + link_count * 8;
73 let source_type = bytes[data_start];
74 let bus_type = bytes[data_start + 1];
75 let flags = bytes[data_start + 2];
76 Ok(SourceBlock {
79 header,
80 name_addr,
81 path_addr,
82 comment_addr,
83 source_type,
84 bus_type,
85 flags,
86 })
87 }
88}
89
90pub fn read_source_block(mmap: &[u8], address: u64) -> Result<SourceBlock, MdfError> {
99
100 let start = address as usize;
101 if start.checked_add(24).is_none_or(|end| end > mmap.len()) {
102 return Err(MdfError::TooShortBuffer {
103 actual: mmap.len(),
104 expected: start.saturating_add(24),
105 file: file!(),
106 line: line!(),
107 });
108 }
109 let header = BlockHeader::from_bytes(&mmap[start..start + 24])?;
110 let total_len = header.block_len as usize;
112 let end = start.checked_add(total_len).ok_or(MdfError::TooShortBuffer {
113 actual: mmap.len(),
114 expected: usize::MAX,
115 file: file!(),
116 line: line!(),
117 })?;
118 if end > mmap.len() {
119 return Err(MdfError::TooShortBuffer {
120 actual: mmap.len(),
121 expected: end,
122 file: file!(),
123 line: line!(),
124 });
125 }
126 let slice = &mmap[start..end];
127 SourceBlock::from_bytes(slice)
128}