multiversx_sc_codec/single/
nested_de_input_slice.rs

1use crate::{DecodeError, DecodeErrorHandler, NestedDecode, NestedDecodeInput};
2
3/// A nested decode buffer implementation on referenced data.
4impl NestedDecodeInput for &[u8] {
5    fn remaining_len(&self) -> usize {
6        self.len()
7    }
8
9    fn peek_into<H>(&mut self, into: &mut [u8], h: H) -> Result<(), H::HandledErr>
10    where
11        H: DecodeErrorHandler,
12    {
13        if into.len() > self.len() {
14            return Err(h.handle_error(DecodeError::INPUT_TOO_SHORT));
15        }
16        let len = into.len();
17        into.copy_from_slice(&self[..len]);
18        Ok(())
19    }
20
21    fn read_into<H>(&mut self, into: &mut [u8], h: H) -> Result<(), H::HandledErr>
22    where
23        H: DecodeErrorHandler,
24    {
25        self.peek_into(into, h)?;
26        *self = &self[into.len()..];
27        Ok(())
28    }
29}
30
31/// Convenience method, to avoid having to specify type when calling `dep_decode`.
32/// Especially useful in the macros.
33/// Also checks that the entire slice was used.
34/// The input doesn't need to be mutable because we are not changing the underlying data.
35pub fn dep_decode_from_byte_slice<T, H>(input: &[u8], h: H) -> Result<T, H::HandledErr>
36where
37    T: NestedDecode,
38    H: DecodeErrorHandler,
39{
40    let mut_slice = &mut &*input;
41    let result = T::dep_decode_or_handle_err(mut_slice, h)?;
42    if !mut_slice.is_empty() {
43        return Err(h.handle_error(DecodeError::INPUT_TOO_LONG));
44    }
45    Ok(result)
46}