multiversx_sc_codec/single/
top_en.rs

1use crate::{
2    codec_err::EncodeError, DefaultErrorHandler, EncodeErrorHandler, NestedEncode,
3    PanicErrorHandler, TopEncodeOutput,
4};
5use alloc::vec::Vec;
6use unwrap_infallible::UnwrapInfallible;
7
8pub trait TopEncode: Sized {
9    /// Attempt to serialize the value to ouput.
10    fn top_encode<O>(&self, output: O) -> Result<(), EncodeError>
11    where
12        O: TopEncodeOutput,
13    {
14        self.top_encode_or_handle_err(output, DefaultErrorHandler)
15    }
16
17    /// Version of `top_encode` that can handle errors as soon as they occur.
18    /// For instance in can exit immediately and make sure that if it returns, it is a success.
19    /// By not deferring error handling, this can lead to somewhat smaller bytecode.
20    fn top_encode_or_handle_err<O, H>(&self, output: O, h: H) -> Result<(), H::HandledErr>
21    where
22        O: TopEncodeOutput,
23        H: EncodeErrorHandler,
24    {
25        match self.top_encode(output) {
26            Ok(()) => Ok(()),
27            Err(e) => Err(h.handle_error(e)),
28        }
29    }
30}
31
32pub fn top_encode_from_nested<T, O, H>(obj: &T, output: O, h: H) -> Result<(), H::HandledErr>
33where
34    O: TopEncodeOutput,
35    T: NestedEncode,
36    H: EncodeErrorHandler,
37{
38    let mut nested_buffer = output.start_nested_encode();
39    obj.dep_encode_or_handle_err(&mut nested_buffer, h)?;
40    output.finalize_nested_encode(nested_buffer);
41    Ok(())
42}
43
44pub fn top_encode_to_vec_u8<T: TopEncode>(obj: &T) -> Result<Vec<u8>, EncodeError> {
45    let mut bytes = Vec::<u8>::new();
46    obj.top_encode(&mut bytes)?;
47    Ok(bytes)
48}
49
50pub fn top_encode_to_vec_u8_or_panic<T: TopEncode>(obj: &T) -> Vec<u8> {
51    let mut bytes = Vec::<u8>::new();
52    obj.top_encode_or_handle_err(&mut bytes, PanicErrorHandler)
53        .unwrap_infallible();
54    bytes
55}