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