multiversx_sc_codec/multi/
top_de_multi_input.rs

1use alloc::{boxed::Box, vec::Vec};
2
3use crate::{DecodeError, DecodeErrorHandler, TopDecode, TopDecodeInput};
4
5pub trait TopDecodeMultiInput: Sized {
6    type ValueInput: TopDecodeInput;
7
8    /// Check if there are more arguments that can be loaded.
9    fn has_next(&self) -> bool;
10
11    /// Retrieves an input for deserializing an argument.
12    /// If the loader is out of arguments, it will crash by itself with an appropriate error,
13    /// without returning.
14    /// Use if the next argument is optional, use `has_next` beforehand.
15    fn next_value_input<H>(&mut self, h: H) -> Result<Self::ValueInput, H::HandledErr>
16    where
17        H: DecodeErrorHandler;
18
19    fn next_value<T, H>(&mut self, h: H) -> Result<T, H::HandledErr>
20    where
21        T: TopDecode,
22        H: DecodeErrorHandler,
23    {
24        T::top_decode_or_handle_err(self.next_value_input(h)?, h)
25    }
26
27    /// Called after retrieving all arguments to validate that extra arguments were not provided.
28    fn assert_no_more_args<H>(&self, h: H) -> Result<(), H::HandledErr>
29    where
30        H: DecodeErrorHandler,
31    {
32        if self.has_next() {
33            Err(h.handle_error(DecodeError::MULTI_TOO_MANY_ARGS))
34        } else {
35            Ok(())
36        }
37    }
38
39    /// Consumes all inputs and ignores them.
40    /// After executing this, assert_no_more_args should not fail.
41    fn flush_ignore<H>(&mut self, h: H) -> Result<(), H::HandledErr>
42    where
43        H: DecodeErrorHandler,
44    {
45        while self.has_next() {
46            let _ = self.next_value_input(h)?;
47        }
48        Ok(())
49    }
50}
51
52impl TopDecodeMultiInput for Vec<Vec<u8>> {
53    type ValueInput = Box<[u8]>;
54
55    fn has_next(&self) -> bool {
56        !self.is_empty()
57    }
58
59    fn next_value_input<H>(&mut self, h: H) -> Result<Self::ValueInput, H::HandledErr>
60    where
61        H: DecodeErrorHandler,
62    {
63        if self.has_next() {
64            let first = core::mem::take(&mut self[0]);
65            let tail = self.split_off(1);
66            *self = tail;
67            Ok(first.into_boxed_slice())
68        } else {
69            Err(h.handle_error(DecodeError::MULTI_TOO_FEW_ARGS))
70        }
71    }
72}