sdmmc_core/command/
null.rs1use crate::lib_bitfield;
2use crate::result::{Error, Result};
3
4lib_bitfield! {
5 pub Argument(u32): u32 {
7 inner: 31, 0;
8 }
9}
10
11impl Argument {
12 pub const LEN: usize = 4;
14
15 pub const fn new() -> Self {
17 Self(0)
18 }
19
20 pub const fn from_bits(val: u32) -> Self {
22 Self(val)
23 }
24
25 pub const fn try_from_bits(val: u32) -> Result<Self> {
27 Ok(Self::from_bits(val))
28 }
29
30 pub const fn bytes(&self) -> [u8; Self::LEN] {
32 self.0.to_be_bytes()
33 }
34
35 pub const fn try_from_bytes(val: &[u8]) -> Result<Self> {
37 match val.len() {
38 len if len < Self::LEN => Err(Error::invalid_length(len, Self::LEN)),
39 _ => Ok(Self(u32::from_be_bytes([val[0], val[1], val[2], val[3]]))),
40 }
41 }
42}
43
44impl Default for Argument {
45 fn default() -> Self {
46 Self::new()
47 }
48}
49
50impl From<u32> for Argument {
51 fn from(val: u32) -> Self {
52 Self::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 mut exp_arg = Argument(raw_arg);
102 let raw = raw_arg.to_be_bytes();
103
104 assert_eq!(Argument::from_bits(raw_arg), exp_arg);
105 assert_eq!(Argument::try_from_bytes(&raw), Ok(exp_arg));
106 assert_eq!(Argument::try_from(&raw), Ok(exp_arg));
107 assert_eq!(Argument::try_from(raw), Ok(exp_arg));
108
109 assert_eq!(exp_arg.bits(), raw_arg);
110 assert_eq!(exp_arg.bytes(), raw);
111 });
112 }
113}