multiversx_sc_codec/single/nested_en.rs
1use crate::{codec_err::EncodeError, DefaultErrorHandler, EncodeErrorHandler, NestedEncodeOutput};
2use alloc::vec::Vec;
3
4/// Trait that allows zero-copy write of value-references to slices in LE format.
5///
6/// Implementations should override `using_top_encoded` for value types and `dep_encode` and `size_hint` for allocating types.
7/// Wrapper types should override all methods.
8pub trait NestedEncode: Sized {
9 /// NestedEncode to output, using the format of an object nested inside another structure.
10 /// Does not provide compact version.
11 fn dep_encode<O: NestedEncodeOutput>(&self, dest: &mut O) -> Result<(), EncodeError> {
12 self.dep_encode_or_handle_err(dest, DefaultErrorHandler)
13 }
14
15 /// Version of `dep_encode` that can handle errors as soon as they occur.
16 /// For instance in can exit immediately and make sure that if it returns, it is a success.
17 /// By not deferring error handling, this can lead to somewhat smaller bytecode.
18 fn dep_encode_or_handle_err<O, H>(&self, dest: &mut O, h: H) -> Result<(), H::HandledErr>
19 where
20 O: NestedEncodeOutput,
21 H: EncodeErrorHandler,
22 {
23 match self.dep_encode(dest) {
24 Ok(()) => Ok(()),
25 Err(e) => Err(h.handle_error(e)),
26 }
27 }
28
29 /// Allows the framework to do monomorphisation of special cases where the data is of type `u8`.
30 ///
31 /// Especially useful for serializing byte arrays.
32 ///
33 /// Working with this also involves transmuting low-level data. Only use if you really know what you are doing!
34 #[doc(hidden)]
35 #[allow(unused_variables)]
36 fn if_u8<Output, If, Else, R>(output: Output, if_branch: If, else_branch: Else) -> R
37 where
38 If: FnOnce(Output) -> R,
39 Else: FnOnce(Output) -> R,
40 {
41 else_branch(output)
42 }
43}
44
45/// Convenience function for getting an object nested-encoded to a Vec<u8> directly.
46pub fn dep_encode_to_vec<T: NestedEncode>(obj: &T) -> Result<Vec<u8>, EncodeError> {
47 let mut bytes = Vec::<u8>::new();
48 obj.dep_encode(&mut bytes)?;
49 Ok(bytes)
50}