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