Skip to content

[codec] Add Zeroed type #1703

@BrendanChou

Description

@BrendanChou

A type that represents a sequence of zeroed bytes. Similar to [0; N] but required to be all-zeroes. Doesn't actually need to store the array, could just be a single usize instead. This is useful for padding or zeroing out a buffer. Should return an error on read_cfg(...) if the bytes are not zeroed

pub struct Zeroed {
    n: usize,
}

impl Zeroed {
    pub fn new(n: usize) -> Self {
        Self { n }
    }
}

impl Read for Zeroed {
    type Cfg = usize;

    fn read_cfg(buf: &mut impl Buf, n: &Self::Cfg) -> Result<Self, Error> {
        at_least(buf, *n)?;
        let mut bytes = vec![0; *n];
        buf.copy_to_slice(&mut bytes);
        if bytes.iter().any(|&b| b != 0) {
            return Err(Error::Invalid("Zeroed", "bytes are not zero"));
        }
        Ok(Self { n: *n })
    }
}

impl Write for Zeroed {
    fn write(&self, buf: &mut impl BufMut) {
        buf.put_bytes(0, self.n);
    }
}

impl EncodeSize for Zeroed {
    fn encode_size(&self) -> usize {
        self.n
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    Status

    Backlog

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions