sdmmc-core 0.5.0

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

lib_bitfield! {
    /// Response sent by every command except `SEND_STATUS` in SDIO mode.
    pub R1(u8): u8 {
        /// Card is in idle state and running intializing process.
        pub idle: 0;
        /// An illegal command code detected.
        pub illegal_command: 2;
        /// A communication CRC check failed.
        pub crc_error: 3;
        /// A function number error occurred.
        pub function_number_error: 4;
        /// Invalid command argument.
        pub parameter_error: 6;
    }
}

response! {
    R1 {
        response_mode: Sdio,
    }
}

impl R1 {
    /// Represents the Reserved for Future Use (RFU, always zero) bits.
    pub const MASK: u8 = 0b1010_0010;
    /// Represents the default value of the [R1].
    pub const DEFAULT: u8 = 0;

    /// Creates a new [R1].
    pub const fn new() -> Self {
        Self(Self::DEFAULT)
    }

    /// Attempts to convert a [`u8`] into a [R1].
    pub const fn try_from_bits(val: u8) -> Result<Self> {
        match val {
            v if (v & Self::MASK) != 0 => Err(Error::invalid_field_variant("r1", val as usize)),
            v => Ok(Self(v)),
        }
    }
}

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

impl TryFrom<u8> for R1 {
    type Error = Error;

    fn try_from(val: u8) -> Result<Self> {
        Self::try_from_bits(val)
    }
}

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

    #[test]
    fn test_fields() {
        let mut r1 = R1::new();

        test_field!(r1, idle: 0);
        test_field!(r1, illegal_command: 2);
        test_field!(r1, crc_error: 3);
        test_field!(r1, function_number_error: 4);
        test_field!(r1, parameter_error: 6);

        (0..=u8::MAX).for_each(|v| match v {
            v if (v & R1::MASK) != 0 => {
                let exp_err = Error::invalid_field_variant("r1", v as usize);
                assert_eq!(R1::try_from_bits(v), Err(exp_err));
                assert_eq!(R1::try_from(v), Err(exp_err));
            }
            _ => {
                r1 = R1(v);

                assert_eq!(R1::try_from_bits(v), Ok(r1));
                assert_eq!(R1::try_from(v), Ok(r1));
            }
        });
    }
}