Skip to content
Snippets Groups Projects
arbitrary.rs 762 B
Newer Older
use arrayvec::ArrayVec;

#[derive(Debug, Clone)]
pub struct Arbitrary(pub ArrayVec<u8, 255>);

impl Arbitrary {
    pub fn new(data: &[u8]) -> Option<Self> {
        let mut av = ArrayVec::new();
        av.try_extend_from_slice(data).ok()?;

        Some(Self(av))
    }

    pub fn encode<'a>(&self, buf: &'a mut [u8]) -> Option<&'a [u8]> {
        let len = self.0.len();

        // length must be <= 255, so this is safe
        *buf.get_mut(0)? = len.try_into().unwrap();
        buf.get_mut(1..(len + 1))?.copy_from_slice(&self.0);

        Some(&buf[0..(len + 1)])
    }

    pub fn decode(data: &[u8]) -> Option<Self> {
        let len: usize = (*data.first()?).into();
        let content = data.get(1..(len + 1))?;

        Self::new(content)
    }
}