sdmmc_core/command/class/class5/cmd36/
arg.rs1use crate::lib_bitfield;
2use crate::result::{Error, Result};
3
4lib_bitfield! {
5 pub Argument(u32): u32 {
7 pub data_address: 31, 0;
9 }
10}
11
12impl Argument {
13 pub const LEN: usize = 4;
15 pub const DEFAULT: u32 = 0;
17
18 pub const fn new() -> Self {
20 Self(Self::DEFAULT)
21 }
22
23 pub const fn from_bits(val: u32) -> Self {
25 Self(val)
26 }
27
28 pub const fn try_from_bits(val: u32) -> Result<Self> {
30 Ok(Self::from_bits(val))
31 }
32
33 pub const fn bytes(&self) -> [u8; Self::LEN] {
35 self.0.to_be_bytes()
36 }
37
38 pub const fn try_from_bytes(val: &[u8]) -> Result<Self> {
40 match val.len() {
41 len if len < Self::LEN => Err(Error::invalid_length(len, Self::LEN)),
42 _ => Self::try_from_bits(u32::from_be_bytes([val[0], val[1], val[2], val[3]])),
43 }
44 }
45}
46
47impl Default for Argument {
48 fn default() -> Self {
49 Self::new()
50 }
51}
52
53impl From<Argument> for u32 {
54 fn from(val: Argument) -> Self {
55 val.bits()
56 }
57}
58
59impl From<Argument> for [u8; Argument::LEN] {
60 fn from(val: Argument) -> Self {
61 val.bytes()
62 }
63}
64
65impl TryFrom<u32> for Argument {
66 type Error = Error;
67
68 fn try_from(val: u32) -> Result<Self> {
69 Self::try_from_bits(val)
70 }
71}
72
73impl TryFrom<&[u8]> for Argument {
74 type Error = Error;
75
76 fn try_from(val: &[u8]) -> Result<Self> {
77 Self::try_from_bytes(val)
78 }
79}
80
81impl<const N: usize> TryFrom<&[u8; N]> for Argument {
82 type Error = Error;
83
84 fn try_from(val: &[u8; N]) -> Result<Self> {
85 Self::try_from_bytes(val.as_ref())
86 }
87}
88
89impl<const N: usize> TryFrom<[u8; N]> for Argument {
90 type Error = Error;
91
92 fn try_from(val: [u8; N]) -> Result<Self> {
93 Self::try_from_bytes(val.as_ref())
94 }
95}
96
97#[cfg(test)]
98mod tests {
99 use super::*;
100
101 #[test]
102 fn test_fields() {
103 (1..=u32::BITS)
104 .map(|r| ((1u64 << r) - 1) as u32)
105 .for_each(|raw_arg| {
106 let raw = raw_arg.to_be_bytes();
107 let exp_addr = raw_arg;
108 let mut exp_arg = Argument(raw_arg);
109
110 assert_eq!(Argument::try_from_bits(raw_arg), Ok(exp_arg));
111 assert_eq!(Argument::try_from_bytes(raw.as_ref()), Ok(exp_arg));
112 assert_eq!(Argument::try_from(raw_arg), Ok(exp_arg));
113 assert_eq!(Argument::try_from(raw), Ok(exp_arg));
114 assert_eq!(Argument::try_from(&raw), Ok(exp_arg));
115
116 assert_eq!(exp_arg.bits(), raw_arg);
117 assert_eq!(exp_arg.bytes(), raw);
118
119 assert_eq!(exp_arg.data_address(), exp_addr);
120
121 exp_arg.set_data_address(0);
122 assert_eq!(exp_arg.data_address(), 0);
123
124 exp_arg.set_data_address(exp_addr);
125 assert_eq!(exp_arg.data_address(), exp_addr);
126 });
127 }
128}