sdmmc_core/command/
null.rsuse crate::lib_bitfield;
use crate::result::{Error, Result};
lib_bitfield! {
pub Argument(u32): u32 {
inner: 31, 0;
}
}
impl Argument {
pub const LEN: usize = 4;
pub const fn new() -> Self {
Self(0)
}
pub const fn from_bits(val: u32) -> Self {
Self(val)
}
pub const fn try_from_bits(val: u32) -> Result<Self> {
Ok(Self::from_bits(val))
}
pub const fn bytes(&self) -> [u8; Self::LEN] {
self.0.to_be_bytes()
}
pub const fn try_from_bytes(val: &[u8]) -> Result<Self> {
match val.len() {
len if len < Self::LEN => Err(Error::invalid_length(len, Self::LEN)),
_ => Ok(Self(u32::from_be_bytes([val[0], val[1], val[2], val[3]]))),
}
}
}
impl Default for Argument {
fn default() -> Self {
Self::new()
}
}
impl From<u32> for Argument {
fn from(val: u32) -> Self {
Self::from_bits(val)
}
}
impl From<Argument> for u32 {
fn from(val: Argument) -> Self {
val.bits()
}
}
impl From<Argument> for [u8; Argument::LEN] {
fn from(val: Argument) -> Self {
val.bytes()
}
}
impl TryFrom<&[u8]> for Argument {
type Error = Error;
fn try_from(val: &[u8]) -> Result<Self> {
Self::try_from_bytes(val)
}
}
impl<const N: usize> TryFrom<&[u8; N]> for Argument {
type Error = Error;
fn try_from(val: &[u8; N]) -> Result<Self> {
Self::try_from_bytes(val.as_ref())
}
}
impl<const N: usize> TryFrom<[u8; N]> for Argument {
type Error = Error;
fn try_from(val: [u8; N]) -> Result<Self> {
Self::try_from_bytes(val.as_ref())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_fields() {
(1..u32::BITS)
.map(|r| ((1u64 << r) - 1) as u32)
.for_each(|raw_arg| {
let mut exp_arg = Argument(raw_arg);
let raw = raw_arg.to_be_bytes();
assert_eq!(Argument::from_bits(raw_arg), exp_arg);
assert_eq!(Argument::try_from_bytes(&raw), Ok(exp_arg));
assert_eq!(Argument::try_from(&raw), Ok(exp_arg));
assert_eq!(Argument::try_from(raw), Ok(exp_arg));
assert_eq!(exp_arg.bits(), raw_arg);
assert_eq!(exp_arg.bytes(), raw);
});
}
}