Simplify the call to from_be_bytes?
⚓ Rust 📅 2026-01-30 👤 surdeus 👁️ 10I'm reading data from a fingerprint scanner, and it have different size packages depending on what command it was sent..
The simpler ones are:
let start = u16::from_be_bytes([self.buffer[0], self.buffer[1]]);
However, this is really getting out of hand:
fpm_model: u128::from_be_bytes([
self.buffer[10],
self.buffer[11],
self.buffer[12],
self.buffer[13],
self.buffer[14],
self.buffer[15],
self.buffer[16],
self.buffer[17],
self.buffer[18],
self.buffer[19],
self.buffer[20],
self.buffer[21],
self.buffer[22],
self.buffer[23],
self.buffer[24],
self.buffer[25],
]),
Looking through examples, this should be possible:
let start = u16::from_be_bytes(self.buffer[0..1].try_into().unwrap());
which would making the retrieval of that FPM model real easy:
fpm_model = u128::from_be_bytes(self.buffer[10..25].try_into().unwrap());
The code would be soooo simpler, easier to read, and more importantly, easier to write
. Because I have quite a number of those big ones left to do..
However, that first one gives me a panic! It compiles fine, but then panics:
called `Result::unwrap()` on an `Err` value: TryFromSliceError(())
The buffer variable is defined in my constructor as:
buffer: heapless::Vec::new()
I've gone over the heapless::Vec, slices, vec's and whatever else docs I could find, but can't find anything that seem .. resonable and usable.
4 posts - 3 participants
🏷️ Rust_feed