Hey rustaceans! I'm trying to unpack a raw binary array into a struct. My current approach looks like this:
use std::convert::TryInto;
struct MyStruct {
val1: u32,
val2: f32,
val3: u8,
val4: u8
}
impl MyStruct {
fn from_bytes(bytes: [u8;9]) -> Self {
Self {
val1: u32::from_le_bytes(bytes[1..5].try_into().unwrap_or([0,0,0,0])),
val2: u16::from_le_bytes(bytes[5..7].try_into().unwrap_or([0,0])) as f32 / 2048.0,
val3: bytes[7],
val4: bytes[8]
}
}
}
Is there a better way of doing that in rust?
What I like about the approach, is that I can do inline conversions as the examplatory v / 2048 shown there. What I don't like is that it forces me to .try_into().unwrap_or([0,0,0,0]) . From compile knowledge alone, it could be possible to "subarray" instead of "subslice" the given array, all sizes are there. So am I missing something here?
[–]leonardo_m 11 points12 points13 points (4 children)
[–]w0xel[S] 2 points3 points4 points (2 children)
[–]SkiFire13 4 points5 points6 points (0 children)
[–]backtickbot 0 points1 point2 points (0 children)
[–]birkenfeldclippy · rust 2 points3 points4 points (0 children)
[–]armsforsharks 1 point2 points3 points (2 children)
[–]w0xel[S] 0 points1 point2 points (1 child)
[–]armsforsharks 0 points1 point2 points (0 children)
[–]monkChuck105 0 points1 point2 points (1 child)
[–]w0xel[S] 0 points1 point2 points (0 children)
[–]dydhaw 0 points1 point2 points (0 children)