yapu 0.1.0-alpha.2

AN3155-compliant programmer
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
#[allow(unused_imports)]
use binrw::{BinRead, BinWrite, binread, binrw, binwrite};
use std::borrow::Cow;
use std::ops::RangeInclusive;
use std::ops::{Deref, DerefMut};

#[cfg(feature = "serde")]
use serde::{Deserialize, Deserializer, Serialize, Serializer};
#[allow(unused_imports)]
#[cfg(feature = "serde")]
use serde::{de, de::Error as _, ser};

/// Protocol conversion error
#[derive(Debug, Clone)]
pub enum Error {
    Exceeded(Exceeded),
}

impl Error {
    pub fn is_exceeded(&self) -> bool {
        matches!(self, Self::Exceeded(..))
    }

    pub fn exceeded(&self) -> Option<&Exceeded> {
        match &self {
            Self::Exceeded(e) => Some(e),
        }
    }
}

impl From<Exceeded> for Error {
    fn from(value: Exceeded) -> Self {
        Self::Exceeded(value)
    }
}

impl std::fmt::Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Exceeded(e) => write!(f, "exceeded: {}", e),
        }
    }
}

impl std::error::Error for Error {}

#[derive(Debug, Clone)]
pub struct Exceeded(usize, ExpectedRange);

impl Exceeded {
    pub fn unexpected(&self) -> usize {
        self.0
    }
    pub fn expected_range(&self) -> &RangeInclusive<usize> {
        &self.1.0
    }

    #[cfg(feature = "serde")]
    pub fn to_serde<'de, D: Deserializer<'de>>(&self) -> D::Error {
        D::Error::invalid_value(de::Unexpected::Unsigned(self.0 as u64), &self.1)
    }
}

impl std::fmt::Display for Exceeded {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{} is not within valid range of size ({})",
            self.0, self.1
        )
    }
}

impl std::error::Error for Exceeded {}

/// A wrapper of [`RangeInclusive<usize>`] that implements [`de::Expected`], for
/// friendlier error handling during deserialization.
#[derive(Debug, Clone, PartialEq, Eq)]
struct ExpectedRange(RangeInclusive<usize>);

impl From<RangeInclusive<usize>> for ExpectedRange {
    fn from(value: RangeInclusive<usize>) -> Self {
        Self(value)
    }
}

impl std::fmt::Display for ExpectedRange {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{:?}", self.0)
    }
}

#[cfg(feature = "serde")]
impl de::Expected for ExpectedRange {
    fn fmt(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(formatter, "a size within range {}", self)
    }
}

mod checksum {
    #[derive(Default, Debug, Clone)]
    pub struct Buffer {
        state: u8,
    }

    impl Buffer {
        pub fn new() -> Self {
            Self::default()
        }
        pub fn state(&self) -> u8 {
            self.state
        }
    }

    impl std::io::Write for Buffer {
        fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
            self.state = self.state ^ iter(buf.iter().copied());
            Ok(buf.len())
        }
        fn flush(&mut self) -> std::io::Result<()> {
            Ok(())
        }
    }

    pub(super) fn single(data: u8) -> u8 {
        data ^ 0xff
    }

    pub(super) fn iter(data: impl Iterator<Item = u8>) -> u8 {
        data.fold(0u8, |acc, e| acc ^ e)
    }
}

/// A wrapper type for opcode.
///
/// `binrw` only supports magic literals, which means any computed value is not
/// supported, no matter it's constant or not. Therefore it's not possible to
/// write:
///
/// ```ignore
/// #[derive(BinWrite)]
/// #[bw(big)]
/// enum Command {
///     #[bw(magic = (0x00u8 << 8) ^ (0x00u8 ^ 0xffu8))]
///     Get,
/// }
/// ```
///
/// The workaround here is to define a new wrapper type for opcodes and add a
/// checksum field with computed `binrw` values, which requires using procedural
/// macro `binwrite` rather than derive macro `BinWrite`.
#[binwrite]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[bw(big)]
pub struct Opcode(u8, #[bw(calc = checksum::single(self.0))] u8);

impl Opcode {
    pub const GET: Self = Self(0x00u8);
    pub const GET_VERSION: Self = Self(0x01u8);
    pub const GET_ID: Self = Self(0x02u8);
    pub const READ: Self = Self(0x11u8);
    pub const GO: Self = Self(0x21u8);
    pub const WRITE: Self = Self(0x31u8);
    pub const ERASE: Self = Self(0x43u8);
    pub const EXTENDED_ERASE: Self = Self(0x44u8);
    pub const WRITE_PROTECT: Self = Self(0x63u8);
    pub const WRITE_UNPROTECT: Self = Self(0x73u8);
    pub const READ_PROTECT: Self = Self(0x82u8);
    pub const READ_UNPROTECT: Self = Self(0x92u8);
    pub const GET_CHECKSUM: Self = Self(0xa1u8);
    pub const SPECIAL: Self = Self(0x50u8);
    pub const EXTENDED_SPECIAL: Self = Self(0x51u8);

    pub fn as_u8(&self) -> u8 {
        self.0
    }
}

impl std::fmt::Display for Opcode {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            &Self::GET => write!(f, "GET"),
            &Self::GET_VERSION => write!(f, "GET_VERSION"),
            &Self::GET_ID => write!(f, "GET_ID"),
            &Self::READ => write!(f, "READ"),
            &Self::GO => write!(f, "GO"),
            &Self::WRITE => write!(f, "WRITE"),
            &Self::ERASE => write!(f, "ERASE"),
            &Self::EXTENDED_ERASE => write!(f, "EXTENDED_ERASE"),
            &Self::WRITE_PROTECT => write!(f, "WRITE_PROTECT"),
            &Self::WRITE_UNPROTECT => write!(f, "WRITE_UNPROTECT"),
            &Self::READ_PROTECT => write!(f, "READ_PROTECT"),
            &Self::READ_UNPROTECT => write!(f, "READ_UNPROTECT"),
            &Self::GET_CHECKSUM => write!(f, "GET_CHECKSUM"),
            &Self::SPECIAL => write!(f, "SPECIAL"),
            &Self::EXTENDED_SPECIAL => write!(f, "EXTENDED_SPECIAL"),
            opcode => write!(f, "UNKNOWN ({:02x?})", opcode.as_u8()),
        }
    }
}

impl From<u8> for Opcode {
    fn from(value: u8) -> Self {
        Self(value)
    }
}

/// Address
#[binwrite]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[bw(big)]
pub struct Address(
    u32,
    #[bw(calc = checksum::iter(self.0.to_ne_bytes().iter().copied()))] u8,
);

impl Address {
    pub fn as_u32(&self) -> u32 {
        self.0
    }
}

impl From<u32> for Address {
    fn from(value: u32) -> Self {
        Self(value)
    }
}

impl Into<u32> for Address {
    fn into(self) -> u32 {
        self.0
    }
}

macro_rules! define_slice_item {
    ($vis:vis $name:ident($inner_ty:ident), $as_method:ident, $size_ty:ty, $size_range:expr) => {
        #[derive(BinWrite, Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
        $vis struct $name;

        impl SliceItem for $name {
            type Repr = $inner_ty;
            type Size = $size_ty;
            const SIZE_RANGE: RangeInclusive<usize> = $size_range;
        }
    }
}

pub type PageNo = u8;
pub type ExtendedPageNo = u16;
pub type SectorNo = u8;

define_slice_item! { pub Byte(u8), as_u8, u8, 1..=256 }
define_slice_item! { pub Page(PageNo), as_u8, u8, 1..=256 }
define_slice_item! { pub ExtendedPage(ExtendedPageNo), as_u16, u16, 1..=0xff00 }
define_slice_item! { pub Sector(SectorNo), as_u8, u8, 1..=256 }

#[binwrite]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[bw(big)]
pub struct Size(u8, #[bw(calc = checksum::single(self.0))] u8);

impl Into<usize> for Size {
    fn into(self) -> usize {
        self.0 as usize + <Byte as SliceItem>::SIZE_RANGE.start()
    }
}

impl TryFrom<usize> for Size {
    type Error = Error;

    fn try_from(value: usize) -> Result<Self, Self::Error> {
        let range = <Byte as SliceItem>::SIZE_RANGE;
        if range.contains(&value) {
            Ok(Self(value as u8))
        } else {
            Err(Exceeded(value, range.into()).into())
        }
    }
}

#[cfg(feature = "serde")]
impl<'de> Deserialize<'de> for Size {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let value = usize::deserialize(deserializer)?;
        let converted = Self::try_from(value).map_err(|e| {
            let exceeded = e.exceeded().unwrap();
            exceeded.to_serde::<D>()
        })?;
        Ok(converted)
    }
}

#[cfg(feature = "serde")]
impl serde::Serialize for Size {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_u64(self.0 as u64)
    }
}

pub trait SliceItem {
    #[cfg(not(feature = "serde"))]
    type Repr: Copy + Clone;
    #[cfg(feature = "serde")]
    type Repr: Copy + Clone + Serialize + for<'de> Deserialize<'de>;
    type Size: TryFrom<usize>;
    const SIZE_RANGE: RangeInclusive<usize> = usize::MIN..=usize::MAX;
}

#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Slice<'a, T: SliceItem> {
    inner: Cow<'a, [T::Repr]>,
}

impl<'a, T: SliceItem> Deref for Slice<'a, T> {
    type Target = Cow<'a, [T::Repr]>;

    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}

impl<'a, T: SliceItem> DerefMut for Slice<'a, T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.inner
    }
}

impl<'a, T: SliceItem> Slice<'a, T> {
    /// Consumes [`Slice`] and returns the inner [`Cow`].
    pub fn into_inner(self) -> Cow<'a, [T::Repr]> {
        self.inner
    }

    /// Returns slice of specific slice items.
    pub fn as_slice(&self) -> &[T::Repr] {
        &self.inner
    }
}

impl<'a, T: SliceItem> Into<Cow<'a, [T::Repr]>> for Slice<'a, T> {
    fn into(self) -> Cow<'a, [T::Repr]> {
        self.inner
    }
}

impl<'a, T: SliceItem> TryFrom<Cow<'a, [T::Repr]>> for Slice<'a, T> {
    type Error = Error;

    fn try_from(value: Cow<'a, [T::Repr]>) -> Result<Self, Self::Error> {
        if T::SIZE_RANGE.contains(&value.len()) {
            Ok(Self { inner: value })
        } else {
            Err(Exceeded(value.len(), T::SIZE_RANGE.into()).into())
        }
    }
}

impl<'a, T: SliceItem> TryFrom<Vec<T::Repr>> for Slice<'a, T> {
    type Error = Error;

    fn try_from(value: Vec<T::Repr>) -> Result<Self, Self::Error> {
        if T::SIZE_RANGE.contains(&value.len()) {
            Ok(Self {
                inner: value.into(),
            })
        } else {
            Err(Exceeded(value.len(), T::SIZE_RANGE.into()).into())
        }
    }
}

impl<'a, T: SliceItem> TryFrom<&'a [T::Repr]> for Slice<'a, T> {
    type Error = Error;

    fn try_from(value: &'a [T::Repr]) -> Result<Self, Self::Error> {
        if T::SIZE_RANGE.contains(&value.len()) {
            Ok(Self {
                inner: value.into(),
            })
        } else {
            Err(Exceeded(value.len(), T::SIZE_RANGE.into()).into())
        }
    }
}

impl<'a, T: SliceItem + BinWrite<Args<'a> = ()>> BinWrite for Slice<'a, T>
where
    [T::Repr]: BinWrite<Args<'a> = ()>,
    T::Size: BinWrite<Args<'a> = ()>,
    <T::Size as TryFrom<usize>>::Error: std::fmt::Debug,
{
    type Args<'arg> = ();

    fn write_options<W: std::io::Write + std::io::Seek>(
        &self,
        writer: &mut W,
        endian: binrw::Endian,
        args: Self::Args<'_>,
    ) -> binrw::BinResult<()> {
        use binrw::io::NoSeek;

        // write shifted size
        let lowerbound = *<T as SliceItem>::SIZE_RANGE.start();
        let size = <T as SliceItem>::Size::try_from(self.inner.len() - lowerbound).unwrap();
        size.write_options(writer, endian, args)?;

        // write data
        self.inner.write_options(writer, endian, args)?;

        // write checksum
        let mut buffer = checksum::Buffer::new();
        self.inner
            .write_options(&mut NoSeek::new(&mut buffer), endian, args)?;
        buffer.state().write_options(writer, endian, args)?;

        Ok(())
    }
}

impl<'a, T: SliceItem + BinWrite<Args<'a> = ()>> binrw::meta::WriteEndian for Slice<'a, T>
where
    [T::Repr]: BinWrite<Args<'a> = ()>,
    T::Size: BinWrite<Args<'a> = ()>,
    <T::Size as TryFrom<usize>>::Error: std::fmt::Debug,
{
    const ENDIAN: binrw::meta::EndianKind = binrw::meta::EndianKind::Endian(binrw::Endian::Big);
}

pub type Data<'a> = Slice<'a, Byte>;
pub type PageNos<'a> = Slice<'a, Page>;
pub type ExtendedPageNos<'a> = Slice<'a, ExtendedPage>;
pub type SectorNos<'a> = Slice<'a, Sector>;

/// Command
#[binwrite]
#[derive(Debug, Clone)]
#[bw(big)]
pub enum Command<'a> {
    Get(#[bw(calc = Opcode::GET)] Opcode),
    Version(#[bw(calc = Opcode::GET_VERSION)] Opcode),
    Id(#[bw(calc = Opcode::GET_ID)] Opcode),
    Read {
        #[bw(calc = Opcode::READ)]
        opcode: Opcode,
        address: Address,
        size: Size,
    },
    Go(#[bw(calc = Opcode::GO)] Opcode, Address),
    Write {
        #[bw(calc = Opcode::WRITE)]
        opcode: Opcode,
        address: Address,
        data: Data<'a>,
    },
    Erase(#[bw(calc = Opcode::ERASE)] Opcode, Erase<'a>),
    ExtendedErase(#[bw(calc = Opcode::ERASE)] Opcode, ExtendedErase<'a>),
    WriteProtect(#[bw(calc = Opcode::WRITE_PROTECT)] Opcode),
    WriteUnprotect(#[bw(calc = Opcode::WRITE_UNPROTECT)] Opcode),
    ReadProtect(#[bw(calc = Opcode::READ_PROTECT)] Opcode),
    ReadUnprotect(#[bw(calc = Opcode::READ_UNPROTECT)] Opcode),

    /// This is used for baudrate handshaking.
    #[bw(magic = 0x7fu8)]
    Synchronize,
}

/// Command for [`Opcode::ERASE`].
#[derive(BinWrite, Debug, Clone)]
#[bw(big)]
pub enum Erase<'a> {
    #[bw(magic = 0xff00u16)]
    Global,
    Specific(Slice<'a, Page>),
}

impl<'a> Erase<'a> {
    /// Whether erasure is done globally.
    pub fn is_global(self) -> bool {
        matches!(self, Self::Global)
    }

    /// Whether erasure is done on specific pages.
    pub fn is_specific(self) -> bool {
        matches!(self, Self::Specific(..))
    }

    /// Returns pages if the erasure is not global.
    pub fn pages(&self) -> Option<&[PageNo]> {
        match self {
            Self::Global => None,
            Self::Specific(slice) => Some(slice.as_slice()),
        }
    }
}

/// Command for [`Opcode::EXTENDED_ERASE`].
#[derive(BinWrite, Debug, Clone)]
#[bw(big)]
pub enum ExtendedErase<'a> {
    #[bw(magic = b"\xff\xff\x00")]
    Global,
    #[bw(magic = b"\xff\xfe\x01")]
    Bank1,
    #[bw(magic = b"\xff\xfd\x02")]
    Bank2,
    Specific(Slice<'a, ExtendedPage>),
}

impl<'a> ExtendedErase<'a> {
    /// Whether erasure is done globally.
    pub fn is_global(self) -> bool {
        matches!(self, Self::Global)
    }

    /// Whether erasure is done on bank 1.
    pub fn is_bank1(self) -> bool {
        matches!(self, Self::Bank1)
    }

    /// Whether erasure is done on bank 2.
    pub fn is_bank2(self) -> bool {
        matches!(self, Self::Bank2)
    }

    /// Whether erasure is done on specific pages.
    pub fn is_specific(self) -> bool {
        matches!(self, Self::Specific(..))
    }

    /// Returns pages if the erasure is not global.
    pub fn pages(&self) -> Option<&[ExtendedPageNo]> {
        match self {
            Self::Global => None,
            Self::Bank1 => None,
            Self::Bank2 => None,
            Self::Specific(slice) => Some(slice.as_slice()),
        }
    }
}

/// Reply
#[derive(BinRead, Debug, Clone, Copy)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[br(big)]
pub enum Reply {
    /// ACK
    #[brw(magic = 0x79u8)]
    Ack,
    /// Negative
    #[brw(magic = 0x1fu8)]
    NAck,
}

/// Bootloader information
///
/// Contains version and supported [`Opcode`]s.
#[binread]
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[br(big)]
pub struct Bootloader {
    #[br(temp)]
    len: u8,
    version: u8,
    #[br(count = len, map = |data: Vec<u8>| {
        data.into_iter().map(|v| v.into()).collect()
    })]
    opcodes: Vec<Opcode>,
}

impl Bootloader {
    /// Bootloader version in [`u8`].
    #[inline]
    pub fn version(&self) -> u8 {
        self.version
    }

    /// Bootloader major version.
    #[inline]
    pub fn major(&self) -> u8 {
        self.version >> 4
    }

    /// Bootloader minor version.
    #[inline]
    pub fn minor(&self) -> u8 {
        self.version & 0xf
    }

    /// Bootloader version string.
    pub fn version_string(&self) -> String {
        format!("{}.{}", self.major(), self.minor())
    }

    /// Supported [`Opcode`]s of the bootloader.
    #[inline]
    pub fn opcodes(&self) -> &[Opcode] {
        &self.opcodes
    }

    /// Whether bootloader supports an [`Opcode`].
    #[inline]
    pub fn supports(&self, opcode: impl Into<Opcode>) -> bool {
        self.opcodes.contains(&opcode.into())
    }
}

/// Version
#[derive(BinRead, Debug, Clone)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[br(big)]
pub struct Version {
    version: u8,
    options: [u8; 2],
}

impl Version {
    /// Bootloader version in [`u8`].
    #[inline]
    pub fn version(&self) -> u8 {
        self.version
    }

    /// Bootloader major version.
    #[inline]
    pub fn major(&self) -> u8 {
        self.version >> 4
    }

    /// Bootloader minor version.
    #[inline]
    pub fn minor(&self) -> u8 {
        self.version & 0xf
    }

    /// Bootloader version string.
    pub fn version_string(&self) -> String {
        format!("{}.{}", self.major(), self.minor())
    }

    #[inline]
    pub fn options(&self) -> [u8; 2] {
        self.options
    }
}

impl std::fmt::Display for Version {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}.{}", self.major(), self.minor())
    }
}

/// Chip ID
#[binread]
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[br(big)]
pub struct Id {
    #[br(temp)]
    len: u8,
    #[br(count = len + 1)]
    id: Vec<u8>,
}

impl Id {
    /// Consumes [`Id`] and returns raw chip ID in [`Vec<u8>`].
    #[inline]
    pub fn into_id(self) -> Vec<u8> {
        self.id
    }

    /// Returns raw chip ID in [`[u8]`] slice.
    #[inline]
    pub fn id(&self) -> &[u8] {
        &self.id
    }

    /// Returns raw chip ID in [`[u8]`] slice.
    #[inline]
    pub fn as_slice(&self) -> &[u8] {
        &self.id
    }

    /// Converts chip ID to a fixed-size array.
    pub fn as_array<const N: usize>(&self) -> [u8; N] {
        let mut buf: [u8; N] = [0u8; N];
        buf[N - self.id.len()..].copy_from_slice(&self.id);
        buf
    }

    /// Interprets chip ID as [`u16`].
    #[inline]
    pub fn as_u16(&self) -> u16 {
        u16::from_be_bytes(self.as_array())
    }

    /// Interprets chip ID as [`u32`].
    #[inline]
    pub fn as_u32(&self) -> u32 {
        u32::from_be_bytes(self.as_array())
    }

    /// Interprets chip ID as [`u64`].
    #[inline]
    pub fn as_u64(&self) -> u64 {
        u64::from_be_bytes(self.as_array())
    }
}