Skip to main content

corevm_codec/
io.rs

1use alloc::vec::Vec;
2
3// Just use JAM codec i/o traits.
4pub use jam_codec::{Input, Output};
5
6pub(crate) struct SliceOutput<'a>(pub(crate) &'a mut [u8]);
7
8impl jam_codec::Output for SliceOutput<'_> {
9    fn write(&mut self, buf: &[u8]) {
10        let (slice, rest) = core::mem::take(&mut self.0).split_at_mut(buf.len());
11        slice.copy_from_slice(buf);
12        self.0 = rest;
13    }
14
15    fn push_byte(&mut self, byte: u8) {
16        let (slice, rest) = core::mem::take(&mut self.0).split_at_mut(1);
17        slice[0] = byte;
18        self.0 = rest;
19    }
20}
21
22/// A wrapper that implements [`Input`] for `Vec<u8>`.
23pub struct VecInput {
24    buf: Vec<u8>,
25    offset: usize,
26}
27
28impl VecInput {
29    /// Creates new input from the provided vector.
30    pub fn new(buf: Vec<u8>) -> Self {
31        Self { buf, offset: 0 }
32    }
33
34    /// Returns `true` if there are no remaining bytes left.
35    pub fn is_empty(&self) -> bool {
36        self.buf.len() == self.offset
37    }
38
39    /// Returns underlying vector.
40    pub fn into_inner(self) -> Vec<u8> {
41        self.buf
42    }
43}
44
45impl jam_codec::Input for VecInput {
46    fn remaining_len(&mut self) -> Result<Option<usize>, jam_codec::Error> {
47        Ok(Some(self.buf.len() - self.offset))
48    }
49
50    fn read_byte(&mut self) -> Result<u8, jam_codec::Error> {
51        let byte = self
52            .buf
53            .get(self.offset)
54            .copied()
55            .ok_or("Buffer overflow")?;
56        self.offset += 1;
57        Ok(byte)
58    }
59
60    fn read(&mut self, buf: &mut [u8]) -> Result<(), jam_codec::Error> {
61        let len = buf.len();
62        let slice = &self
63            .buf
64            .get(self.offset..self.offset + len)
65            .ok_or("Buffer overflow")?;
66        buf.copy_from_slice(slice);
67        self.offset += len;
68        Ok(())
69    }
70}