multiversx_sc/formatter/
formatter_traits.rs

1use unwrap_infallible::UnwrapInfallible;
2
3use crate::codec::TopEncode;
4
5use crate::{
6    api::ManagedTypeApi, contract_base::ExitCodecErrorHandler, err_msg, types::ManagedBuffer,
7};
8
9pub const HEX_VALUE_PREFIX: &[u8] = b"0x";
10pub const BINARY_VALUE_PREFIX: &[u8] = b"0b";
11
12pub trait FormatByteReceiver {
13    type Api: ManagedTypeApi;
14
15    fn append_bytes(&mut self, bytes: &[u8]);
16
17    fn append_managed_buffer(&mut self, item: &ManagedBuffer<Self::Api>);
18
19    fn append_managed_buffer_lower_hex(&mut self, item: &ManagedBuffer<Self::Api>);
20
21    fn append_managed_buffer_binary(&mut self, item: &ManagedBuffer<Self::Api>);
22}
23
24pub trait FormatBuffer: Default {
25    fn append_ascii(&mut self, ascii: &[u8]);
26
27    fn append_display<T: SCDisplay>(&mut self, item: &T);
28
29    fn append_lower_hex<T: SCLowerHex>(&mut self, item: &T);
30
31    fn append_binary<T: SCBinary>(&mut self, item: &T);
32
33    fn append_codec<T: SCCodec>(&mut self, item: &T);
34}
35
36#[derive(Default)]
37pub struct FormatBufferIgnore;
38
39impl FormatBuffer for FormatBufferIgnore {
40    #[inline]
41    fn append_ascii(&mut self, _ascii: &[u8]) {}
42
43    #[inline]
44    fn append_display<T: SCDisplay>(&mut self, _item: &T) {}
45
46    #[inline]
47    fn append_lower_hex<T: SCLowerHex>(&mut self, _item: &T) {}
48
49    #[inline]
50    fn append_binary<T: SCBinary>(&mut self, _item: &T) {}
51
52    #[inline]
53    fn append_codec<T: SCCodec>(&mut self, _item: &T) {}
54}
55
56pub trait SCDisplay {
57    fn fmt<F: FormatByteReceiver>(&self, f: &mut F);
58}
59
60impl<T: SCDisplay> SCDisplay for &T {
61    fn fmt<F: FormatByteReceiver>(&self, f: &mut F) {
62        SCDisplay::fmt(*self, f)
63    }
64}
65
66pub trait SCLowerHex {
67    fn fmt<F>(&self, f: &mut F)
68    where
69        F: FormatByteReceiver;
70}
71
72impl<T: SCLowerHex> SCLowerHex for &T {
73    fn fmt<F: FormatByteReceiver>(&self, f: &mut F) {
74        SCLowerHex::fmt(*self, f)
75    }
76}
77
78pub trait SCBinary {
79    fn fmt<F: FormatByteReceiver>(&self, f: &mut F);
80}
81
82impl<T: SCBinary> SCBinary for &T {
83    fn fmt<F: FormatByteReceiver>(&self, f: &mut F) {
84        SCBinary::fmt(*self, f)
85    }
86}
87
88pub trait SCCodec {
89    fn fmt<F: FormatByteReceiver>(&self, f: &mut F);
90}
91
92impl<T: TopEncode> SCCodec for T {
93    fn fmt<F: FormatByteReceiver>(&self, f: &mut F) {
94        let mut encoded = ManagedBuffer::<F::Api>::new();
95        self.top_encode_or_handle_err(
96            &mut encoded,
97            ExitCodecErrorHandler::<F::Api>::from(err_msg::FORMATTER_ENCODE_ERROR),
98        )
99        .unwrap_infallible();
100        SCLowerHex::fmt(&encoded, f);
101    }
102}