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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
use std::error::Error;
use std::fmt;
use std::iter::FusedIterator;
use std::str;
use crate::checksum::checksum;
use crate::record::{types, Record};
#[derive(PartialEq, Eq, Clone, Copy, Debug, Hash)]
pub enum ReaderError {
MissingStartCode,
RecordTooShort,
RecordTooLong,
RecordNotEvenLength,
ContainsInvalidCharacters,
ChecksumMismatch(u8, u8),
PayloadLengthMismatch,
UnsupportedRecordType(u8),
InvalidLengthForType,
}
impl Error for ReaderError {}
impl fmt::Display for ReaderError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
ReaderError::MissingStartCode => write!(f, "missing start code ':'"),
ReaderError::RecordTooShort => write!(f, "too short"),
ReaderError::RecordTooLong => write!(f, "too long"),
ReaderError::RecordNotEvenLength => {
write!(f, "record does not contain a whole number of bytes")
}
ReaderError::ContainsInvalidCharacters => {
write!(f, "invalid characters encountered in record")
}
ReaderError::ChecksumMismatch(found, expecting) => write!(
f,
"invalid checksum '{:02X}', expecting '{:02X}'",
found, expecting,
),
ReaderError::PayloadLengthMismatch => {
write!(f, "payload length does not match record header")
}
ReaderError::UnsupportedRecordType(record_type) => {
write!(f, "unsupported IHEX record type '{:02X}'", record_type)
}
ReaderError::InvalidLengthForType => {
write!(f, "payload length invalid for record type")
}
}
}
}
mod char_counts {
pub const SMALLEST_RECORD_EXCLUDING_START_CODE: usize = (1 + 2 + 1 + 1) * 2;
pub const LARGEST_RECORD_EXCLUDING_START_CODE: usize = (1 + 2 + 1 + 255 + 1) * 2;
}
mod payload_sizes {
pub const END_OF_FILE: usize = 0;
pub const EXTENDED_SEGMENT_ADDRESS: usize = 2;
pub const START_SEGMENT_ADDRESS: usize = 4;
pub const EXTENDED_LINEAR_ADDRESS: usize = 2;
pub const START_LINEAR_ADDRESS: usize = 4;
}
impl Record {
pub fn from_record_string(string: &str) -> Result<Self, ReaderError> {
if let Some(':') = string.chars().next() {
} else {
return Err(ReaderError::MissingStartCode);
}
let data_portion = &string[1..];
let data_poriton_length = data_portion.chars().count();
if !data_portion
.chars()
.all(|character| character.is_ascii_hexdigit())
{
return Err(ReaderError::ContainsInvalidCharacters);
}
if data_poriton_length < char_counts::SMALLEST_RECORD_EXCLUDING_START_CODE {
return Err(ReaderError::RecordTooShort);
} else if data_poriton_length > char_counts::LARGEST_RECORD_EXCLUDING_START_CODE {
return Err(ReaderError::RecordTooLong);
} else if (data_poriton_length % 2) != 0 {
return Err(ReaderError::RecordNotEvenLength);
}
let mut data_bytes = data_portion
.as_bytes()
.chunks(2)
.map(|chunk| str::from_utf8(chunk).unwrap())
.map(|byte_str| u8::from_str_radix(byte_str, 16).unwrap())
.collect::<Vec<u8>>();
let expected_checksum = data_bytes.pop().unwrap();
let validated_region_bytes = data_bytes.as_slice();
let checksum = checksum(validated_region_bytes);
if checksum != expected_checksum {
return Err(ReaderError::ChecksumMismatch(checksum, expected_checksum));
}
let length = validated_region_bytes[0];
let address_hi = (validated_region_bytes[1] as u16) << 8;
let address_lo = validated_region_bytes[2] as u16;
let address = address_hi | address_lo;
let record_type = validated_region_bytes[3];
let payload_bytes = &validated_region_bytes[4..];
if payload_bytes.len() != (length as usize) {
return Err(ReaderError::PayloadLengthMismatch);
}
match record_type {
types::DATA => {
Ok(Record::Data {
offset: address,
value: Vec::from(payload_bytes),
})
}
types::END_OF_FILE => {
match payload_bytes.len() {
payload_sizes::END_OF_FILE => Ok(Record::EndOfFile),
_ => Err(ReaderError::InvalidLengthForType),
}
}
types::EXTENDED_SEGMENT_ADDRESS => {
match payload_bytes.len() {
payload_sizes::EXTENDED_SEGMENT_ADDRESS => {
let address_hi = (payload_bytes[0] as u16) << 8;
let address_lo = payload_bytes[1] as u16;
let address = address_hi | address_lo;
Ok(Record::ExtendedSegmentAddress(address))
}
_ => Err(ReaderError::InvalidLengthForType),
}
}
types::START_SEGMENT_ADDRESS => {
match payload_bytes.len() {
payload_sizes::START_SEGMENT_ADDRESS => {
let cs_hi = (payload_bytes[0] as u16) << 8;
let cs_lo = payload_bytes[1] as u16;
let ip_hi = (payload_bytes[2] as u16) << 8;
let ip_lo = payload_bytes[3] as u16;
let cs = cs_hi | cs_lo;
let ip = ip_hi | ip_lo;
Ok(Record::StartSegmentAddress { cs, ip })
}
_ => Err(ReaderError::InvalidLengthForType),
}
}
types::EXTENDED_LINEAR_ADDRESS => {
match payload_bytes.len() {
payload_sizes::EXTENDED_LINEAR_ADDRESS => {
let ela_hi = (payload_bytes[0] as u16) << 8;
let ela_lo = payload_bytes[1] as u16;
let ela = ela_hi | ela_lo;
Ok(Record::ExtendedLinearAddress(ela))
}
_ => Err(ReaderError::InvalidLengthForType),
}
}
types::START_LINEAR_ADDRESS => {
match payload_bytes.len() {
payload_sizes::START_LINEAR_ADDRESS => {
let sla_4 = (payload_bytes[0] as u32) << 24;
let sla_3 = (payload_bytes[1] as u32) << 16;
let sla_2 = (payload_bytes[2] as u32) << 8;
let sla_1 = payload_bytes[3] as u32;
let sla = sla_4 | sla_3 | sla_2 | sla_1;
Ok(Record::StartLinearAddress(sla))
}
_ => Err(ReaderError::InvalidLengthForType),
}
}
_ => Err(ReaderError::UnsupportedRecordType(record_type)),
}
}
}
impl str::FromStr for Record {
type Err = ReaderError;
fn from_str(input: &str) -> Result<Self, Self::Err> {
Record::from_record_string(input)
}
}
#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)]
pub struct ReaderOptions {
pub stop_after_first_error: bool,
pub stop_after_eof: bool,
}
impl Default for ReaderOptions {
fn default() -> Self {
ReaderOptions {
stop_after_first_error: true,
stop_after_eof: true,
}
}
}
pub struct Reader<'a> {
line_iterator: str::Lines<'a>,
finished: bool,
options: ReaderOptions,
}
impl<'a> Reader<'a> {
pub fn new_with_options(string: &'a str, options: ReaderOptions) -> Self {
Reader {
line_iterator: string.lines(),
finished: false,
options,
}
}
pub fn new(string: &'a str) -> Self {
Reader::new_with_options(string, Default::default())
}
fn next_record(&mut self) -> Option<&'a str> {
let mut result = None;
while let Some(line) = self.line_iterator.next() {
if !line.is_empty() {
result = Some(line);
break;
}
}
result
}
}
impl<'a> Iterator for Reader<'a> {
type Item = Result<Record, ReaderError>;
fn next(&mut self) -> Option<Self::Item> {
if self.finished {
return None;
}
match self.next_record() {
None => {
self.finished = true;
None
}
Some(line) => {
let parse_result = str::parse::<Record>(line);
if parse_result.is_err() && self.options.stop_after_first_error {
self.finished = true;
}
if let Ok(Record::EndOfFile) = parse_result {
if self.options.stop_after_eof {
self.finished = true;
}
}
Some(parse_result)
}
}
}
}
impl<'a> FusedIterator for Reader<'a> {}