multiversx_sc_codec/single/
nested_de.rs

1// use core::ops::Try;
2
3use crate::{codec_err::DecodeError, DecodeErrorHandler, DefaultErrorHandler, NestedDecodeInput};
4
5/// Trait that allows zero-copy read of value-references from slices in LE format.
6pub trait NestedDecode: Sized {
7    /// Attempt to deserialise the value from input,
8    /// using the format of an object nested inside another structure.
9    /// In case of success returns the deserialized value and the number of bytes consumed during the operation.
10    fn dep_decode<I: NestedDecodeInput>(input: &mut I) -> Result<Self, DecodeError> {
11        Self::dep_decode_or_handle_err(input, DefaultErrorHandler)
12    }
13
14    /// Version of `dep_decode` that can handle errors as soon as they occur.
15    /// For instance in can exit immediately and make sure that if it returns, it is a success.
16    /// By not deferring error handling, this can lead to somewhat smaller bytecode.
17    fn dep_decode_or_handle_err<I, H>(input: &mut I, h: H) -> Result<Self, H::HandledErr>
18    where
19        I: NestedDecodeInput,
20        H: DecodeErrorHandler,
21    {
22        match Self::dep_decode(input) {
23            Ok(v) => Ok(v),
24            Err(e) => Err(h.handle_error(e)),
25        }
26    }
27
28    /// Allows the framework to do monomorphisation of special cases where the data is of type `u8`.
29    ///
30    /// Especially useful for deserializing byte arrays.
31    ///
32    /// Working with this also involves transmuting low-level data. Only use if you really know what you are doing!
33    #[doc(hidden)]
34    #[allow(unused_variables)]
35    fn if_u8<Input, If, Else, R>(input: Input, if_branch: If, else_branch: Else) -> R
36    where
37        If: FnOnce(Input) -> R,
38        Else: FnOnce(Input) -> R,
39    {
40        else_branch(input)
41    }
42}