elrond_codec/single/
top_en.rs

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