parsenic/
writer.rs

1use crate::{error::FullError, result::FullResult, Write};
2
3/// [`Write`]r that writes to a [`slice`] of bytes
4#[derive(Debug)]
5pub struct Writer<'a>(&'a mut [u8]);
6
7impl<'a> Writer<'a> {
8    /// Create a new `Writer` into the provided growable `buffer`.
9    pub fn new(buffer: &'a mut [u8]) -> Self {
10        Self(buffer)
11    }
12
13    fn subslice<'b>(&mut self, len: usize) -> FullResult<&'b mut [u8]>
14    where
15        'a: 'b,
16    {
17        let slice;
18        let mut tmp: &'a mut [u8] = &mut [];
19
20        if let Some(remaining) = len.checked_sub(self.0.len()) {
21            if remaining != 0 {
22                return Err(FullError::from_remaining(remaining));
23            }
24        }
25
26        core::mem::swap(&mut tmp, &mut self.0);
27        (slice, self.0) = tmp.split_at_mut(len);
28
29        Ok(slice)
30    }
31}
32
33impl Write for Writer<'_> {
34    fn remaining(&self) -> Option<usize> {
35        Some(self.0.len())
36    }
37
38    fn take(&mut self, len: usize) -> FullResult<Self> {
39        Ok(Writer(self.subslice(len)?))
40    }
41
42    fn bytes(&mut self, bytes: impl AsRef<[u8]>) -> FullResult {
43        let bytes = bytes.as_ref();
44
45        self.subslice(bytes.len())
46            .map(|buf| buf.copy_from_slice(bytes))
47    }
48}