bincode icon indicating copy to clipboard operation
bincode copied to clipboard

`bincode::decode_whole`?

Open dpc opened this issue 6 months ago • 0 comments

As a user of bincode, 99% of the time when I'm decoding something it's a whole message and I don't want to know how many bytes were read, but just get an error if not all bytes were consumed (to reject unexpected extra bytes).

I have:

pub fn decode_whole<D: de::Decode<()>, C: Config>(
    src: &[u8],
    config: C,
) -> Result<D, error::DecodeError> {
    let (t, consumed) = bincode::decode_from_slice(src, config)?;

    if consumed != src.len() {
        return Err(bincode::error::DecodeError::Other("leftover bytes"));
    }

    Ok(t)
}

helper, but it's just ... weird to have it as an extra function, that I need to remember to use (all need to remember during reviews for AI or other devs to use it), etc.

BTW. in some custom encoding Rust schemeds kind of like bincode I've used in some other project, we eventually added _partial suffix to all decoding functions that did not error-out on unconsumed bytes, precisely because we've noticed that users were too often not noticing that they ignore extra bytes, which could introduce security issues. But anyway, probably too late now to rename anything in bincode. Just having a standard "decode whole" function for slices would be nice.

dpc avatar Jun 07 '25 01:06 dpc