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