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 `SLEEP_NOTIFICATION_TIME` field inner value.
pub type TimeoutValue = RangeU8<0, 0x17>;

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

impl SleepNotificationTimeout {
    /// Represents the timeout multiplier in microseconds.
    pub const TIMEOUT: u32 = 10;

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

impl ExtCsd {
    /// Gets the `SLEEP_NOTIFICATION_TIME` field of the [ExtCsd] register.
    pub const fn sleep_notification_time(&self) -> Result<SleepNotificationTimeout> {
        SleepNotificationTimeout::try_from_inner(
            self.0[ExtCsdIndex::SleepNotificationTime.into_inner()],
        )
    }

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

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

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

        assert_eq!(
            ext_csd.sleep_notification_time(),
            Ok(SleepNotificationTimeout::new())
        );

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

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