1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
use super::RawChannelGroup;
use crate::{
Error, Result,
blocks::{
DataBlock, DataGroupBlock, DataListBlock, HlBlock, u64_to_usize, {BlockHeader, BlockParse},
},
};
use alloc::string::ToString;
use alloc::vec::Vec;
#[cfg(feature = "compression")]
use crate::blocks::DzBlock;
/// Either a reference to existing data or owned decompressed data.
#[derive(Debug)]
pub enum DataBlockData<'a> {
/// Reference to memory-mapped data (uncompressed DT/DV blocks).
Borrowed(&'a [u8]),
/// Owned decompressed data (from DZ blocks).
#[cfg(feature = "compression")]
Owned(Vec<u8>),
}
impl<'a> DataBlockData<'a> {
/// Get the data as a slice.
pub fn as_slice(&self) -> &[u8] {
match self {
DataBlockData::Borrowed(s) => s,
#[cfg(feature = "compression")]
DataBlockData::Owned(v) => v.as_slice(),
}
}
/// Get the length of the data.
pub fn len(&self) -> usize {
self.as_slice().len()
}
/// Check if the data is empty.
pub fn is_empty(&self) -> bool {
self.as_slice().is_empty()
}
}
/// A data block that may contain borrowed or owned data.
///
/// This allows handling both regular DT/DV blocks (zero-copy) and
/// decompressed DZ blocks (owned data) with a unified interface.
#[derive(Debug)]
pub struct ResolvedDataBlock<'a> {
/// Original block type ID (e.g., "##DT", "##DV").
pub block_id: &'static str,
/// The data contents (may be borrowed or owned).
pub data: DataBlockData<'a>,
}
impl<'a> ResolvedDataBlock<'a> {
/// Iterate over raw records of fixed size.
///
/// # Arguments
/// * `record_size` - Size in bytes of one record (including record ID)
///
/// # Returns
/// An iterator yielding each raw record slice.
pub fn records(&self, record_size: usize) -> impl Iterator<Item = &[u8]> {
self.data.as_slice().chunks_exact(record_size)
}
}
#[derive(Debug, Clone)]
pub struct RawDataGroup {
pub block: DataGroupBlock,
pub channel_groups: Vec<RawChannelGroup>,
/// Whether this data group is from an unfinalized MDF file.
pub is_unfinalized: bool,
}
impl RawDataGroup {
/// Collect all data blocks referenced by this data group.
///
/// The returned vector contains the `DT` or `DV` blocks in the order they
/// appear on disk, transparently following any `DL` list chains.
///
/// For unfinalized MDF files, this will automatically use the correct
/// parsing method based on the `is_unfinalized` flag.
///
/// # Arguments
/// * `mmap` - Memory mapped file containing the MDF data
///
/// # Returns
/// A vector of [`DataBlock`] objects or an [`Error`] if parsing fails.
pub fn data_blocks<'a>(&self, mmap: &'a [u8]) -> Result<Vec<DataBlock<'a>>> {
let mut collected_blocks = Vec::new();
// Start at the group's primary data pointer
let mut current_block_address = self.block.data_block_addr;
// Guard against cyclic DL chains in corrupt files.
let mut seen_dl = alloc::collections::BTreeSet::new();
while current_block_address != 0 {
if !seen_dl.insert(current_block_address) {
return Err(Error::LinkCycle {
address: current_block_address,
});
}
let byte_offset = current_block_address as usize;
// Read the block header
let block_header = BlockHeader::from_bytes(&mmap[byte_offset..byte_offset + 24])?;
match block_header.id.as_str() {
"##DT" | "##DV" => {
// Check if this is an empty block in an unfinalized file
// (block_len == 24 means header only, but data follows anyway)
let data_block = if self.is_unfinalized && block_header.length == 24 {
// Use unfinalized parsing - read until end of file
DataBlock::from_bytes_unfinalized(&mmap[byte_offset..])?
} else {
// Normal parsing
DataBlock::from_bytes(&mmap[byte_offset..])?
};
collected_blocks.push(data_block);
// No list to follow, we're done
current_block_address = 0;
}
"##DL" => {
// Fragmented list of data blocks
let data_list_block = DataListBlock::from_bytes(&mmap[byte_offset..])?;
// Parse each fragment in this list
for &fragment_address in &data_list_block.data_block_addrs {
if fragment_address == 0 {
continue;
}
let (frag_addr, _) =
HlBlock::skip_hierarchy_blocks(mmap, fragment_address)?;
let fragment_offset = u64_to_usize(frag_addr, "DL fragment address")?;
let fragment_block = DataBlock::from_bytes(&mmap[fragment_offset..])?;
collected_blocks.push(fragment_block);
}
// Move to the next DLBLOCK in the chain (0 = end)
current_block_address = data_list_block.next_dl_addr;
}
"##HL" => {
let len = u64_to_usize(block_header.length, "##HL")?;
current_block_address =
HlBlock::next_block_addr(&mmap[byte_offset..byte_offset + len])?;
}
unexpected_id => {
return Err(Error::BlockIDError {
actual: unexpected_id.to_string(),
expected: "##DT / ##DV / ##DL / ##HL".to_string(),
});
}
}
}
Ok(collected_blocks)
}
/// Collect all data blocks, decompressing DZ blocks if needed.
///
/// This method handles both regular DT/DV blocks and compressed DZ blocks.
/// For DZ blocks, the data is decompressed and stored as owned data.
///
/// # Arguments
/// * `mmap` - Memory mapped file containing the MDF data
///
/// # Returns
/// A vector of [`ResolvedDataBlock`] objects or an [`Error`] if parsing fails.
///
/// # Feature Requirements
/// - Without `compression` feature: Returns error on DZ blocks
/// - With `compression` feature: Decompresses DZ blocks transparently
pub fn resolved_data_blocks<'a>(&self, mmap: &'a [u8]) -> Result<Vec<ResolvedDataBlock<'a>>> {
let mut collected_blocks = Vec::new();
let mut current_block_address = self.block.data_block_addr;
// Guard against cyclic DL chains in corrupt files.
let mut seen_dl = alloc::collections::BTreeSet::new();
while current_block_address != 0 {
if !seen_dl.insert(current_block_address) {
return Err(Error::LinkCycle {
address: current_block_address,
});
}
let byte_offset = current_block_address as usize;
let block_header = BlockHeader::from_bytes(&mmap[byte_offset..byte_offset + 24])?;
match block_header.id.as_str() {
"##DT" | "##DV" => {
let data_block = if self.is_unfinalized && block_header.length == 24 {
DataBlock::from_bytes_unfinalized(&mmap[byte_offset..])?
} else {
DataBlock::from_bytes(&mmap[byte_offset..])?
};
collected_blocks.push(ResolvedDataBlock {
block_id: if block_header.id == "##DT" {
"##DT"
} else {
"##DV"
},
data: DataBlockData::Borrowed(data_block.data),
});
current_block_address = 0;
}
#[cfg(feature = "compression")]
"##DZ" => {
let dz_block = DzBlock::from_bytes(&mmap[byte_offset..])?;
let decompressed = dz_block.decompress()?;
collected_blocks.push(ResolvedDataBlock {
block_id: "##DT", // DZ decompresses to DT-equivalent data
data: DataBlockData::Owned(decompressed),
});
current_block_address = 0;
}
#[cfg(not(feature = "compression"))]
"##DZ" => {
return Err(Error::BlockSerializationError(
"DZ blocks require the 'compression' feature".to_string(),
));
}
"##DL" => {
let data_list_block = DataListBlock::from_bytes(&mmap[byte_offset..])?;
for &fragment_address in &data_list_block.data_block_addrs {
if fragment_address == 0 {
continue;
}
let (frag_addr, frag_header) =
HlBlock::skip_hierarchy_blocks(mmap, fragment_address)?;
let fragment_offset = u64_to_usize(frag_addr, "DL fragment address")?;
match frag_header.id.as_str() {
"##DT" | "##DV" => {
let fragment_block =
DataBlock::from_bytes(&mmap[fragment_offset..])?;
collected_blocks.push(ResolvedDataBlock {
block_id: if frag_header.id == "##DT" {
"##DT"
} else {
"##DV"
},
data: DataBlockData::Borrowed(fragment_block.data),
});
}
#[cfg(feature = "compression")]
"##DZ" => {
let dz_block = DzBlock::from_bytes(&mmap[fragment_offset..])?;
let decompressed = dz_block.decompress()?;
collected_blocks.push(ResolvedDataBlock {
block_id: "##DT",
data: DataBlockData::Owned(decompressed),
});
}
#[cfg(not(feature = "compression"))]
"##DZ" => {
return Err(Error::BlockSerializationError(
"DZ blocks require the 'compression' feature".to_string(),
));
}
other => {
return Err(Error::BlockIDError {
actual: other.to_string(),
expected: "##DT / ##DV / ##DZ".to_string(),
});
}
}
}
current_block_address = data_list_block.next_dl_addr;
}
"##HL" => {
let len = u64_to_usize(block_header.length, "##HL")?;
current_block_address =
HlBlock::next_block_addr(&mmap[byte_offset..byte_offset + len])?;
}
unexpected_id => {
return Err(Error::BlockIDError {
actual: unexpected_id.to_string(),
expected: "##DT / ##DV / ##DL / ##DZ / ##HL".to_string(),
});
}
}
}
Ok(collected_blocks)
}
}
#[cfg(test)]
mod hl_chain_tests {
//! `##HL` may appear in the `##DG` measurement-data chain before `##DL` / `##DT`.
//! See `tests/data/sample_with_hl.mf4` (same bytes as `sample_with_hl_in_data_chain_loads`).
use super::RawDataGroup;
use crate::blocks::{BlockParse, DataGroupBlock};
#[test]
fn data_blocks_skip_hl_before_dt_in_chain() {
const SAMPLE: &[u8] = include_bytes!("../../tests/data/sample_with_hl.mf4");
const DG_OFF: usize = 1400;
let dg = DataGroupBlock::from_bytes(&SAMPLE[DG_OFF..DG_OFF + 64]).expect("DG in fixture");
let group = RawDataGroup {
block: dg,
channel_groups: Vec::new(),
is_unfinalized: false,
};
let blocks = group
.data_blocks(SAMPLE)
.expect("reader should skip ##HL and collect DT blocks");
assert!(
!blocks.is_empty(),
"fixture contains measurement data after ##HL"
);
}
}