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
//! SD Card Registers
//!
//! Register representations can be created from an array of little endian
//! words. Note that the SDMMC protocol transfers the registers in big endian
//! byte order.
//!
//! ```
//! # use sdio_host::SCR;
//! let scr: SCR = [0, 1].into();
//! ```
//!
//! ## Reference documents:
//!
//! PLSS_v7_10: Physical Layer Specification Simplified Specification Version
//! 7.10. March 25, 2020. (C) SD Card Association

#![no_std]

use core::{fmt, str};

pub mod cmd;
#[doc(inline)]
pub use cmd::Cmd;

/// Types of SD Card
#[derive(Debug, Copy, Clone)]
#[non_exhaustive]
pub enum CardCapacity {
    /// Standard Capacity (< 2Gb)
    SDSC,
    /// High capacity (< 32Gb)
    SDHC,
}
impl Default for CardCapacity {
    fn default() -> Self {
        CardCapacity::SDSC
    }
}

#[non_exhaustive]
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum SDSpecVersion {
    /// Version 1.0 and and 1.0.1
    V1_0,
    /// Version 1.10
    V1_10,
    /// Version 2.0
    V2,
    /// Version 3.0
    V3,
    /// Version 4.0
    V4,
    /// Version 5.0
    V5,
    /// Version 6.0
    V6,
    /// Version 7.0
    V7,
    /// Version not known by this crate
    Unknown,
}

/// The number of data lines in use on the SDMMC bus
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
#[allow(missing_docs)]
pub enum BusWidth {
    #[non_exhaustive]
    Unknown,
    One = 1,
    Four = 4,
    Eight = 8,
}

#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum BlockSize {
    #[non_exhaustive]
    Unknown = 0,
    B512 = 9,
    B1024 = 10,
    B2048 = 11,
}

#[derive(Copy, Clone, Eq, PartialEq)]
#[allow(non_camel_case_types)]
pub enum CurrentConsumption {
    I_0mA,
    I_1mA,
    I_5mA,
    I_10mA,
    I_25mA,
    I_35mA,
    I_45mA,
    I_60mA,
    I_80mA,
    I_100mA,
    I_200mA,
}
impl From<&CurrentConsumption> for u32 {
    fn from(i: &CurrentConsumption) -> u32 {
        match i {
            CurrentConsumption::I_0mA => 0,
            CurrentConsumption::I_1mA => 1,
            CurrentConsumption::I_5mA => 5,
            CurrentConsumption::I_10mA => 10,
            CurrentConsumption::I_25mA => 25,
            CurrentConsumption::I_35mA => 35,
            CurrentConsumption::I_45mA => 45,
            CurrentConsumption::I_60mA => 60,
            CurrentConsumption::I_80mA => 80,
            CurrentConsumption::I_100mA => 100,
            CurrentConsumption::I_200mA => 200,
        }
    }
}
impl CurrentConsumption {
    fn from_minimum_reg(reg: u128) -> CurrentConsumption {
        match reg {
            0 => CurrentConsumption::I_0mA,
            1 => CurrentConsumption::I_1mA,
            2 => CurrentConsumption::I_5mA,
            3 => CurrentConsumption::I_10mA,
            4 => CurrentConsumption::I_25mA,
            5 => CurrentConsumption::I_35mA,
            6 => CurrentConsumption::I_60mA,
            _ => CurrentConsumption::I_100mA,
        }
    }
    fn from_maximum_reg(reg: u128) -> CurrentConsumption {
        match reg {
            0 => CurrentConsumption::I_0mA,
            1 => CurrentConsumption::I_5mA,
            2 => CurrentConsumption::I_10mA,
            3 => CurrentConsumption::I_25mA,
            4 => CurrentConsumption::I_35mA,
            5 => CurrentConsumption::I_45mA,
            6 => CurrentConsumption::I_80mA,
            _ => CurrentConsumption::I_200mA,
        }
    }
}
impl fmt::Debug for CurrentConsumption {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let ma: u32 = self.into();
        write!(f, "{} mA", ma)
    }
}

/// CURRENT_STATE enum. Used for R1 response in command queue mode.
///
/// Ref PLSS_v7_10 Table 4-75
#[derive(Eq, PartialEq, Copy, Clone, Debug)]
#[allow(dead_code)]
pub enum CurrentState {
    /// Card state is ready
    Ready = 1,
    /// Card is in identification state
    Identification = 2,
    /// Card is in standby state
    Standby = 3,
    /// Card is in transfer state
    Transfer = 4,
    /// Card is sending an operation
    Sending = 5,
    /// Card is receiving operation information
    Receiving = 6,
    /// Card is in programming state
    Programming = 7,
    /// Card is disconnected
    Disconnected = 8,
    // 9 - 14: Reserved
    // 15: Resevered
    /// Error
    Error = 128,
}

impl From<u8> for CurrentState {
    fn from(n: u8) -> Self {
        match n {
            1 => Self::Ready,
            2 => Self::Identification,
            3 => Self::Standby,
            4 => Self::Transfer,
            5 => Self::Sending,
            6 => Self::Receiving,
            7 => Self::Programming,
            8 => Self::Disconnected,
            _ => Self::Error,
        }
    }
}

/// Operation Conditions Register (OCR)
///
/// R3
#[derive(Clone, Copy, Default)]
pub struct OCR(u32);
impl From<u32> for OCR {
    fn from(word: u32) -> Self {
        Self(word)
    }
}
impl OCR {
    /// VDD voltage window
    pub fn voltage_window_mv(&self) -> Option<(u16, u16)> {
        let mut window = (self.0 >> 15) & 0x1FF;
        let mut min = 2_700;

        while window & 1 == 0 && window != 0 {
            min += 100;
            window >>= 1;
        }
        let mut max = min;
        while window != 0 {
            max += 100;
            window >>= 1;
        }

        if max == min {
            None
        } else {
            Some((min, max))
        }
    }
    /// Switching to 1.8V Accepted (S18A). Only UHS-I cards support this bit
    pub fn v18_allowed(&self) -> bool {
        self.0 & 0x0100_0000 != 0
    }
    /// Over 2TB support Status. Only SDUC card support this bit
    pub fn over_2tb(&self) -> bool {
        self.0 & 0x0800_0000 != 0
    }
    /// Indicates whether the card supports UHS-II Interface
    pub fn uhs2_card_status(&self) -> bool {
        self.0 & 0x2000_0000 != 0
    }
    /// Card Capacity Status (CCS). True for SDHC/SDXC/SDUC, false for SDSC
    pub fn high_capacity(&self) -> bool {
        self.0 & 0x4000_0000 != 0
    }
    /// Card power up status bit (busy)
    pub fn is_busy(&self) -> bool {
        self.0 & 0x8000_0000 == 0 // Set active LOW
    }
}
impl fmt::Debug for OCR {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("OCR: Operation Conditions Register")
            .field(
                "Voltage Window (mV)",
                &self.voltage_window_mv().unwrap_or((0, 0)),
            )
            .field("S18A (UHS-I only)", &self.v18_allowed())
            .field("Over 2TB flag (SDUC only)", &self.over_2tb())
            .field("UHS-II Card", &self.uhs2_card_status())
            .field(
                "Card Capacity Status (CSS)",
                &if self.high_capacity() {
                    "SDHC/SDXC/SDUC"
                } else {
                    "SDSC"
                },
            )
            .field("Busy", &self.is_busy())
            .finish()
    }
}

/// Card Identification Register (CID)
///
/// R2
#[derive(Clone, Copy, Default)]
pub struct CID {
    inner: u128,
    bytes: [u8; 16],
}
impl From<u128> for CID {
    fn from(inner: u128) -> Self {
        Self {
            inner,
            bytes: inner.to_be_bytes(),
        }
    }
}
/// From little endian words
impl From<[u32; 4]> for CID {
    fn from(words: [u32; 4]) -> Self {
        let inner = ((words[3] as u128) << 96)
            | ((words[2] as u128) << 64)
            | ((words[1] as u128) << 32)
            | words[0] as u128;
        inner.into()
    }
}
impl CID {
    /// Manufacturer ID
    pub fn manufacturer_id(&self) -> u8 {
        self.bytes[0]
    }
    /// OEM/Application ID
    pub fn oem_id(&self) -> &str {
        str::from_utf8(&self.bytes[1..3]).unwrap_or(&"<ERR>")
    }
    /// Product name
    pub fn product_name(&self) -> &str {
        str::from_utf8(&self.bytes[3..8]).unwrap_or(&"<ERR>")
    }
    /// Product revision
    pub fn product_revision(&self) -> u8 {
        self.bytes[8]
    }
    /// Product serial number
    pub fn serial(&self) -> u32 {
        (self.inner >> 24) as u32
    }
    /// Manufacturing date
    pub fn manufacturing_date(&self) -> (u8, u16) {
        (
            (self.inner >> 8) as u8 & 0xF,             // Month
            ((self.inner >> 12) as u16 & 0xFF) + 2000, // Year
        )
    }
    #[allow(unused)]
    fn crc7(&self) -> u8 {
        (self.bytes[15] >> 1) & 0x7F
    }
}
impl fmt::Debug for CID {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("CID: Card Identification")
            .field("Manufacturer ID", &self.manufacturer_id())
            .field("OEM ID", &self.oem_id())
            .field("Product Name", &self.product_name())
            .field("Product Revision", &self.product_revision())
            .field("Product Serial Number", &self.serial())
            .field("Manufacturing Date", &self.manufacturing_date())
            .finish()
    }
}

/// SD CARD Configuration Register (SCR)
#[derive(Clone, Copy, Default)]
pub struct SCR(pub u64);
/// From little endian words
impl From<[u32; 2]> for SCR {
    fn from(words: [u32; 2]) -> Self {
        Self(((words[1] as u64) << 32) | words[0] as u64)
    }
}
impl SCR {
    /// Physical Layer Specification Version Number
    pub fn version(&self) -> SDSpecVersion {
        let spec = (self.0 >> 56) & 0xF;
        let spec3 = (self.0 >> 47) & 1;
        let spec4 = (self.0 >> 42) & 1;
        let specx = (self.0 >> 38) & 0xF;

        // Ref PLSS_v7_10 Table 5-17
        match (spec, spec3, spec4, specx) {
            (0, 0, 0, 0) => SDSpecVersion::V1_0,
            (1, 0, 0, 0) => SDSpecVersion::V1_10,
            (2, 0, 0, 0) => SDSpecVersion::V2,
            (2, 1, 0, 0) => SDSpecVersion::V3,
            (2, 1, 1, 0) => SDSpecVersion::V4,
            (2, 1, _, 1) => SDSpecVersion::V5,
            (2, 1, _, 2) => SDSpecVersion::V6,
            (2, 1, _, 3) => SDSpecVersion::V7,
            _ => SDSpecVersion::Unknown,
        }
    }
    /// Bus widths supported
    pub fn bus_widths(&self) -> u8 {
        // Ref PLSS_v7_10 Table 5-21
        ((self.0 >> 48) as u8) & 0xF
    }
    /// Supports 1-bit bus width
    pub fn bus_width_one(&self) -> bool {
        (self.0 >> 48) & 1 != 0
    }
    /// Supports 4-bit bus width
    pub fn bus_width_four(&self) -> bool {
        (self.0 >> 50) & 1 != 0
    }
}
impl fmt::Debug for SCR {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("SCR: SD CARD Configuration Register")
            .field("Version", &self.version())
            .field("1-bit width", &self.bus_width_one())
            .field("4-bit width", &self.bus_width_four())
            .finish()
    }
}

/// Card Specific Data (CSD)
#[derive(Clone, Copy, Default)]
pub struct CSD(u128);
impl From<u128> for CSD {
    fn from(inner: u128) -> Self {
        Self(inner)
    }
}
/// From little endian words
impl From<[u32; 4]> for CSD {
    fn from(words: [u32; 4]) -> Self {
        let inner = ((words[3] as u128) << 96)
            | ((words[2] as u128) << 64)
            | ((words[1] as u128) << 32)
            | words[0] as u128;
        inner.into()
    }
}
impl CSD {
    /// CSD structure version
    pub fn version(&self) -> u8 {
        (self.0 >> 126) as u8 & 3
    }
    /// Maximum data transfer rate per one data line
    pub fn transfer_rate(&self) -> u8 {
        (self.0 >> 96) as u8
    }
    /// Maximum block length. In an SD Memory Card the WRITE_BL_LEN is
    /// always equal to READ_BL_LEN
    pub fn block_length(&self) -> BlockSize {
        // Read block length
        match (self.0 >> 80) & 0xF {
            9 => BlockSize::B512,
            10 => BlockSize::B1024,
            11 => BlockSize::B2048,
            _ => BlockSize::Unknown,
        }
    }
    /// Number of blocks in the card
    pub fn block_count(&self) -> u32 {
        match self.version() {
            0 => {
                // SDSC
                let c_size: u16 = ((self.0 >> 62) as u16) & 0xFFF;
                let c_size_mult: u8 = ((self.0 >> 47) as u8) & 7;

                ((c_size + 1) as u32) * ((1 << (c_size_mult + 2)) as u32)
            }
            1 => {
                // SDHC / SDXC
                (((self.0 >> 48) as u32 & 0x3F_FFFF) + 1) * 1024
            }
            2 => {
                // SDUC
                (((self.0 >> 48) as u32 & 0xFFF_FFFF) + 1) * 1024
            }
            _ => 0,
        }
    }
    /// Card size in bytes
    pub fn card_size(&self) -> u64 {
        let block_size_bytes = 1 << self.block_length() as u64;

        (self.block_count() as u64) * block_size_bytes
    }
    /// Maximum read current at the minimum VDD
    pub fn read_current_minimum_vdd(&self) -> CurrentConsumption {
        CurrentConsumption::from_minimum_reg(self.0 >> 59)
    }
    /// Maximum write current at the minimum VDD
    pub fn write_current_minimum_vdd(&self) -> CurrentConsumption {
        CurrentConsumption::from_minimum_reg(self.0 >> 56)
    }
    /// Maximum read current at the maximum VDD
    pub fn read_current_maximum_vdd(&self) -> CurrentConsumption {
        CurrentConsumption::from_maximum_reg(self.0 >> 53)
    }
    /// Maximum write current at the maximum VDD
    pub fn write_current_maximum_vdd(&self) -> CurrentConsumption {
        CurrentConsumption::from_maximum_reg(self.0 >> 50)
    }
    /// Erase size (in blocks)
    pub fn erase_size_blocks(&self) -> u32 {
        if (self.0 >> 46) & 1 == 1 {
            // ERASE_BLK_EN
            1
        } else {
            let sector_size_tens = (self.0 >> 43) & 0x7;
            let sector_size_units = (self.0 >> 39) & 0xF;

            (sector_size_tens as u32 * 10) + (sector_size_units as u32)
        }
    }
}
impl fmt::Debug for CSD {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("CSD: Card Specific Data")
            .field("Transfer Rate", &self.transfer_rate())
            .field("Block Count", &self.block_count())
            .field("Card Size (bytes)", &self.card_size())
            .field("Read I (@min VDD)", &self.read_current_minimum_vdd())
            .field("Write I (@min VDD)", &self.write_current_minimum_vdd())
            .field("Read I (@max VDD)", &self.read_current_maximum_vdd())
            .field("Write I (@max VDD)", &self.write_current_maximum_vdd())
            .field("Erase Size (Blocks)", &self.erase_size_blocks())
            .finish()
    }
}

/// Card Status (R1)
///
/// Error and state information of an executed command
///
/// Ref PLSS_v7_10 Section 4.10.1
#[derive(Clone, Copy)]
pub struct CardStatus(u32);

impl From<u32> for CardStatus {
    fn from(word: u32) -> Self {
        Self(word)
    }
}

impl CardStatus {
    /// Command's argument was out of range
    pub fn out_of_range(&self) -> bool {
        self.0 & 0x8000_0000 != 0
    }
    /// Misaligned address
    pub fn address_error(&self) -> bool {
        self.0 & 0x4000_0000 != 0
    }
    /// Block len error
    pub fn block_len_error(&self) -> bool {
        self.0 & 0x2000_0000 != 0
    }
    /// Error in the erase commands sequence
    pub fn erase_seq_error(&self) -> bool {
        self.0 & 0x1000_0000 != 0
    }
    /// Invalid selection of blocks for erase
    pub fn erase_param(&self) -> bool {
        self.0 & 0x800_0000 != 0
    }
    /// Host attempted to write to protected area
    pub fn wp_violation(&self) -> bool {
        self.0 & 0x400_0000 != 0
    }
    /// Card is locked by the host
    pub fn card_is_locked(&self) -> bool {
        self.0 & 0x200_0000 != 0
    }
    /// Password error
    pub fn lock_unlock_failed(&self) -> bool {
        self.0 & 0x100_0000 != 0
    }
    /// Crc check of previous command failed
    pub fn com_crc_error(&self) -> bool {
        self.0 & 0x80_0000 != 0
    }
    /// Command is not legal for the card state
    pub fn illegal_command(&self) -> bool {
        self.0 & 0x40_0000 != 0
    }
    /// Card internal ECC failed
    pub fn card_ecc_failed(&self) -> bool {
        self.0 & 0x20_0000 != 0
    }
    /// Internal controller error
    pub fn cc_error(&self) -> bool {
        self.0 & 0x10_0000 != 0
    }
    /// A General error occurred
    pub fn error(&self) -> bool {
        self.0 & 0x8_0000 != 0
    }
    // Bit 18: Reserved
    // Bit 17: Reserved
    /// CSD error
    pub fn csd_overwrite(&self) -> bool {
        self.0 & 0x1_0000 != 0
    }
    /// Some blocks where skipped while erasing
    pub fn wp_erase_skip(&self) -> bool {
        self.0 & 0x8000 != 0
    }
    /// Command was executed without internal ECC
    pub fn ecc_disabled(&self) -> bool {
        self.0 & 0x4000 != 0
    }
    /// Erase sequence was aborted
    pub fn erase_reset(&self) -> bool {
        self.0 & 0x2000 != 0
    }
    /// Current card state
    pub fn state(&self) -> CurrentState {
        CurrentState::from(((self.0 >> 9) & 0xF) as u8)
    }
    /// Corresponds to buffer empty signaling on the bus
    pub fn ready_for_data(&self) -> bool {
        self.0 & 0x100 != 0
    }
    // Bit 7: Reserved
    /// Extension function specific status
    pub fn fx_event(&self) -> bool {
        self.0 & 0x40 != 0
    }
    /// The card will accept a ACMD
    pub fn app_cmd(&self) -> bool {
        self.0 & 0x20 != 0
    }
    // Bit 4: Reserved
    /// Authentication sequence error
    pub fn ake_seq_error(&self) -> bool {
        self.0 & 0x8 != 0
    }
    // Bits 2,1,0: Reserved
}

impl fmt::Debug for CardStatus {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Card Status")
            .field("Out of range error", &self.out_of_range())
            .field("Address error", &self.address_error())
            .field("Block len error", &self.block_len_error())
            .field("Erase seq error", &self.erase_seq_error())
            .field("Erase param error", &self.erase_param())
            .field("Write protect error", &self.wp_violation())
            .field("Card locked", &self.card_is_locked())
            .field("Password lock unlock error", &self.lock_unlock_failed())
            .field(
                "Crc check for the previous command failed",
                &self.com_crc_error(),
            )
            .field("Illegal command", &self.illegal_command())
            .field("Card internal ecc failed", &self.card_ecc_failed())
            .field("Internal card controller error", &self.cc_error())
            .field("General Error", &self.error())
            .field("Csd error", &self.csd_overwrite())
            .field("Write protect error", &self.wp_erase_skip())
            .field("Command ecc disabled", &self.ecc_disabled())
            .field("Erase sequence cleared", &self.erase_reset())
            .field("Card state", &self.state())
            .field("Buffer empty", &self.ready_for_data())
            .field("Extension event", &self.fx_event())
            .field("Card expects app cmd", &self.app_cmd())
            .field("Auth process error", &self.ake_seq_error())
            .finish()
    }
}

/// SD Status
///
/// Status bits related to SD Memory Card proprietary features
///
/// Ref PLSS_v7_10 Section 4.10.2 SD Status
#[derive(Clone, Copy, Default)]
pub struct SDStatus {
    inner: [u32; 16],
}
/// From little endian words
impl From<[u32; 16]> for SDStatus {
    fn from(inner: [u32; 16]) -> Self {
        Self { inner }
    }
}
impl SDStatus {
    /// Current data bus width
    pub fn bus_width(&self) -> BusWidth {
        match (self.inner[15] >> 30) & 3 {
            0 => BusWidth::One,
            2 => BusWidth::Four,
            _ => BusWidth::Unknown,
        }
    }
    /// Is the card currently in the secured mode
    pub fn secure_mode(&self) -> bool {
        self.inner[15] & 0x2000_0000 != 0
    }
    /// SD Memory Card type (ROM, OTP, etc)
    pub fn sd_memory_card_type(&self) -> u16 {
        self.inner[15] as u16
    }
    /// SDHC / SDXC: Capacity of Protected Area in bytes
    pub fn protected_area_size(&self) -> u32 {
        self.inner[14]
    }
    /// Speed Class
    pub fn speed_class(&self) -> u8 {
        (self.inner[13] >> 24) as u8
    }
    /// "Performance Move" indicator in 1 MB/s units
    pub fn move_performance(&self) -> u8 {
        (self.inner[13] >> 16) as u8
    }
    /// Allocation Unit (AU) size. Lookup in PLSS v7_10 Table 4-47
    pub fn allocation_unit_size(&self) -> u8 {
        (self.inner[13] >> 12) as u8 & 0xF
    }
    /// Indicates N_Erase, in units of AU
    pub fn erase_size(&self) -> u16 {
        (self.inner[13] & 0xFF) as u16 | ((self.inner[12] >> 24) & 0xFF) as u16
    }
    /// Indicates T_Erase / Erase Timeout (s)
    pub fn erase_timeout(&self) -> u8 {
        (self.inner[12] >> 18) as u8 & 0x3F
    }
    /// Video speed class
    pub fn video_speed_class(&self) -> u8 {
        (self.inner[11] & 0xFF) as u8
    }
    /// Application Performance Class
    pub fn app_perf_class(&self) -> u8 {
        (self.inner[9] >> 16) as u8 & 0xF
    }
    /// Discard Support
    pub fn discard_support(&self) -> bool {
        self.inner[8] & 0x0200_0000 != 0
    }
}
impl fmt::Debug for SDStatus {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("SD Status")
            .field("Bus Width", &self.bus_width())
            .field("Secured Mode", &self.secure_mode())
            .field("SD Memory Card Type", &self.sd_memory_card_type())
            .field("Protected Area Size (B)", &self.protected_area_size())
            .field("Speed Class", &self.speed_class())
            .field("Video Speed Class", &self.video_speed_class())
            .field("Application Performance Class", &self.app_perf_class())
            .field("Move Performance (MB/s)", &self.move_performance())
            .field("AU Size", &self.allocation_unit_size())
            .field("Erase Size (units of AU)", &self.erase_size())
            .field("Erase Timeout (s)", &self.erase_timeout())
            .field("Discard Support", &self.discard_support())
            .finish()
    }
}

/// Relative Card Address (RCA)
///
/// R6
#[derive(Copy, Clone, Default)]
pub struct RCA(u32);
impl From<u32> for RCA {
    fn from(word: u32) -> Self {
        Self(word)
    }
}
impl RCA {
    /// Address of card
    pub fn address(&self) -> u16 {
        (self.0 >> 16) as u16
    }
    /// Status
    pub fn status(&self) -> u16 {
        self.0 as u16
    }
}

/// Card interface condition (R7)
#[derive(Copy, Clone, Default)]
pub struct CIC(u32);
impl From<u32> for CIC {
    fn from(word: u32) -> Self {
        Self(word)
    }
}
impl CIC {
    /// The voltage range the card accepts
    pub fn voltage_accepted(&self) -> u8 {
        (self.0 >> 8) as u8
    }
    /// Echo-back check pattern
    pub fn pattern(&self) -> u8 {
        self.0 as u8
    }
}