• Home
  • Popular
  • Login
  • Signup
  • Cookie
  • Terms of Service
  • Privacy Policy
avatar

Posted by John Dev


10 Jan, 2025

Updated at 20 Jan, 2025

{int}::from_{end}_bytes: have I missed a tidier way?

Suppose you have a large byte buffer containing some sort of data packet and you're pulling fields out one at a time. The from_{endianness}_bytes methods on the primitive numeric types seem like they're made for this, but they take fixed-size array arguments -- reasonably enough, it wouldn't make sense to call e.g. u32::from_le_bytes with anything other than four bytes -- and going from a (sub)slice to a fixed-size array is awkward. I find myself writing a lot of helper functions like

use std::mem::size_of;
fn u32_le_at_offset(buf: &[u8], offset: usize) -> Option<u32> {
    let field = buf.get(offset .. offset + size_of::<u32>())?;
    Some(u32::from_le_bytes(field.try_into().unwrap()))
}

This works, and the compiler can optimize out the try_into and unwrap, but it's ugly. And it makes me feel like I must've missed something somewhere in std that would let me do it with less ceremony... Have I missed something?

4 posts - 3 participants

Read full topic