Skip to main content

mf4_rs/blocks/
header_block.rs

1// src/blocks/header_block.rs
2use crate::blocks::common::BlockHeader;
3use crate::blocks::common::BlockParse;
4use byteorder::{ByteOrder, LittleEndian};
5
6use crate::error::MdfError;
7
8#[derive(Debug)]
9pub struct HeaderBlock {
10    pub header: BlockHeader,       // Common header from the first 24 bytes
11    pub first_dg_addr: u64,        // bytes[24..32]
12    pub file_history_addr: u64,    // bytes[32..40]
13    pub channel_tree_addr: u64,    // bytes[40..48]
14    pub first_attachment_addr: u64,// bytes[48..56]
15    pub first_event_addr: u64,     // bytes[56..64]
16    pub comment_addr: u64,         // bytes[64..72]
17    pub abs_time: u64,             // bytes[72..80]
18    pub tz_offset: i16,            // bytes[80..82]
19    pub daylight_save_time: i16,   // bytes[82..84]
20    pub time_flags: u8,            // byte[84]
21    pub time_quality: u8,          // byte[85]
22    pub flags: u8,                 // byte[86]
23    pub reserved1: u8,             // byte[87]
24    pub start_angle: u64,          // bytes[88..96]
25    pub start_distance: u64,       // bytes[96..104]
26}
27
28impl HeaderBlock {
29    /// Serializes the HeaderBlock to bytes according to MDF 4.1 specification.
30    ///
31    /// # Structure (104 bytes total):
32    /// - BlockHeader (24 bytes): Standard block header with id "##HD"
33    /// - Link section (48 bytes): Six 8-byte links to other blocks
34    ///   * first_dg_addr: Link to first Data Group block
35    ///   * file_history_addr: Link to file history block
36    ///   * channel_tree_addr: Link to channel hierarchy tree
37    ///   * first_attachment_addr: Link to first attachment block
38    ///   * first_event_addr: Link to first event block
39    ///   * comment_addr: Link to comment block
40    /// - Time section (16 bytes): Timestamp and timezone information
41    /// - Angle/Distance section (16 bytes): Start values for angle and distance
42    ///
43    /// # Returns
44    /// - `Ok(Vec<u8>)` containing the serialized header block
45    /// - `Err(MdfError)` if serialization fails
46    ///
47    /// # Important
48    /// - The header must have id="##HD" and block_len=104
49    /// - Links will typically be updated after all blocks are written
50    pub fn to_bytes(&self) -> Result<Vec<u8>, MdfError> {
51        // Validate the header before serializing
52        if self.header.id != "##HD" {
53            return Err(MdfError::BlockSerializationError(
54                format!("HeaderBlock must have ID '##HD', found '{}'", self.header.id)
55            ));
56        }
57        
58        if self.header.block_len != 104 {
59            return Err(MdfError::BlockSerializationError(
60                format!("HeaderBlock must have block_len=104, found {}", self.header.block_len)
61            ));
62        }
63        
64        // Create a buffer with exact capacity for efficiency
65        let mut buffer = Vec::with_capacity(104);
66        
67        // 1. Write the block header (24 bytes)
68        buffer.extend_from_slice(&self.header.to_bytes()?);
69        
70        // 2. Write the six link addresses (48 bytes total)
71        // Each is a u64 in little-endian format
72        buffer.extend_from_slice(&self.first_dg_addr.to_le_bytes());
73        buffer.extend_from_slice(&self.file_history_addr.to_le_bytes());
74        buffer.extend_from_slice(&self.channel_tree_addr.to_le_bytes());
75        buffer.extend_from_slice(&self.first_attachment_addr.to_le_bytes());
76        buffer.extend_from_slice(&self.first_event_addr.to_le_bytes());
77        buffer.extend_from_slice(&self.comment_addr.to_le_bytes());
78        
79        // 3. Write the time section (16 bytes)
80        buffer.extend_from_slice(&self.abs_time.to_le_bytes());           // 8 bytes - absolute time
81        buffer.extend_from_slice(&self.tz_offset.to_le_bytes());         // 2 bytes - timezone offset
82        buffer.extend_from_slice(&self.daylight_save_time.to_le_bytes()); // 2 bytes - DST offset
83        buffer.push(self.time_flags);                                     // 1 byte - time flags
84        buffer.push(self.time_quality);                                   // 1 byte - time quality
85        buffer.push(self.flags);                                          // 1 byte - general flags
86        buffer.push(self.reserved1);                                      // 1 byte - reserved
87        
88        // 4. Write the angle/distance section (16 bytes)
89        buffer.extend_from_slice(&self.start_angle.to_le_bytes());       // 8 bytes - start angle
90        buffer.extend_from_slice(&self.start_distance.to_le_bytes());    // 8 bytes - start distance
91        
92        // Verify the buffer is exactly 104 bytes
93        if buffer.len() != 104 {
94            return Err(MdfError::BlockSerializationError(
95                format!("HeaderBlock must be exactly 104 bytes, got {}", buffer.len())
96            ));
97        }
98        
99        // Ensure 8-byte alignment (should always be true since 104 is divisible by 8)
100        debug_assert_eq!(buffer.len() % 8, 0, "HeaderBlock size is not 8-byte aligned");
101        
102        Ok(buffer)
103    }
104}
105
106impl BlockParse<'_> for HeaderBlock {
107    const ID: &'static str = "##HD";
108    /// Creates a HeaderBlock from a 104-byte slice.
109    fn from_bytes(bytes: &[u8]) -> Result<Self, MdfError> {
110
111        let header = Self::parse_header(bytes)?;
112
113        let expected_bytes = 104;
114        if bytes.len() < expected_bytes {
115            return Err(MdfError::TooShortBuffer {
116                actual:   bytes.len(),
117                expected: expected_bytes,
118                file:     file!(),
119                line:     line!(),
120            });
121        }
122        
123        Ok(Self {
124            header,
125            first_dg_addr: LittleEndian::read_u64(&bytes[24..32]),
126            file_history_addr: LittleEndian::read_u64(&bytes[32..40]),
127            channel_tree_addr: LittleEndian::read_u64(&bytes[40..48]),
128            first_attachment_addr: LittleEndian::read_u64(&bytes[48..56]),
129            first_event_addr: LittleEndian::read_u64(&bytes[56..64]),
130            comment_addr: LittleEndian::read_u64(&bytes[64..72]),
131            abs_time: LittleEndian::read_u64(&bytes[72..80]),
132            tz_offset: LittleEndian::read_i16(&bytes[80..82]),
133            daylight_save_time: LittleEndian::read_i16(&bytes[82..84]),
134            time_flags: bytes[84],
135            time_quality: bytes[85],
136            flags: bytes[86],
137            reserved1: bytes[87],
138            start_angle: LittleEndian::read_u64(&bytes[88..96]),
139            start_distance: LittleEndian::read_u64(&bytes[96..104]),
140        })
141    }
142}
143
144impl Default for HeaderBlock {
145    fn default() -> Self {
146        let header = BlockHeader {
147            id: String::from("##HD"),
148            reserved0: 0,
149            block_len: 104,
150            links_nr: 6,
151        };
152
153        HeaderBlock {
154            header,
155            first_dg_addr: 0,
156            file_history_addr: 0,
157            channel_tree_addr: 0,
158            first_attachment_addr: 0,
159            first_event_addr: 0,
160            comment_addr: 0,
161            abs_time: 0,
162            tz_offset: 0,
163            daylight_save_time: 0,
164            time_flags: 0,
165            time_quality: 0,
166            flags: 0,
167            reserved1: 0,
168            start_angle: 0,
169            start_distance: 0,
170        }
171    }
172}