commonware_codec/
util.rs

1//! Codec utility functions
2
3use crate::{extensions::ReadExt as _, Error};
4use bytes::Buf;
5
6/// Checks if the buffer has at least `len` bytes remaining. Returns an [Error::EndOfBuffer] if not.
7#[inline]
8pub fn at_least<B: Buf>(buf: &mut B, len: usize) -> Result<(), Error> {
9    let rem = buf.remaining();
10    if rem < len {
11        return Err(Error::EndOfBuffer);
12    }
13    Ok(())
14}
15
16/// Ensures the next `size` bytes are all zeroes in the provided buffer, returning an [Error]
17/// otherwise.
18#[inline]
19pub fn ensure_zeros<B: Buf>(buf: &mut B, size: usize) -> Result<(), Error> {
20    for _ in 0..size {
21        if u8::read(buf)? != 0 {
22            return Err(Error::Invalid("codec", "non-zero bytes"));
23        }
24    }
25    Ok(())
26}