multiversx_sc_codec/multi/
top_en_multi.rs

1use crate::{
2    DefaultErrorHandler, EncodeError, EncodeErrorHandler, TopEncode, TopEncodeMultiOutput,
3};
4
5pub trait TopEncodeMulti: Sized {
6    /// Attempt to serialize the value to ouput.
7    fn multi_encode<O>(&self, output: &mut O) -> Result<(), EncodeError>
8    where
9        O: TopEncodeMultiOutput,
10    {
11        self.multi_encode_or_handle_err(output, DefaultErrorHandler)
12    }
13
14    /// Version of `top_encode` 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 multi_encode_or_handle_err<O, H>(&self, output: &mut O, h: H) -> Result<(), H::HandledErr>
18    where
19        O: TopEncodeMultiOutput,
20        H: EncodeErrorHandler,
21    {
22        match self.multi_encode(output) {
23            Ok(()) => Ok(()),
24            Err(e) => Err(h.handle_error(e)),
25        }
26    }
27}
28
29/// All single top encode types also work as multi-value encode types.
30impl<T> TopEncodeMulti for T
31where
32    T: TopEncode,
33{
34    fn multi_encode_or_handle_err<O, H>(&self, output: &mut O, h: H) -> Result<(), H::HandledErr>
35    where
36        O: TopEncodeMultiOutput,
37        H: EncodeErrorHandler,
38    {
39        output.push_single_value(self, h)
40    }
41}
42
43pub fn multi_encode_iter_or_handle_err<T, Iter, O, H>(
44    iterator: Iter,
45    output: &mut O,
46    h: H,
47) -> Result<(), H::HandledErr>
48where
49    T: TopEncodeMulti,
50    Iter: Iterator<Item = T>,
51    O: TopEncodeMultiOutput,
52    H: EncodeErrorHandler,
53{
54    for item in iterator {
55        item.multi_encode_or_handle_err(output, h)?;
56    }
57    Ok(())
58}