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