sdmmc-core 0.5.0

SD/MMC core data structures and algorithms
Documentation
use crate::lib_bitfield;
use crate::result::{Error, Result};

const CARD_STATUS_MASK: u16 = 0xe000;

lib_bitfield! {
    /// Represents the card status field of the [R6](super::R6) response in SDIO mode.
    pub CardStatus(u16): bool {
        /// The CRC check of the previous command failed.
        pub crc_error: 15;
        /// Command not legal for the card state.
        pub illegal_command: 14;
        /// A general or an unknown error occurred.
        pub error: 13;
    }
}

impl CardStatus {
    /// Represents the byte length of the [CardStatus].
    pub const LEN: usize = 2;

    /// Creates a new [CardStatus].
    pub const fn new() -> Self {
        Self(0)
    }

    /// Converts a [`u16`] into a [CardStatus].
    pub const fn from_bits(val: u16) -> Self {
        Self(val & CARD_STATUS_MASK)
    }

    /// Converts the [CardStatus] into a byte array.
    pub const fn bytes(&self) -> [u8; Self::LEN] {
        self.0.to_be_bytes()
    }

    /// Attempts to convert a byte slice into a [CardStatus].
    pub const fn try_from_bytes(val: &[u8]) -> Result<Self> {
        match val.len() {
            len if len < Self::LEN => Err(Error::invalid_length(len, Self::LEN)),
            _ => Ok(Self::from_bits(u16::from_be_bytes([val[0], val[1]]))),
        }
    }
}

impl Default for CardStatus {
    fn default() -> Self {
        Self::new()
    }
}

impl From<u16> for CardStatus {
    fn from(val: u16) -> Self {
        Self::from_bits(val)
    }
}

impl From<CardStatus> for u16 {
    fn from(val: CardStatus) -> Self {
        val.bits()
    }
}

impl From<CardStatus> for [u8; CardStatus::LEN] {
    fn from(val: CardStatus) -> Self {
        val.bytes()
    }
}

impl TryFrom<&[u8]> for CardStatus {
    type Error = Error;

    fn try_from(val: &[u8]) -> Result<Self> {
        Self::try_from_bytes(val)
    }
}

impl<const N: usize> TryFrom<&[u8; N]> for CardStatus {
    type Error = Error;

    fn try_from(val: &[u8; N]) -> Result<Self> {
        Self::try_from_bytes(val.as_ref())
    }
}

impl<const N: usize> TryFrom<[u8; N]> for CardStatus {
    type Error = Error;

    fn try_from(val: [u8; N]) -> Result<Self> {
        Self::try_from_bytes(val.as_ref())
    }
}

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

    #[test]
    fn test_fields() {
        let mut cs = CardStatus::new();

        test_field!(cs, crc_error: 15);
        test_field!(cs, illegal_command: 14);
        test_field!(cs, error: 13);
    }
}