Skip to main content

proc_macro/bridge/
rpc.rs

1//! Serialization for client-server communication.
2
3use std::any::Any;
4use std::io::Write;
5use std::num::NonZero;
6
7use super::buffer::Buffer;
8
9pub(super) trait Encode<S>: Sized {
10    fn encode(self, w: &mut Buffer, s: &mut S);
11}
12
13pub(super) trait Decode<'a, 's, S>: Sized {
14    fn decode(r: &mut &'a [u8], s: &'s mut S) -> Self;
15}
16
17macro_rules! rpc_encode_decode {
18    (le $ty:ty) => {
19        impl<S> Encode<S> for $ty {
20            fn encode(self, w: &mut Buffer, _: &mut S) {
21                w.extend_from_array(&self.to_le_bytes());
22            }
23        }
24
25        impl<S> Decode<'_, '_, S> for $ty {
26            fn decode(r: &mut &[u8], _: &mut S) -> Self {
27                const N: usize = size_of::<$ty>();
28
29                let mut bytes = [0; N];
30                bytes.copy_from_slice(&r[..N]);
31                *r = &r[N..];
32
33                Self::from_le_bytes(bytes)
34            }
35        }
36    };
37    (struct $name:ident $(<$($T:ident),+>)? { $($field:ident),* $(,)? }) => {
38        impl<S, $($($T: Encode<S>),+)?> Encode<S> for $name $(<$($T),+>)? {
39            fn encode(self, w: &mut Buffer, s: &mut S) {
40                $(self.$field.encode(w, s);)*
41            }
42        }
43
44        impl<'a, S, $($($T: for<'s> Decode<'a, 's, S>),+)?> Decode<'a, '_, S>
45            for $name $(<$($T),+>)?
46        {
47            fn decode(r: &mut &'a [u8], s: &mut S) -> Self {
48                $name {
49                    $($field: Decode::decode(r, s)),*
50                }
51            }
52        }
53    };
54    (enum $name:ident $(<$($T:ident),+>)? { $($variant:ident $(($field:ident))*),* $(,)? }) => {
55        #[allow(non_upper_case_globals, non_camel_case_types)]
56        const _: () = {
57            #[repr(u8)] enum Tag { $($variant),* }
58
59            $(const $variant: u8 = Tag::$variant as u8;)*
60
61            impl<S, $($($T: Encode<S>),+)?> Encode<S> for $name $(<$($T),+>)? {
62                fn encode(self, w: &mut Buffer, s: &mut S) {
63                    match self {
64                        $($name::$variant $(($field))* => {
65                            $variant.encode(w, s);
66                            $($field.encode(w, s);)*
67                        })*
68                    }
69                }
70            }
71
72            impl<'a, S, $($($T: for<'s> Decode<'a, 's, S>),+)?> Decode<'a, '_, S>
73                for $name $(<$($T),+>)?
74            {
75                fn decode(r: &mut &'a [u8], s: &mut S) -> Self {
76                    match u8::decode(r, s) {
77                        $($variant => {
78                            $(let $field = Decode::decode(r, s);)*
79                            $name::$variant $(($field))*
80                        })*
81                        _ => unreachable!(),
82                    }
83                }
84            }
85        };
86    }
87}
88
89impl<S> Encode<S> for () {
90    fn encode(self, _: &mut Buffer, _: &mut S) {}
91}
92
93impl<S> Decode<'_, '_, S> for () {
94    fn decode(_: &mut &[u8], _: &mut S) -> Self {}
95}
96
97impl<S> Encode<S> for u8 {
98    fn encode(self, w: &mut Buffer, _: &mut S) {
99        w.push(self);
100    }
101}
102
103impl<S> Decode<'_, '_, S> for u8 {
104    fn decode(r: &mut &[u8], _: &mut S) -> Self {
105        let x = r[0];
106        *r = &r[1..];
107        x
108    }
109}
110
111rpc_encode_decode!(le u32);
112rpc_encode_decode!(le usize);
113
114impl<S> Encode<S> for bool {
115    fn encode(self, w: &mut Buffer, s: &mut S) {
116        (self as u8).encode(w, s);
117    }
118}
119
120impl<S> Decode<'_, '_, S> for bool {
121    fn decode(r: &mut &[u8], s: &mut S) -> Self {
122        match u8::decode(r, s) {
123            0 => false,
124            1 => true,
125            _ => unreachable!(),
126        }
127    }
128}
129
130impl<S> Encode<S> for NonZero<u32> {
131    fn encode(self, w: &mut Buffer, s: &mut S) {
132        self.get().encode(w, s);
133    }
134}
135
136impl<S> Decode<'_, '_, S> for NonZero<u32> {
137    fn decode(r: &mut &[u8], s: &mut S) -> Self {
138        Self::new(u32::decode(r, s)).unwrap()
139    }
140}
141
142impl<S, A: Encode<S>, B: Encode<S>> Encode<S> for (A, B) {
143    fn encode(self, w: &mut Buffer, s: &mut S) {
144        self.0.encode(w, s);
145        self.1.encode(w, s);
146    }
147}
148
149impl<'a, S, A: for<'s> Decode<'a, 's, S>, B: for<'s> Decode<'a, 's, S>> Decode<'a, '_, S>
150    for (A, B)
151{
152    fn decode(r: &mut &'a [u8], s: &mut S) -> Self {
153        (Decode::decode(r, s), Decode::decode(r, s))
154    }
155}
156
157impl<S> Encode<S> for &str {
158    fn encode(self, w: &mut Buffer, s: &mut S) {
159        let bytes = self.as_bytes();
160        bytes.len().encode(w, s);
161        w.write_all(bytes).unwrap();
162    }
163}
164
165impl<'a, S> Decode<'a, '_, S> for &'a str {
166    fn decode(r: &mut &'a [u8], s: &mut S) -> Self {
167        let len = usize::decode(r, s);
168        let xs = &r[..len];
169        *r = &r[len..];
170        str::from_utf8(xs).unwrap()
171    }
172}
173
174impl<S> Encode<S> for String {
175    fn encode(self, w: &mut Buffer, s: &mut S) {
176        self[..].encode(w, s);
177    }
178}
179
180impl<S> Decode<'_, '_, S> for String {
181    fn decode(r: &mut &[u8], s: &mut S) -> Self {
182        <&str>::decode(r, s).to_string()
183    }
184}
185
186impl<S, T: Encode<S>> Encode<S> for Vec<T> {
187    fn encode(self, w: &mut Buffer, s: &mut S) {
188        self.len().encode(w, s);
189        for x in self {
190            x.encode(w, s);
191        }
192    }
193}
194
195impl<'a, S, T: for<'s> Decode<'a, 's, S>> Decode<'a, '_, S> for Vec<T> {
196    fn decode(r: &mut &'a [u8], s: &mut S) -> Self {
197        let len = usize::decode(r, s);
198        let mut vec = Vec::with_capacity(len);
199        for _ in 0..len {
200            vec.push(T::decode(r, s));
201        }
202        vec
203    }
204}
205
206/// Simplified version of panic payloads, ignoring
207/// types other than `&'static str` and `String`.
208pub enum PanicMessage {
209    StaticStr(&'static str),
210    String(String),
211    Unknown,
212}
213
214impl From<Box<dyn Any + Send>> for PanicMessage {
215    fn from(payload: Box<dyn Any + Send + 'static>) -> Self {
216        if let Some(s) = payload.downcast_ref::<&'static str>() {
217            return PanicMessage::StaticStr(s);
218        }
219        if let Ok(s) = payload.downcast::<String>() {
220            return PanicMessage::String(*s);
221        }
222        PanicMessage::Unknown
223    }
224}
225
226impl From<PanicMessage> for Box<dyn Any + Send> {
227    fn from(val: PanicMessage) -> Self {
228        match val {
229            PanicMessage::StaticStr(s) => Box::new(s),
230            PanicMessage::String(s) => Box::new(s),
231            PanicMessage::Unknown => {
232                struct UnknownPanicMessage;
233                Box::new(UnknownPanicMessage)
234            }
235        }
236    }
237}
238
239impl PanicMessage {
240    pub fn as_str(&self) -> Option<&str> {
241        match self {
242            PanicMessage::StaticStr(s) => Some(s),
243            PanicMessage::String(s) => Some(s),
244            PanicMessage::Unknown => None,
245        }
246    }
247}
248
249impl<S> Encode<S> for PanicMessage {
250    fn encode(self, w: &mut Buffer, s: &mut S) {
251        self.as_str().encode(w, s);
252    }
253}
254
255impl<S> Decode<'_, '_, S> for PanicMessage {
256    fn decode(r: &mut &[u8], s: &mut S) -> Self {
257        match Option::<String>::decode(r, s) {
258            Some(s) => PanicMessage::String(s),
259            None => PanicMessage::Unknown,
260        }
261    }
262}