multiversx_sc_codec/single/
top_en_output.rs

1use crate::{
2    num_conv::{top_encode_number, top_encode_number_buffer},
3    EncodeError, EncodeErrorHandler, NestedEncodeOutput, TryStaticCast,
4};
5use alloc::vec::Vec;
6
7/// Specifies objects that can receive the result of a TopEncode computation.
8/// in principle from NestedEncode performed on nested items.
9///
10/// All methods consume the object, so they can only be called once.
11///
12/// The trait is used in 3 scenarios:
13/// - SC results
14/// - `#[storage_set(...)]`
15/// - Serialize async call.
16pub trait TopEncodeOutput: Sized {
17    /// Type of `NestedEncodeOutput` that can be spawned to gather serializations of children.
18    type NestedBuffer: NestedEncodeOutput;
19
20    fn set_slice_u8(self, bytes: &[u8]);
21
22    fn set_u64(self, value: u64) {
23        let mut buffer = top_encode_number_buffer();
24        let slice = top_encode_number(value, false, &mut buffer);
25        self.set_slice_u8(slice);
26    }
27
28    fn set_i64(self, value: i64) {
29        let mut buffer = top_encode_number_buffer();
30        let slice = top_encode_number(value as u64, true, &mut buffer);
31        self.set_slice_u8(slice);
32    }
33
34    /// The unit type `()` is serializable, but some TopEncodeOutput implementations might want to treat it differently.
35    /// For instance, SC function result units do not cause `finish` to be called, no empty result produced.
36    #[doc(hidden)]
37    #[inline]
38    fn set_unit(self) {
39        self.set_slice_u8(&[]);
40    }
41
42    #[inline]
43    fn supports_specialized_type<T: TryStaticCast>() -> bool {
44        false
45    }
46
47    /// Allows special handling of special types.
48    /// Also requires an alternative serialization, in case the special handling is not covered.
49    /// The alternative serialization, `else_serialization` is only called when necessary and
50    /// is normally compiled out via monomorphization.
51    #[inline]
52    fn set_specialized<T, H>(self, _value: &T, h: H) -> Result<(), H::HandledErr>
53    where
54        T: TryStaticCast,
55        H: EncodeErrorHandler,
56    {
57        Err(h.handle_error(EncodeError::UNSUPPORTED_OPERATION))
58    }
59
60    fn start_nested_encode(&self) -> Self::NestedBuffer;
61
62    fn finalize_nested_encode(self, nb: Self::NestedBuffer);
63}
64
65impl TopEncodeOutput for &mut Vec<u8> {
66    type NestedBuffer = Vec<u8>;
67
68    fn set_slice_u8(self, bytes: &[u8]) {
69        self.extend_from_slice(bytes);
70    }
71
72    fn start_nested_encode(&self) -> Self::NestedBuffer {
73        Vec::<u8>::new()
74    }
75
76    fn finalize_nested_encode(self, nb: Self::NestedBuffer) {
77        *self = nb;
78    }
79}