sdmmc-core 0.5.0

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

/// Represents the byte length of the [ManufacturingDate].
pub const MDT_LEN: usize = 2;

const MDT_MASK: u16 = 0xfff;

const MONTH_MASK: u16 = 0xf;

const YEAR_MASK: u16 = 0xff0;
const YEAR_SHIFT: usize = 4;

mod month;
mod year;

pub use month::*;
pub use year::*;

/// Represents the manufacturing date field of the `CID` register.
///
/// Contains a 4-bit month field, and 8-bit year field (starting in 2000).
#[repr(C)]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct ManufacturingDate(u16);

impl ManufacturingDate {
    /// Creates a new [ManufacturingDate].
    pub const fn new() -> Self {
        Self(1)
    }

    /// Attempt to get the [Month] field of the [ManufacturingDate].
    pub const fn month(&self) -> Result<Month> {
        Month::try_from_bits((self.0 & MONTH_MASK) as u8)
    }

    /// Sets the [Month] field of the [ManufacturingDate].
    pub fn set_month(&mut self, val: Month) {
        self.0 = (self.0 & !MONTH_MASK) | (val.bits() as u16);
    }

    /// Gets the [Year] field of the [ManufacturingDate].
    pub const fn year(&self) -> Year {
        Year::from_bits(((self.0 & YEAR_MASK) >> YEAR_SHIFT) as u8)
    }

    /// Sets the [Year] field of the [ManufacturingDate].
    pub fn set_year(&mut self, val: Year) {
        self.0 = (self.0 & !YEAR_MASK) | ((val.bits() as u16) << YEAR_SHIFT);
    }

    /// Gets the bit value of the [ManufacturingDate].
    pub const fn bits(&self) -> u16 {
        self.0
    }

    /// Attempts to convert a [`u16`] into a [ManufacturingDate].
    pub const fn try_from_bits(val: u16) -> Result<Self> {
        match (val, Month::try_from_bits((val & MONTH_MASK) as u8)) {
            (v, _) if (v & !MDT_MASK) != 0 => Err(Error::InvalidVariant(val as usize)),
            (_, Err(err)) => Err(err),
            (_, Ok(_)) => Ok(Self(val)),
        }
    }

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

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

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