multiversx_sc_codec/single/
nested_de_input_owned.rs

1use alloc::boxed::Box;
2
3use crate::{DecodeError, DecodeErrorHandler, NestedDecodeInput};
4
5/// A nested decode buffer that owns its data.
6pub struct OwnedBytesNestedDecodeInput {
7    bytes: Box<[u8]>,
8    decode_index: usize,
9}
10
11impl OwnedBytesNestedDecodeInput {
12    pub fn new(bytes: Box<[u8]>) -> Self {
13        OwnedBytesNestedDecodeInput {
14            bytes,
15            decode_index: 0,
16        }
17    }
18
19    fn perform_read_into(&mut self, into: &mut [u8]) {
20        let len = into.len();
21        into.copy_from_slice(&self.bytes[self.decode_index..self.decode_index + len]);
22    }
23}
24
25impl NestedDecodeInput for OwnedBytesNestedDecodeInput {
26    fn remaining_len(&self) -> usize {
27        self.bytes.len() - self.decode_index
28    }
29
30    fn peek_into<H>(&mut self, into: &mut [u8], h: H) -> Result<(), H::HandledErr>
31    where
32        H: DecodeErrorHandler,
33    {
34        if into.len() > self.remaining_len() {
35            return Err(h.handle_error(DecodeError::INPUT_TOO_SHORT));
36        }
37        self.perform_read_into(into);
38        Ok(())
39    }
40
41    fn read_into<H>(&mut self, into: &mut [u8], h: H) -> Result<(), H::HandledErr>
42    where
43        H: DecodeErrorHandler,
44    {
45        self.peek_into(into, h)?;
46        self.decode_index += into.len();
47        Ok(())
48    }
49}