sdmmc-core 0.5.0

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

use super::{ExtCsd, ExtCsdIndex};

/// Represents the `MAX_CONTEXT_ID` sub-field of the `CONTEXT_CAPABILITIES` field.
pub type MaxContextId = RangeU8<5, 0xf>;

lib_bitfield! {
    /// Represents the `LARGE_UNIT_MAX_MULTIPLIER_M1` sub-field of the `CONTEXT_CAPABILITIES` field.
    LargeUnitMaxMultiplierM1: u8,
    mask: 0x7,
    default: 5,
    {
        /// Represents the highest multiplier for `Large Unit` contexts.
        large_unit_max_multiplier_m1: 2, 0;
    }
}

impl LargeUnitMaxMultiplierM1 {
    /// Gets the maximum multiplier for `Large Unit` contexts.
    ///
    /// # Note
    ///
    /// The maximum multiplier is calculated with the algorithm:
    ///
    /// ```no_build,no_run
    /// multiplier = LARGE_UNIT_MAX_MULTIPLIER_M1 + 1
    /// ```
    pub const fn max_multiplier(&self) -> u8 {
        self.large_unit_max_multiplier_m1() + 1
    }
}

lib_bitfield! {
    /// Represents the `CONTEXT_CAPABILITIES` field of the [ExtCsd] register.
    ContextCapabilities: u8,
    mask: 0x7f,
    default: 5,
    {
        /// Represents the maximum multipler (minus 1) for `Large Unit` contexts.
        large_unit_max_multiplier_m1: LargeUnitMaxMultiplierM1, 6, 4;
        /// Represents the maximum context ID number.
        max_context_id: MaxContextId, 3, 0;
    }
}

impl ExtCsd {
    /// Gets the `CONTEXT_CAPABILITIES` field of the [ExtCsd] register.
    pub const fn context_capabilities(&self) -> Result<ContextCapabilities> {
        ContextCapabilities::try_from_inner(self.0[ExtCsdIndex::ContextCapabilities.into_inner()])
    }

    /// Sets the `CONTEXT_CAPABILITIES` field of the [ExtCsd] register.
    pub(crate) fn set_context_capabilities(&mut self, val: ContextCapabilities) {
        self.0[ExtCsdIndex::ContextCapabilities.into_inner()] = val.into_inner();
    }
}

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

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

        ext_csd.set_context_capabilities(ContextCapabilities::new());
        assert_eq!(
            ext_csd.context_capabilities(),
            Ok(ContextCapabilities::new())
        );

        (0..=u8::MAX).for_each(|raw_cc| {
            // set a potentially invalid ContextCapabilities
            ext_csd.set_context_capabilities(ContextCapabilities(raw_cc));

            match ContextCapabilities::try_from_inner(raw_cc) {
                Ok(cc) => assert_eq!(ext_csd.context_capabilities(), Ok(cc)),
                Err(err) => assert_eq!(ext_csd.context_capabilities(), Err(err)),
            }
        });
    }
}