sdmmc-core 0.5.0

SD/MMC core data structures and algorithms
Documentation
use crate::result::Result;

use super::{DataSectorSize, ExtCsd, ExtCsdIndex};

/// Represents the `ENH_START_ADDR` of the [ExtCsd] register.
#[repr(C)]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct EnhancedUserDataStartAddress(u32);

impl EnhancedUserDataStartAddress {
    /// Represents the default byte value of the [EnhancedUserDataStartAddress].
    pub const DEFAULT: u32 = 0;

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

    /// Converts a [`u32`] into a [EnhancedUserDataStartAddress].
    pub const fn from_inner(val: u32) -> Self {
        Self(val)
    }

    /// Attempts to convert an inner representation into a [EnhancedUserDataStartAddress].
    pub const fn try_from_inner(val: u32) -> Result<Self> {
        Ok(Self::from_inner(val))
    }

    /// Converts a [EnhancedUserDataStartAddress] into a [`u32`].
    pub const fn into_inner(self) -> u32 {
        self.0
    }
}

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

impl From<u32> for EnhancedUserDataStartAddress {
    fn from(val: u32) -> Self {
        Self::from_inner(val)
    }
}

impl From<EnhancedUserDataStartAddress> for u32 {
    fn from(val: EnhancedUserDataStartAddress) -> Self {
        val.into_inner()
    }
}

impl ExtCsd {
    /// Gets the `ENH_START_ADDR` field of the [ExtCsd].
    pub const fn enh_start_addr(&self) -> EnhancedUserDataStartAddress {
        EnhancedUserDataStartAddress::from_inner(u32::from_le_bytes([
            self.0[ExtCsdIndex::ENH_START_ADDR_START],
            self.0[ExtCsdIndex::ENH_START_ADDR_START + 1],
            self.0[ExtCsdIndex::ENH_START_ADDR_START + 2],
            self.0[ExtCsdIndex::ENH_START_ADDR_END],
        ]))
    }

    /// Sets the `ENH_START_ADDR` field of the [ExtCsd].
    pub fn set_enh_start_addr(&mut self, val: EnhancedUserDataStartAddress) {
        let [b0, b1, b2, b3] = val.into_inner().to_le_bytes();

        self.0[ExtCsdIndex::ENH_START_ADDR_START] = b0;
        self.0[ExtCsdIndex::ENH_START_ADDR_START + 1] = b1;
        self.0[ExtCsdIndex::ENH_START_ADDR_START + 2] = b2;
        self.0[ExtCsdIndex::ENH_START_ADDR_END] = b3;
    }
}

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

    #[test]
    fn test_enh_start_addr() {
        let mut ext_csd = ExtCsd::new();

        assert_eq!(
            ext_csd.enh_start_addr(),
            EnhancedUserDataStartAddress::new()
        );

        (1..=u32::BITS)
            .map(|r| EnhancedUserDataStartAddress::from_inner(((1u64 << r) - 1) as u32))
            .for_each(|size| {
                ext_csd.set_enh_start_addr(size);
                assert_eq!(ext_csd.enh_start_addr(), size);
            });
    }
}