Skip to content

Commit 2ca4eb7

Browse files
committed
Add From and TryFrom implementations for Data
1 parent edd44a6 commit 2ca4eb7

1 file changed

Lines changed: 34 additions & 0 deletions

File tree

src/frame/data.rs

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,40 @@ impl<'d> Data<'d> {
6060
}
6161
}
6262

63+
/// The buffer has an invalid size (must be a non null multiple of 2).
64+
pub struct DataFromBufferError;
65+
66+
impl<'buffer> TryFrom<&'buffer [u8]> for Data<'buffer> {
67+
type Error = DataFromBufferError;
68+
69+
fn try_from(value: &'buffer [u8]) -> Result<Self, Self::Error> {
70+
if value.is_empty() || value.len() % 2 != 0 {
71+
Err(DataFromBufferError)
72+
} else {
73+
Ok(Self {
74+
data: value,
75+
quantity: value.len() / 2,
76+
})
77+
}
78+
}
79+
}
80+
81+
macro_rules! derive_from_for_data {
82+
($($buffer_length: literal)+) => {
83+
$(
84+
impl<'buffer> From<&'buffer [u8; $buffer_length]> for Data<'buffer> {
85+
fn from(value: &'buffer [u8; $buffer_length]) -> Self {
86+
Self {
87+
data: value,
88+
quantity: $buffer_length / 2,
89+
}
90+
}
91+
}
92+
)+
93+
};
94+
}
95+
derive_from_for_data!(2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32);
96+
6397
/// Data iterator
6498
// TODO: crate a generic iterator
6599
#[cfg_attr(all(feature = "defmt", target_os = "none"), derive(defmt::Format))]

0 commit comments

Comments
 (0)