bin_file 0.1.4

Mangling of various file formats that conveys binary information (Motorola S-Record, Intel HEX, TI-TXT and binary files).
Documentation
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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
//
// Copyright 2016 ihex Developers
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed except according to those terms.
//
// Changes Copyright 2023 Robert Ernst

use core::fmt;
use std::fmt::Write;
use std::str;

use ansic::ansi;

use crate::checksums::crc_ihex;
use crate::error::Error;
use crate::Record;

const R: &str = ansi!(reset);
const GREEN: &str = ansi!(green);
const BLUE: &str = ansi!(blue);
const RED: &str = ansi!(red);
const CYAN: &str = ansi!(cyan);
const YELLOW: &str = ansi!(yellow);
const BRIGHT_CYAN: &str = ansi!(br.cyan); // 96
const BRIGHT_MAGENTA: &str = ansi!(br.magenta); // 95
const BRIGHT_GREEN: &str = ansi!(br.green); // 92

mod char_counts {
    /// The smallest record (excluding start code) is Byte Count + Address + Record Type + Checksum.
    pub const SMALLEST_RECORD_EXCLUDING_START_CODE: usize = (1 + 2 + 1 + 1) * 2;
    /// The smallest record (excluding start code) {Smallest} + a 255 byte payload region.
    pub const LARGEST_RECORD_EXCLUDING_START_CODE: usize = (1 + 2 + 1 + 255 + 1) * 2;
}

mod payload_sizes {
    /// An EoF record has no payload.
    pub const END_OF_FILE: usize = 0;
    /// An Extended Segment Address has a 16-bit payload.
    pub const EXTENDED_SEGMENT_ADDRESS: usize = 2;
    /// An Start Segment Address has two 16-bit payloads.
    pub const START_SEGMENT_ADDRESS: usize = 4;
    /// An Extended Linear Address has a 16-bit payload.
    pub const EXTENDED_LINEAR_ADDRESS: usize = 2;
    /// An Start Linear Address has a 32-bit payload.
    pub const START_LINEAR_ADDRESS: usize = 4;
}

/// This data structure holds a single line from a Intel Hex File.
///
/// [wikipedia](https://en.wikipedia.org/wiki/Intel_HEX)
#[derive(PartialEq, Eq, Debug, Clone, Hash)]
pub enum IHexRecord {
    /// Specifies a 16-bit offset address and up to 255 bytes of data.
    /// Availability: I8HEX, I16HEX and I32HEX.
    Data {
        /// The offset of the data record in memory.
        offset: u16,
        /// Up to 255 bytes of data to be written to memory.
        value: Vec<u8>,
    },

    /// Indicates the end of the object file. Must occur exactly once per file, at the end.
    /// Availability: I8HEX, I16HEX and I32HEX.
    EndOfFile,

    /// Specifies bits 4-19 of the Segment Base Address (SBA) to address up to 1MiB.
    /// Availability: I16HEX.
    ExtendedSegmentAddress(u16),

    /// Specifies the 20-bit segment address.
    /// Availability: I16HEX.
    StartSegmentAddress(u32),

    /// Specifies the upper 16 bits of a 32-bit linear address.
    /// The lower 16 bits are derived from the Data record load offset.
    /// Availability: I32HEX.
    ExtendedLinearAddress(u16),

    /// Specifies the execution start address for the object file.
    /// This is the 32-bit linear address for register EIP.
    /// Availability: I32HEX.
    StartLinearAddress(u32),
}

impl IHexRecord {
    /// The record type specifier corresponding to the receiver.
    fn record_type(&self) -> u8 {
        match self {
            IHexRecord::Data { .. } => types::DATA,
            IHexRecord::EndOfFile => types::END_OF_FILE,
            IHexRecord::ExtendedSegmentAddress(..) => types::EXTENDED_SEGMENT_ADDRESS,
            IHexRecord::StartSegmentAddress { .. } => types::START_SEGMENT_ADDRESS,
            IHexRecord::ExtendedLinearAddress(..) => types::EXTENDED_LINEAR_ADDRESS,
            IHexRecord::StartLinearAddress(..) => types::START_LINEAR_ADDRESS,
        }
    }
}

impl Record for IHexRecord {
    fn to_record_string(&self) -> Result<String, Error> {
        match self {
            IHexRecord::Data { offset, value } => format_record(self.record_type(), *offset, value),

            IHexRecord::EndOfFile => format_record(self.record_type(), 0x0000, []),

            IHexRecord::ExtendedSegmentAddress(segment_address) => {
                format_record(self.record_type(), 0x0000, segment_address.to_be_bytes())
            }

            IHexRecord::StartSegmentAddress(address) => {
                format_record(self.record_type(), 0x0000, address.to_be_bytes())
            }

            IHexRecord::ExtendedLinearAddress(linear_address) => {
                format_record(self.record_type(), 0x0000, linear_address.to_be_bytes())
            }

            IHexRecord::StartLinearAddress(address) => {
                format_record(self.record_type(), 0x0000, address.to_be_bytes())
            }
        }
    }

    fn to_pretty_record_string(&self) -> Result<String, Error> {
        let record_string = self.to_record_string()?;
        let (type_str, type_txt) = match self {
            IHexRecord::Data { .. } => (format!("{GREEN}{}{R}", &record_string[7..9]), " (data)"),
            IHexRecord::EndOfFile => (
                format!("{BRIGHT_CYAN}{}{R}", &record_string[7..9]),
                " (end of file)",
            ),
            IHexRecord::ExtendedSegmentAddress(_) => (
                format!("{BLUE}{}{R}", &record_string[7..9]),
                " (extended segment address)",
            ),
            IHexRecord::StartSegmentAddress(_) => (
                format!("{BRIGHT_GREEN}{}{R}", &record_string[7..9]),
                " (start segment address)",
            ),
            IHexRecord::ExtendedLinearAddress(_) => (
                format!("{BRIGHT_CYAN}{}{R}", &record_string[7..9]),
                " (extended linear address)",
            ),
            IHexRecord::StartLinearAddress(_) => (
                format!("{BRIGHT_GREEN}{}{R}", &record_string[7..9]),
                " (start linear address)",
            ),
        };
        Ok(format!(
            "{RED}{}{R}{BRIGHT_MAGENTA}{}{R}{YELLOW}{}{R}{}{}{CYAN}{}{R}{}",
            &record_string[..1],
            &record_string[1..3],
            &record_string[3..7],
            type_str,
            &record_string[9..record_string.len() - 2],
            &record_string[record_string.len() - 2..],
            type_txt
        ))
    }

    fn from_record_string<S>(record_string: S) -> Result<Self, Error>
    where
        S: AsRef<str>,
    {
        let string = record_string.as_ref().trim();
        if let Some(':') = string.chars().next() {
        } else {
            return Err(Error::MissingStartCode);
        }

        let data_portion = &string[1..];
        let data_portion_length = data_portion.chars().count();

        // Validate all characters are hexadecimal before checking the digit counts for more accurate errors.
        if !data_portion
            .chars()
            .all(|character| character.is_ascii_hexdigit())
        {
            return Err(Error::ContainsInvalidCharacters);
        }

        // Basic sanity-checking the input record string.
        if data_portion_length < char_counts::SMALLEST_RECORD_EXCLUDING_START_CODE {
            return Err(Error::RecordTooShort);
        } else if data_portion_length > char_counts::LARGEST_RECORD_EXCLUDING_START_CODE {
            return Err(Error::RecordTooLong);
        } else if (data_portion_length % 2) != 0 {
            return Err(Error::RecordNotEvenLength);
        }

        // Convert the character stream to bytes.
        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>>();

        // Compute the checksum.
        let expected_checksum = data_bytes.pop().unwrap();
        let validated_region_bytes = data_bytes.as_slice();
        let checksum = crc_ihex(validated_region_bytes);

        // The read is failed if the checksum does not match.
        if checksum != expected_checksum {
            return Err(Error::ChecksumMismatch(checksum, expected_checksum));
        }

        // Decode header values.
        let length = validated_region_bytes[0];
        let address = u16::from_be_bytes([validated_region_bytes[1], validated_region_bytes[2]]);
        let record_type = validated_region_bytes[3];
        let payload_bytes = &validated_region_bytes[4..];

        // Validate the length of the record matches what was specified in the header.
        if payload_bytes.len() != (length as usize) {
            return Err(Error::PayloadLengthMismatch);
        }

        match record_type {
            types::DATA => {
                // A Data record consists of an address and payload bytes.
                Ok(IHexRecord::Data {
                    offset: address,
                    value: Vec::from(payload_bytes),
                })
            }

            types::END_OF_FILE => {
                // An EoF record has no payload.
                match payload_bytes.len() {
                    payload_sizes::END_OF_FILE => Ok(IHexRecord::EndOfFile),

                    _ => Err(Error::InvalidLengthForType),
                }
            }

            types::EXTENDED_SEGMENT_ADDRESS => {
                match payload_bytes.len() {
                    payload_sizes::EXTENDED_SEGMENT_ADDRESS => {
                        // The 16-bit extended segment address is encoded big-endian.
                        let address: u16 = u16::from_be_bytes(payload_bytes.try_into().unwrap());
                        Ok(IHexRecord::ExtendedSegmentAddress(address))
                    }
                    _ => Err(Error::InvalidLengthForType),
                }
            }

            types::START_SEGMENT_ADDRESS => match payload_bytes.len() {
                payload_sizes::START_SEGMENT_ADDRESS => {
                    let address: u32 = u32::from_be_bytes(payload_bytes.try_into().unwrap());
                    Ok(IHexRecord::StartSegmentAddress(address))
                }
                _ => Err(Error::InvalidLengthForType),
            },

            types::EXTENDED_LINEAR_ADDRESS => {
                match payload_bytes.len() {
                    payload_sizes::EXTENDED_LINEAR_ADDRESS => {
                        // The upper 16 bits of the linear address are encoded as a 16-bit big-endian integer.
                        let ela: u16 = u16::from_be_bytes(payload_bytes.try_into().unwrap());
                        Ok(IHexRecord::ExtendedLinearAddress(ela))
                    }
                    _ => Err(Error::InvalidLengthForType),
                }
            }

            types::START_LINEAR_ADDRESS => {
                match payload_bytes.len() {
                    payload_sizes::START_LINEAR_ADDRESS => {
                        // The 32-bit value loaded into EIP is encoded as a 32-bit big-endian integer.
                        let sla: u32 = u32::from_be_bytes(payload_bytes.try_into().unwrap());
                        Ok(IHexRecord::StartLinearAddress(sla))
                    }

                    _ => Err(Error::InvalidLengthForType),
                }
            }

            _ => Err(Error::UnsupportedRecordType {
                record: string.into(),
                record_type,
            }),
        }
    }
}

impl str::FromStr for IHexRecord {
    type Err = Error;
    fn from_str(input: &str) -> Result<Self, Self::Err> {
        IHexRecord::from_record_string(input)
    }
}

/// The Record types as specified by the specification.
///
/// [wikipedia](https://en.wikipedia.org/wiki/Intel_HEX)
mod types {
    /// Type specifier for a Data record.
    pub const DATA: u8 = 0x00;
    /// Type specifier for an End-Of-File record.
    pub const END_OF_FILE: u8 = 0x01;
    /// Type specifier for an Extended Segment Address record.
    pub const EXTENDED_SEGMENT_ADDRESS: u8 = 0x02;
    /// Type specifier for a Start Segment Address record.
    pub const START_SEGMENT_ADDRESS: u8 = 0x03;
    /// Type specifier for an Extended Linear Address record.
    pub const EXTENDED_LINEAR_ADDRESS: u8 = 0x04;
    /// Type specifier for a Start Linear Address record.
    pub const START_LINEAR_ADDRESS: u8 = 0x05;
}

impl fmt::Display for IHexRecord {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            IHexRecord::Data { offset, value } => {
                write!(f, "Data Record: Offset:{}, value: {:X?}", offset, value)
            }
            IHexRecord::EndOfFile => {
                write!(f, "EndOfFile Record")
            }
            IHexRecord::ExtendedSegmentAddress(address) => {
                write!(f, "Extended Segment Address Record: Address: {}", address)
            }
            IHexRecord::StartSegmentAddress(address) => {
                write!(f, "Start Segment Address Record: Address: {}", address)
            }
            IHexRecord::ExtendedLinearAddress(address) => {
                write!(f, "Extended Linear Address Record: Address: {}", address)
            }
            IHexRecord::StartLinearAddress(address) => {
                write!(f, "Start Linear Address Record: Address: {}", address)
            }
        }
    }
}

/// IHEX records all contain the following fields:
/// `+-----+------------+--------------+----------+------------+-------------+`
/// `| ':' | Length: u8 | Address: u16 | Type: u8 | Data: [u8] | Checkum: u8 |`
/// `+-----+------------+--------------+----------+------------+-------------+`
/// Any multi-byte values are represented big endian.
/// Note that this method will fail if a data record is more than 255 bytes long.
/// This method returns a formatted IHEX record on success with the specified
/// `record_type`, `address` and `data` values. On failure, an error is returned.
///
/// # Parameters
///
/// - `record_type`: Record type as u8
/// - `address: Address of the record
/// - `input`: data of the record
fn format_record<T>(record_type: u8, address: u16, input: T) -> Result<String, Error>
where
    T: AsRef<[u8]>,
{
    let data = input.as_ref();
    if data.len() > 0xFF {
        return Err(Error::DataExceedsMaximumLength(data.len()));
    }

    // Allocate space for the data region (everything but the start code).
    let data_length = 1 + 2 + 1 + data.len() + 1;
    let mut data_region = Vec::<u8>::with_capacity(data_length);

    // Build the record (excluding start code) up to the checksum.
    data_region.push(data.len() as u8);
    data_region.push(((address & 0xFF00) >> 8) as u8);
    data_region.push((address & 0x00FF) as u8);
    data_region.push(record_type);
    data_region.extend_from_slice(data);

    // Compute the checksum of the data region thus far and append it.
    let checksum = crc_ihex(data_region.as_slice());
    data_region.push(checksum);

    // The result string is twice as long as the record plus the start code.
    let result_length = 1 + (2 * data_length);
    let mut result = String::with_capacity(result_length);

    // Construct the record.
    result.push(':');
    data_region.iter().try_fold(result, |mut acc, byte| {
        write!(&mut acc, "{:02X}", byte)
            .map_err(|_| Error::SynthesisFailed)
            .map(|_| acc)
    })
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn test_empty_record() {
        let res = IHexRecord::from_record_string("");
        assert_eq!(res, Err(Error::MissingStartCode));
    }

    #[test]
    fn test_wrong_start_code() {
        let res = IHexRecord::from_record_string(".0011110022");
        assert_eq!(res, Err(Error::MissingStartCode));
    }

    #[test]
    fn test_wrong_checksum() {
        let res = IHexRecord::from_record_string(":0011110022");
        assert_eq!(res, Err(Error::ChecksumMismatch(0xDE, 0x22)));
    }
    #[test]
    fn test_record_from_record_string_rejects_missing_start_code() {
        assert_eq!(
            IHexRecord::from_record_string("00000001FF"),
            Err(Error::MissingStartCode)
        );
    }

    #[test]
    fn test_record_from_record_string_rejects_short_records() {
        assert_eq!(
            IHexRecord::from_record_string(":"),
            Err(Error::RecordTooShort)
        );
        assert_eq!(
            IHexRecord::from_record_string(":00"),
            Err(Error::RecordTooShort)
        );
        assert_eq!(
            IHexRecord::from_record_string(":00000001F"),
            Err(Error::RecordTooShort)
        );
    }

    #[test]
    fn test_record_from_record_string_rejects_long_records() {
        let longest_valid_data = (0..255).map(|_| 0u8).collect::<Vec<u8>>();
        let longest_valid_data_record = IHexRecord::Data {
            offset: 0x0010,
            value: longest_valid_data,
        };
        let longest_valid_string = longest_valid_data_record.to_record_string().unwrap();
        let shortest_invalid_string = longest_valid_string.clone() + "0";

        assert_eq!(longest_valid_string.len(), 521);
        assert!(IHexRecord::from_record_string(&longest_valid_string).is_ok());

        assert_eq!(shortest_invalid_string.len(), 522);
        assert_eq!(
            IHexRecord::from_record_string(&shortest_invalid_string),
            Err(Error::RecordTooLong)
        );
    }

    #[test]
    fn test_record_from_record_string_rejects_odd_length_records() {
        assert_eq!(
            IHexRecord::from_record_string(":0B0010006164647265737320676170A7D"),
            Err(Error::RecordNotEvenLength)
        );
        assert_eq!(
            IHexRecord::from_record_string(":00000001FFF"),
            Err(Error::RecordNotEvenLength)
        );
        assert_eq!(
            IHexRecord::from_record_string(":0200000212FEECD"),
            Err(Error::RecordNotEvenLength)
        );
        assert_eq!(
            IHexRecord::from_record_string(":04000003123438007BD"),
            Err(Error::RecordNotEvenLength)
        );
        assert_eq!(
            IHexRecord::from_record_string(":02000004ABCD823"),
            Err(Error::RecordNotEvenLength)
        );
        assert_eq!(
            IHexRecord::from_record_string(":0400000512345678E34"),
            Err(Error::RecordNotEvenLength)
        );
    }

    #[test]
    fn test_record_from_record_string_rejects_non_hex_characters() {
        assert_eq!(
            IHexRecord::from_record_string(":000000q1ff"),
            Err(Error::ContainsInvalidCharacters)
        );
        assert_eq!(
            IHexRecord::from_record_string(":00000021f*"),
            Err(Error::ContainsInvalidCharacters)
        );
        assert_eq!(
            IHexRecord::from_record_string(":^0000001FF"),
            Err(Error::ContainsInvalidCharacters)
        );
        assert_eq!(
            IHexRecord::from_record_string(":â„¢0000001FF"),
            Err(Error::ContainsInvalidCharacters)
        );
    }

    #[test]
    fn test_record_from_record_string_rejects_invalid_checksums() {
        assert_eq!(
            IHexRecord::from_record_string(":0B0010006164647265737320676170FF"),
            Err(Error::ChecksumMismatch(0xA7, 0xFF))
        );
        assert_eq!(
            IHexRecord::from_record_string(":0000000100"),
            Err(Error::ChecksumMismatch(0xFF, 0x00))
        );
        assert_eq!(
            IHexRecord::from_record_string(":020000021200EB"),
            Err(Error::ChecksumMismatch(0xEA, 0xEB))
        );
        assert_eq!(
            IHexRecord::from_record_string(":04000003000038001C"),
            Err(Error::ChecksumMismatch(0xC1, 0x1C))
        );
        assert_eq!(
            IHexRecord::from_record_string(":02000004FFFFFD"),
            Err(Error::ChecksumMismatch(0xFC, 0xFD))
        );
        assert_eq!(
            IHexRecord::from_record_string(":04000005000001CD2A"),
            Err(Error::ChecksumMismatch(0x29, 0x2A))
        );
    }

    #[test]
    fn test_record_from_record_string_rejects_payload_length_mismatches() {
        assert_eq!(
            IHexRecord::from_record_string(":0C0010006164647265737320676170A6"),
            Err(Error::PayloadLengthMismatch)
        );
        assert_eq!(
            IHexRecord::from_record_string(":000010006164647265737320676170B2"),
            Err(Error::PayloadLengthMismatch)
        );
        assert_eq!(
            IHexRecord::from_record_string(":01000001FE"),
            Err(Error::PayloadLengthMismatch)
        );
        assert_eq!(
            IHexRecord::from_record_string(":0F0000021200DD"),
            Err(Error::PayloadLengthMismatch)
        );
        assert_eq!(
            IHexRecord::from_record_string(":0200000300003800C3"),
            Err(Error::PayloadLengthMismatch)
        );
        assert_eq!(
            IHexRecord::from_record_string(":01000004FFFFFD"),
            Err(Error::PayloadLengthMismatch)
        );
        assert_eq!(
            IHexRecord::from_record_string(":05000005000001CD28"),
            Err(Error::PayloadLengthMismatch)
        );
    }

    #[test]
    fn test_record_from_record_string_rejects_unsupported_record_types() {
        assert_eq!(
            IHexRecord::from_record_string(":0B0010066164647265737320676170A1"),
            Err(Error::UnsupportedRecordType {
                record: ":0B0010066164647265737320676170A1".into(),
                record_type: 0x06
            })
        );
        assert_eq!(
            IHexRecord::from_record_string(":0B0010FF6164647265737320676170A8"),
            Err(Error::UnsupportedRecordType {
                record: ":0B0010FF6164647265737320676170A8".into(),
                record_type: 0xff
            })
        );
    }

    #[test]
    fn test_record_from_record_string_rejects_invalid_lengths_for_types() {
        assert_eq!(
            IHexRecord::from_record_string(":01000001FFFF"),
            Err(Error::InvalidLengthForType)
        );
        assert_eq!(
            IHexRecord::from_record_string(":0100000200FD"),
            Err(Error::InvalidLengthForType)
        );
        assert_eq!(
            IHexRecord::from_record_string(":03000002FF1200EA"),
            Err(Error::InvalidLengthForType)
        );
        assert_eq!(
            IHexRecord::from_record_string(":03000003003800C2"),
            Err(Error::InvalidLengthForType)
        );
        assert_eq!(
            IHexRecord::from_record_string(":050000030000003800C0"),
            Err(Error::InvalidLengthForType)
        );
        assert_eq!(
            IHexRecord::from_record_string(":01000004FFFC"),
            Err(Error::InvalidLengthForType)
        );
        assert_eq!(
            IHexRecord::from_record_string(":03000004FFFFFFFC"),
            Err(Error::InvalidLengthForType)
        );
        assert_eq!(
            IHexRecord::from_record_string(":030000050000CD2B"),
            Err(Error::InvalidLengthForType)
        );
        assert_eq!(
            IHexRecord::from_record_string(":0500000500000000CD29"),
            Err(Error::InvalidLengthForType)
        );
    }

    #[test]
    fn test_record_from_record_string_parses_valid_data_records() {
        assert_eq!(
            IHexRecord::from_record_string(":0B0010006164647265737320676170A7"),
            Ok(IHexRecord::Data {
                offset: 0x0010,
                value: vec![0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x20, 0x67, 0x61, 0x70,],
            })
        );

        assert_eq!(
            IHexRecord::from_record_string(":00FFFE0003"),
            Ok(IHexRecord::Data {
                offset: 0xFFFE,
                value: vec![],
            })
        );
    }

    #[test]
    fn test_record_from_record_string_parses_valid_eof_record() {
        assert_eq!(
            IHexRecord::from_record_string(":00000001FF"),
            Ok(IHexRecord::EndOfFile)
        );
        assert_eq!(
            IHexRecord::from_record_string(":00000001ff"),
            Ok(IHexRecord::EndOfFile)
        );
    }

    #[test]
    fn test_record_from_record_string_parses_valid_extended_segment_address() {
        assert_eq!(
            IHexRecord::from_record_string(":0200000212FEEC"),
            Ok(IHexRecord::ExtendedSegmentAddress(0x12FE))
        );
        assert_eq!(
            IHexRecord::from_record_string(":0200000212fEEc"),
            Ok(IHexRecord::ExtendedSegmentAddress(0x12FE))
        );
    }

    #[test]
    fn test_record_from_record_string_parses_valid_start_segment_address() {
        assert_eq!(
            IHexRecord::from_record_string(":04000003123438007B"),
            IHexRecord::from_record_string(":04000003123438007b")
        );
        assert_eq!(
            IHexRecord::from_record_string(":04000003123438007B"),
            Ok(IHexRecord::StartSegmentAddress(0x12343800))
        );
    }

    #[test]
    fn test_record_from_record_string_parses_valid_extended_linear_address() {
        assert_eq!(
            IHexRecord::from_record_string(":02000004ABCD82"),
            Ok(IHexRecord::ExtendedLinearAddress(0xABCD))
        );
        assert_eq!(
            IHexRecord::from_record_string(":02000004abcd82"),
            Ok(IHexRecord::ExtendedLinearAddress(0xABCD))
        );
    }

    #[test]
    fn test_record_from_record_string_parses_valid_start_linear_address() {
        assert_eq!(
            IHexRecord::from_record_string(":0400000512345678E3"),
            Ok(IHexRecord::StartLinearAddress(0x12345678))
        );
        assert_eq!(
            IHexRecord::from_record_string(":0400000512345678e3"),
            Ok(IHexRecord::StartLinearAddress(0x12345678))
        );
    }

    #[test]
    fn test_to_record_string() {
        assert_eq!(
            IHexRecord::StartLinearAddress(0x12345678).to_record_string(),
            Ok(":0400000512345678E3".into())
        );
        assert_eq!(
            IHexRecord::ExtendedLinearAddress(0xABCD).to_record_string(),
            Ok(":02000004ABCD82".into())
        );
        assert_eq!(
            IHexRecord::StartSegmentAddress(0x12343800).to_record_string(),
            Ok(":04000003123438007B".into())
        );
        assert_eq!(
            IHexRecord::ExtendedSegmentAddress(0x12FE).to_record_string(),
            Ok(":0200000212FEEC".into())
        );
        assert_eq!(
            IHexRecord::EndOfFile.to_record_string(),
            Ok(":00000001FF".into())
        );
        assert_eq!(
            IHexRecord::Data {
                offset: 0x0010,
                value: vec![0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x20, 0x67, 0x61, 0x70,],
            }
            .to_record_string(),
            Ok(":0B0010006164647265737320676170A7".into())
        );
    }

    #[test]
    fn test_pretty_record_string() {
        println!(
            "{}",
            IHexRecord::StartLinearAddress(0x12345678)
                .to_pretty_record_string()
                .expect("Pretty Record should not fail")
        );
        println!(
            "{}",
            IHexRecord::ExtendedLinearAddress(0xABCD)
                .to_pretty_record_string()
                .expect("Pretty Record should not fail")
        );
        println!(
            "{}",
            IHexRecord::StartSegmentAddress(0x12343800)
                .to_pretty_record_string()
                .expect("Pretty Record should not fail")
        );
        println!(
            "{}",
            IHexRecord::ExtendedSegmentAddress(0x12FE)
                .to_pretty_record_string()
                .expect("Pretty Record should not fail")
        );
        println!(
            "{}",
            IHexRecord::EndOfFile
                .to_pretty_record_string()
                .expect("Pretty Record should not fail")
        );
        println!(
            "{}",
            IHexRecord::Data {
                offset: 0x0010,
                value: vec![0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x20, 0x67, 0x61, 0x70,],
            }
            .to_pretty_record_string()
            .expect("Pretty Record should not fail")
        );
    }
}