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};

/// Convenience alias for the `S_A_TIMEOUT` field inner value.
pub type TimeoutValue = RangeU8<0, 0x17>;

lib_bitfield! {
    /// Represents the `S_A_TIMEOUT` field of the [ExtCsd] register.
    SleepAwakeTimeout: u8,
    mask: 0xff,
    default: 0,
    {
        /// Represents the base `S_A_TIMEOUT` value.
        sleep_notification_time: TimeoutValue, 7, 0;
    }
}

impl SleepAwakeTimeout {
    /// Represents the timeout multiplier in nanoseconds.
    pub const TIMEOUT: u32 = 100;

    /// Gets the sleep notification timeout value (in 100ns increments).
    ///
    /// # Note
    ///
    /// The timeout value is calculated with the algorithm:
    ///
    /// ```no_build,no_run
    /// timeout = 100ns * (2 ^ S_A_TIMEOUT)
    /// ```
    pub const fn timeout(&self) -> u32 {
        Self::TIMEOUT * (1u32 << self.into_inner())
    }
}

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

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

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

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

        assert_eq!(ext_csd.s_a_timeout(), Ok(SleepAwakeTimeout::new()));

        (0..u8::MAX).for_each(|raw_sleep| {
            // set a potentially invalid SleepAwakeTimeout
            ext_csd.0[ExtCsdIndex::SATimeout.into_inner()] = raw_sleep;

            match SleepAwakeTimeout::try_from_inner(raw_sleep) {
                Ok(sleep) => {
                    assert_eq!(ext_csd.s_a_timeout(), Ok(sleep));
                    assert_eq!(
                        sleep.timeout(),
                        SleepAwakeTimeout::TIMEOUT * (1u32 << raw_sleep)
                    );
                }
                Err(err) => assert_eq!(ext_csd.s_a_timeout(), Err(err)),
            }
        });
    }
}