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
use crate::blocks::common::BlockHeader;
use crate::blocks::common::BlockParse;
use crate::error::MdfError;
#[derive(Debug)]
pub struct TextBlock {
pub header: BlockHeader,
pub text: String,
}
impl BlockParse<'_> for TextBlock {
const ID: &'static str = "##TX";
fn from_bytes(bytes: &[u8]) -> Result<Self, MdfError> {
let header = Self::parse_header(bytes)?;
let data_len = (header.block_len as usize).saturating_sub(24);
let expected_bytes = 24 + data_len;
if bytes.len() < expected_bytes {
return Err(MdfError::TooShortBuffer {
actual: bytes.len(),
expected: expected_bytes,
file: file!(),
line: line!(),
});
}
let data = &bytes[24..24 + data_len];
// The stored text is a NUL-terminated C string: everything from the
// first NUL byte onwards (terminator + alignment padding) is ignored.
// Do NOT strip leading NULs — that would alter the decoded name.
let terminated = match data.iter().position(|&b| b == 0) {
Some(pos) => &data[..pos],
None => data,
};
let text = String::from_utf8_lossy(terminated).to_string();
Ok(Self { header, text })
}
}
impl TextBlock {
/// Creates a new TextBlock with the provided text content.
/// This will automatically calculate the correct block size based on the text length.
///
/// # Arguments
/// * `text` - The text content to store in this block
///
/// # Returns
/// A new TextBlock with properly initialized header and text content
pub fn new(text: &str) -> Self {
// Calculate required block size: 24 bytes for header + text length
// The block size must be a multiple of 8 bytes for alignment
let text_bytes = text.as_bytes();
let needs_null = text_bytes.is_empty() || *text_bytes.last().unwrap() != 0;
let text_size = text_bytes.len() + if needs_null { 1 } else { 0 };
let unpadded_size = 24 + text_size;
let padding_bytes = (8 - (unpadded_size % 8)) % 8;
let block_len = unpadded_size + padding_bytes;
// Create header with proper ID, size, and link count (0 for TextBlock)
let header = BlockHeader {
id: String::from("##TX"),
reserved0: 0,
block_len: block_len as u64,
links_nr: 0, // TextBlock has no links
};
TextBlock {
header,
text: text.to_string(),
}
}
/// Creates an empty TextBlock with a minimal valid size.
///
/// # Returns
/// A new TextBlock with an empty text string
pub fn new_empty() -> Self {
Self::new("")
}
/// Serializes the TextBlock to bytes according to MDF 4.1 specification.
///
/// TextBlock structure consists of:
/// - BlockHeader (24 bytes)
/// - Text content (variable length, null-terminated)
/// - Optional padding to maintain 8-byte alignment
///
/// # Returns
/// - `Ok(Vec<u8>)` containing the serialized text block
/// - `Err(MdfError)` if serialization fails
pub fn to_bytes(&self) -> Result<Vec<u8>, MdfError> {
// Validate the block ID
if self.header.id != "##TX" {
return Err(MdfError::BlockSerializationError(
format!("TextBlock must have ID '##TX', found '{}'", self.header.id)
));
}
// Get the text as bytes
let text_bytes = self.text.as_bytes();
let needs_null = text_bytes.is_empty() || *text_bytes.last().unwrap() != 0;
let text_size = text_bytes.len() + if needs_null { 1 } else { 0 };
// Calculate total size including header, text (with null) and padding
let unpadded_size = 24 + text_size;
let padding_bytes = (8 - (unpadded_size % 8)) % 8;
let total_size = unpadded_size + padding_bytes;
// Verify block_len in header matches calculated size
if self.header.block_len as usize != total_size {
return Err(MdfError::BlockSerializationError(
format!("TextBlock header.block_len ({}) does not match calculated size ({})",
self.header.block_len, total_size)
));
}
// Create a buffer with exact capacity
let mut buffer = Vec::with_capacity(total_size);
// 1. Write the header (24 bytes)
buffer.extend_from_slice(&self.header.to_bytes()?);
// 2. Write the text bytes
buffer.extend_from_slice(text_bytes);
// 3. Add null terminator if not already present
if needs_null {
buffer.push(0);
}
// 4. Add padding to maintain 8-byte alignment
let current_size = buffer.len();
let remaining_padding = total_size - current_size;
if remaining_padding > 0 {
buffer.extend(vec![0u8; remaining_padding]);
}
// Verify the final size is correct and 8-byte aligned
if buffer.len() != total_size {
return Err(MdfError::BlockSerializationError(
format!("TextBlock has incorrect final size: expected {}, got {}",
total_size, buffer.len())
));
}
debug_assert_eq!(buffer.len() % 8, 0, "TextBlock size is not 8-byte aligned");
Ok(buffer)
}
}
impl Default for TextBlock {
fn default() -> Self {
Self::new("")
}
}