testnumbat_codec/
top_ser.rs

1use crate::{
2    codec_err::EncodeError, nested_ser::NestedEncode, top_ser_output::TopEncodeOutput, TypeInfo,
3};
4use alloc::vec::Vec;
5
6/// Most types will be encoded without any possibility of error.
7/// The trait is used to provide these implementations.
8/// This is currently not a substitute for implementing a proper TopEncode.
9pub trait TopEncodeNoErr: Sized {
10    fn top_encode_no_err<O: TopEncodeOutput>(&self, output: O);
11}
12
13/// Quick encoding of a type that never fails on encoding.
14pub fn top_encode_no_err<T: TopEncodeNoErr>(obj: &T) -> Vec<u8> {
15    let mut bytes = Vec::<u8>::new();
16    obj.top_encode_no_err(&mut bytes);
17    bytes
18}
19
20pub trait TopEncode: Sized {
21    // !INTERNAL USE ONLY!
22    #[doc(hidden)]
23    const TYPE_INFO: TypeInfo = TypeInfo::Unknown;
24
25    /// Attempt to serialize the value to ouput.
26    fn top_encode<O: TopEncodeOutput>(&self, output: O) -> Result<(), EncodeError>;
27
28    /// Version of `top_decode` that exits quickly in case of error.
29    /// Its purpose is to create smaller bytecode implementations
30    /// in cases where the application is supposed to exit directly on decode error.
31    fn top_encode_or_exit<O: TopEncodeOutput, ExitCtx: Clone>(
32        &self,
33        output: O,
34        c: ExitCtx,
35        exit: fn(ExitCtx, EncodeError) -> !,
36    ) {
37        match self.top_encode(output) {
38            Ok(v) => v,
39            Err(e) => exit(c, e),
40        }
41    }
42}
43
44pub fn top_encode_from_nested<T, O>(obj: &T, output: O) -> Result<(), EncodeError>
45where
46    O: TopEncodeOutput,
47    T: NestedEncode,
48{
49    let mut nested_buffer = output.start_nested_encode();
50    obj.dep_encode(&mut nested_buffer)?;
51    output.finalize_nested_encode(nested_buffer);
52    Ok(())
53}
54
55pub fn top_encode_from_nested_or_exit<T, O, ExitCtx>(
56    obj: &T,
57    output: O,
58    c: ExitCtx,
59    exit: fn(ExitCtx, EncodeError) -> !,
60) where
61    O: TopEncodeOutput,
62    T: NestedEncode,
63    ExitCtx: Clone,
64{
65    let mut nested_buffer = output.start_nested_encode();
66    obj.dep_encode_or_exit(&mut nested_buffer, c, exit);
67    output.finalize_nested_encode(nested_buffer);
68}
69
70pub fn top_encode_to_vec<T: TopEncode>(obj: &T) -> Result<Vec<u8>, EncodeError> {
71    let mut bytes = Vec::<u8>::new();
72    obj.top_encode(&mut bytes)?;
73    Ok(bytes)
74}