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