Skip to main content

mf4_rs/blocks/
data_block.rs

1use crate::blocks::common::BlockHeader;
2use crate::blocks::common::BlockParse;
3use crate::error::MdfError;
4
5#[derive(Debug)]
6pub struct DataBlock<'a> {
7    pub header: BlockHeader,
8    pub data: &'a [u8],
9}
10
11impl<'a> BlockParse<'a> for DataBlock<'a> {
12    const ID: &'static str = "##DT";
13    /// Parse a DTBLOCK or DVBLOCK from the given byte slice.
14    ///
15    /// Both `##DT` (record data) and `##DV` (sample data of a column-oriented
16    /// group) blocks share the same layout: a 24-byte header followed by raw
17    /// data. Any other block id is rejected.
18    ///
19    /// The slice must contain at least the number of bytes specified by the
20    /// block length in the header. Only a reference to the data portion is
21    /// stored to avoid unnecessary allocations.
22    fn from_bytes(bytes: &'a [u8]) -> Result<Self, MdfError> {
23
24        let header = BlockHeader::from_bytes(bytes)?;
25        if header.id != "##DT" && header.id != "##DV" {
26            return Err(MdfError::BlockIDError {
27                actual: header.id.clone(),
28                expected: "##DT / ##DV".to_string(),
29            });
30        }
31
32        let data_len = (header.block_len as usize).saturating_sub(24);
33        let expected_bytes = 24 + data_len;
34        if bytes.len() < expected_bytes {
35            return Err(MdfError::TooShortBuffer {
36                actual:   bytes.len(),
37                expected: expected_bytes,
38                file:     file!(),
39                line:     line!(),
40            });
41        }
42        let data = &bytes[24..24 + data_len];
43        Ok(Self { header, data })
44    }
45}
46impl<'a> DataBlock<'a> {
47    /// Iterate over raw records of fixed size.
48    /// If the data block contains padding at the end, it’s your caller’s responsibility to trim that.
49    ///
50    /// # Arguments
51    /// * `record_size` - Size in bytes of one record (including record ID)
52    ///
53    /// # Returns
54    /// An iterator yielding each raw record slice.
55    pub fn records(&self, record_size: usize) -> impl Iterator<Item = &'a [u8]> {
56        self.data.chunks_exact(record_size)
57    }
58}