numbat_codec/nested_ser.rs
1use crate::{codec_err::EncodeError, nested_ser_output::NestedEncodeOutput, TypeInfo};
2use alloc::vec::Vec;
3
4/// Most types will be encoded without any possibility of error.
5/// The trait is used to provide these implementations.
6/// This is currently not a substitute for implementing a proper TopEncode.
7pub trait NestedEncodeNoErr: Sized {
8 fn dep_encode_no_err<O: NestedEncodeOutput>(&self, dest: &mut O);
9}
10
11/// Trait that allows zero-copy write of value-references to slices in LE format.
12///
13/// Implementations should override `using_top_encoded` for value types and `dep_encode` and `size_hint` for allocating types.
14/// Wrapper types should override all methods.
15pub trait NestedEncode: Sized {
16 // !INTERNAL USE ONLY!
17 // This const helps SCALE to optimize the encoding/decoding by doing fake specialization.
18 #[doc(hidden)]
19 const TYPE_INFO: TypeInfo = TypeInfo::Unknown;
20
21 /// NestedEncode to output, using the format of an object nested inside another structure.
22 /// Does not provide compact version.
23 fn dep_encode<O: NestedEncodeOutput>(&self, dest: &mut O) -> Result<(), EncodeError>;
24
25 /// Version of `top_decode` that exits quickly in case of error.
26 /// Its purpose is to create smaller implementations
27 /// in cases where the application is supposed to exit directly on decode error.
28 fn dep_encode_or_exit<O: NestedEncodeOutput, ExitCtx: Clone>(
29 &self,
30 dest: &mut O,
31 c: ExitCtx,
32 exit: fn(ExitCtx, EncodeError) -> !,
33 ) {
34 match self.dep_encode(dest) {
35 Ok(v) => v,
36 Err(e) => exit(c, e),
37 }
38 }
39}
40
41/// Convenience function for getting an object nested-encoded to a Vec<u8> directly.
42pub fn dep_encode_to_vec<T: NestedEncode>(obj: &T) -> Result<Vec<u8>, EncodeError> {
43 let mut bytes = Vec::<u8>::new();
44 obj.dep_encode(&mut bytes)?;
45 Ok(bytes)
46}