multiversx_sc_codec/single/
nested_de_input_owned.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
use alloc::boxed::Box;

use crate::{DecodeError, DecodeErrorHandler, NestedDecodeInput};

/// A nested decode buffer that owns its data.
pub struct OwnedBytesNestedDecodeInput {
    bytes: Box<[u8]>,
    decode_index: usize,
}

impl OwnedBytesNestedDecodeInput {
    pub fn new(bytes: Box<[u8]>) -> Self {
        OwnedBytesNestedDecodeInput {
            bytes,
            decode_index: 0,
        }
    }

    fn perform_read_into(&mut self, into: &mut [u8]) {
        let len = into.len();
        into.copy_from_slice(&self.bytes[self.decode_index..self.decode_index + len]);
    }
}

impl NestedDecodeInput for OwnedBytesNestedDecodeInput {
    fn remaining_len(&self) -> usize {
        self.bytes.len() - self.decode_index
    }

    fn peek_into<H>(&mut self, into: &mut [u8], h: H) -> Result<(), H::HandledErr>
    where
        H: DecodeErrorHandler,
    {
        if into.len() > self.remaining_len() {
            return Err(h.handle_error(DecodeError::INPUT_TOO_SHORT));
        }
        self.perform_read_into(into);
        Ok(())
    }

    fn read_into<H>(&mut self, into: &mut [u8], h: H) -> Result<(), H::HandledErr>
    where
        H: DecodeErrorHandler,
    {
        self.peek_into(into, h)?;
        self.decode_index += into.len();
        Ok(())
    }
}