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
// blocks/common.rs
use byteorder::{ByteOrder, LittleEndian};
use crate::blocks::text_block::TextBlock;
use crate::blocks::metadata_block::MetadataBlock;
use crate::error::MdfError;
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct BlockHeader {
pub id: String, // 4-byte string
pub reserved0: u32, // 4 bytes
pub block_len: u64, // 8 bytes
pub links_nr: u64, // 8 bytes
}
impl Default for BlockHeader {
/// Returns a BlockHeader with id 'UNSET' and block_len 0 as a placeholder.
/// This is not a valid MDF block header and should be replaced before writing.
fn default() -> Self {
BlockHeader {
id: String::from("UNSET"), // Placeholder, must be set by user
reserved0: 0,
block_len: 0, // Placeholder, must be set by user
links_nr: 0,
}
}
}
impl BlockHeader {
/// Serializes the BlockHeader to bytes according to MDF 4.1 specification.
///
/// The BlockHeader is always 24 bytes and consists of:
/// - id: 4 bytes (ASCII characters, must be exactly 4 bytes)
/// - reserved0: 4 bytes (always 0)
/// - block_len: 8 bytes (total length of the block including this header)
/// - links_nr: 8 bytes (number of links in this block)
///
/// # Returns
/// - `Ok(Vec<u8>)` containing the serialized block header
/// - `Err(MdfError)` if serialization fails
pub fn to_bytes(&self) -> Result<Vec<u8>, MdfError> {
// Create a buffer with exactly 24 bytes capacity
let mut buffer = Vec::with_capacity(24);
// 1. Write the ID field (4 bytes)
// The ID must be exactly 4 bytes - truncate or pad as needed
let id_bytes = self.id.as_bytes();
let mut id_field = [0u8; 4]; // Initialize with zeros for padding
// Copy either all bytes or first 4 bytes of ID
let id_len = std::cmp::min(id_bytes.len(), 4);
id_field[..id_len].copy_from_slice(&id_bytes[..id_len]);
buffer.extend_from_slice(&id_field);
// 2. Write reserved0 field (4 bytes)
buffer.extend_from_slice(&self.reserved0.to_le_bytes());
// 3. Write block_len field (8 bytes)
buffer.extend_from_slice(&self.block_len.to_le_bytes());
// 4. Write links_nr field (8 bytes)
buffer.extend_from_slice(&self.links_nr.to_le_bytes());
// Verify buffer is exactly 24 bytes
if buffer.len() != 24 {
return Err(MdfError::BlockSerializationError(
format!("BlockHeader must be exactly 24 bytes, got {}", buffer.len())
));
}
Ok(buffer)
}
/// Parse a block header from the first 24 bytes of `bytes`.
///
/// # Arguments
/// * `bytes` - Slice containing at least 24 bytes from the MDF file.
///
/// # Returns
/// A [`BlockHeader`] on success or [`MdfError::TooShortBuffer`] when the
/// slice is smaller than 24 bytes.
pub fn from_bytes(bytes: &[u8]) -> Result<Self, MdfError> {
let expected_bytes = 24;
if bytes.len() < expected_bytes {
return Err(MdfError::TooShortBuffer {
actual: bytes.len(),
expected: expected_bytes,
file: file!(),
line: line!(),
});
}
Ok(Self {
id: String::from_utf8_lossy(&bytes[0..4]).to_string(),
reserved0: LittleEndian::read_u32(&bytes[4..8]),
block_len: LittleEndian::read_u64(&bytes[8..16]),
links_nr: LittleEndian::read_u64(&bytes[16..24]),
})
}
}
pub trait BlockParse<'a>: Sized {
const ID: &'static str;
fn parse_header(bytes: &[u8]) -> Result<BlockHeader, MdfError> {
let header = BlockHeader::from_bytes(&bytes[0..24])?;
if header.id != Self::ID {
return Err(MdfError::BlockIDError {
actual: header.id.clone(),
expected: Self::ID.to_string(),
});
}
Ok(header)
}
fn from_bytes(bytes: &'a [u8]) -> Result<Self, MdfError>;
}
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub enum DataType {
UnsignedIntegerLE,
UnsignedIntegerBE,
SignedIntegerLE,
SignedIntegerBE,
FloatLE,
FloatBE,
StringLatin1,
StringUtf8,
StringUtf16LE,
StringUtf16BE,
ByteArray,
MimeSample,
MimeStream,
CanOpenDate,
CanOpenTime,
ComplexLE,
ComplexBE,
Unknown(()),
}
impl DataType {
/// Converts the DataType enum value to its corresponding u8 representation
/// according to the MDF 4.1 specification.
///
/// # Returns
/// The u8 value corresponding to this DataType
///
/// # Note
/// For ComplexLE, ComplexBE, and Unknown variants, we use values that match
/// the MDF 4.1 specification (15, 16) or a default (0) for Unknown.
pub fn to_u8(&self) -> u8 {
match self {
DataType::UnsignedIntegerLE => 0,
DataType::UnsignedIntegerBE => 1,
DataType::SignedIntegerLE => 2,
DataType::SignedIntegerBE => 3,
DataType::FloatLE => 4,
DataType::FloatBE => 5,
DataType::StringLatin1 => 6,
DataType::StringUtf8 => 7,
DataType::StringUtf16LE => 8,
DataType::StringUtf16BE => 9,
DataType::ByteArray => 10,
DataType::MimeSample => 11,
DataType::MimeStream => 12,
DataType::CanOpenDate => 13,
DataType::CanOpenTime => 14,
DataType::ComplexLE => 15, // Complex numbers, little-endian
DataType::ComplexBE => 16, // Complex numbers, big-endian
DataType::Unknown(_) => 0, // Default to 0 for unknown types
}
}
/// Convert a numeric representation to the corresponding `DataType`.
/// Values outside the known range yield `DataType::Unknown`.
pub fn from_u8(value: u8) -> Self {
match value {
0 => DataType::UnsignedIntegerLE,
1 => DataType::UnsignedIntegerBE,
2 => DataType::SignedIntegerLE,
3 => DataType::SignedIntegerBE,
4 => DataType::FloatLE,
5 => DataType::FloatBE,
6 => DataType::StringLatin1,
7 => DataType::StringUtf8,
8 => DataType::StringUtf16LE,
9 => DataType::StringUtf16BE,
10 => DataType::ByteArray,
11 => DataType::MimeSample,
12 => DataType::MimeStream,
13 => DataType::CanOpenDate,
14 => DataType::CanOpenTime,
15 => DataType::ComplexLE,
16 => DataType::ComplexBE,
_ => DataType::Unknown(()),
}
}
/// Returns a typical bit width for this data type.
/// This is used when creating channels without an explicit bit count.
pub fn default_bits(&self) -> u32 {
match self {
DataType::UnsignedIntegerLE
| DataType::UnsignedIntegerBE
| DataType::SignedIntegerLE
| DataType::SignedIntegerBE => 32,
DataType::FloatLE | DataType::FloatBE => 32,
DataType::StringLatin1
| DataType::StringUtf8
| DataType::StringUtf16LE
| DataType::StringUtf16BE
| DataType::ByteArray
| DataType::MimeSample
| DataType::MimeStream => 8,
DataType::CanOpenDate | DataType::CanOpenTime => 64,
DataType::ComplexLE | DataType::ComplexBE => 64,
DataType::Unknown(_) => 8,
}
}
}
/// Read a text or metadata block at `address` and return its contents.
///
/// # Arguments
/// * `mmap` - The full memory mapped MDF file.
/// * `address` - Offset of the target block; use `0` for no block.
///
/// # Returns
/// The block's string contents if present or `Ok(None)` if `address` is zero or
/// the block type is not text or metadata.
pub fn read_string_block(mmap: &[u8], address: u64) -> Result<Option<String>, MdfError> {
if address == 0 {
return Ok(None);
}
let offset = address as usize;
let header = BlockHeader::from_bytes(&mmap[offset..offset + 24])?;
match header.id.as_str() {
"##TX" => Ok(Some(TextBlock::from_bytes(&mmap[offset..])?.text)),
"##MD" => Ok(Some(MetadataBlock::from_bytes(&mmap[offset..])?.xml)),
_ => Ok(None),
}
}