Skip to main content

proc_macro/bridge/
rpc.rs

1//! Serialization for client-server communication.
2
3use std::num::NonZero;
4
5use super::buffer::Buffer;
6
7pub(super) trait Encode<S>: Sized {
8    fn encode(self, w: &mut Buffer, s: &mut S);
9}
10
11pub(super) trait Decode<'a, 's, S>: Sized {
12    fn decode(r: &mut &'a [u8], s: &'s mut S) -> Self;
13}
14
15macro_rules! rpc_encode_decode {
16    (le $ty:ty) => {
17        impl<S> Encode<S> for $ty {
18            #[inline]
19            fn encode(self, w: &mut Buffer, _: &mut S) {
20                w.extend_from_array(&self.to_le_bytes());
21            }
22        }
23
24        impl<S> Decode<'_, '_, S> for $ty {
25            #[inline]
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            #[inline]
48            fn decode(r: &mut &'a [u8], s: &mut S) -> Self {
49                $name {
50                    $($field: Decode::decode(r, s)),*
51                }
52            }
53        }
54    };
55    (enum $name:ident $(<$($T:ident),+>)? { $($variant:ident $(($field:ident))*),* $(,)? }) => {
56        #[allow(non_upper_case_globals, non_camel_case_types)]
57        const _: () = {
58            #[repr(u8)] enum Tag { $($variant),* }
59
60            $(const $variant: u8 = Tag::$variant as u8;)*
61
62            impl<S, $($($T: Encode<S>),+)?> Encode<S> for $name $(<$($T),+>)? {
63                #[inline]
64                fn encode(self, w: &mut Buffer, s: &mut S) {
65                    match self {
66                        $($name::$variant $(($field))* => {
67                            $variant.encode(w, s);
68                            $($field.encode(w, s);)*
69                        })*
70                    }
71                }
72            }
73
74            impl<'a, S, $($($T: for<'s> Decode<'a, 's, S>),+)?> Decode<'a, '_, S>
75                for $name $(<$($T),+>)?
76            {
77                #[inline]
78                fn decode(r: &mut &'a [u8], s: &mut S) -> Self {
79                    match u8::decode(r, s) {
80                        $($variant => {
81                            $(let $field = Decode::decode(r, s);)*
82                            $name::$variant $(($field))*
83                        })*
84                        _ => unreachable!(),
85                    }
86                }
87            }
88        };
89    }
90}
91
92impl<S> Encode<S> for () {
93    #[inline]
94    fn encode(self, _: &mut Buffer, _: &mut S) {}
95}
96
97impl<S> Decode<'_, '_, S> for () {
98    #[inline]
99    fn decode(_: &mut &[u8], _: &mut S) -> Self {}
100}
101
102impl<S> Encode<S> for u8 {
103    #[inline]
104    fn encode(self, w: &mut Buffer, _: &mut S) {
105        w.push(self);
106    }
107}
108
109impl<S> Decode<'_, '_, S> for u8 {
110    #[inline]
111    fn decode(r: &mut &[u8], _: &mut S) -> Self {
112        let x = r[0];
113        *r = &r[1..];
114        x
115    }
116}
117
118rpc_encode_decode!(le u32);
119#[cfg(target_pointer_width = "64")]
120rpc_encode_decode!(le usize);
121
122#[cfg(not(target_pointer_width = "64"))]
123const MAX_USIZE_SIZE: usize = 8;
124
125#[cfg(not(target_pointer_width = "64"))]
126impl<S> Encode<S> for usize {
127    #[inline]
128    fn encode(self, w: &mut Buffer, _: &mut S) {
129        const N: usize = size_of::<usize>();
130
131        // We can pad with zeros without changing the value because of
132        // little endian encoding.
133        let mut bytes = [0; MAX_USIZE_SIZE];
134        bytes[..N].copy_from_slice(&self.to_le_bytes());
135
136        w.extend_from_array(&bytes);
137    }
138}
139
140#[cfg(not(target_pointer_width = "64"))]
141impl<S> Decode<'_, '_, S> for usize {
142    #[inline]
143    fn decode(r: &mut &[u8], _: &mut S) -> Self {
144        const N: usize = size_of::<usize>();
145        const {
146            assert!(N <= MAX_USIZE_SIZE);
147        }
148
149        let mut bytes = [0; N];
150        bytes.copy_from_slice(&r[..N]);
151        *r = &r[MAX_USIZE_SIZE..];
152
153        Self::from_le_bytes(bytes)
154    }
155}
156
157impl<S> Encode<S> for bool {
158    #[inline]
159    fn encode(self, w: &mut Buffer, s: &mut S) {
160        (self as u8).encode(w, s);
161    }
162}
163
164impl<S> Decode<'_, '_, S> for bool {
165    #[inline]
166    fn decode(r: &mut &[u8], s: &mut S) -> Self {
167        match u8::decode(r, s) {
168            0 => false,
169            1 => true,
170            _ => unreachable!(),
171        }
172    }
173}
174
175impl<S> Encode<S> for NonZero<u32> {
176    #[inline]
177    fn encode(self, w: &mut Buffer, s: &mut S) {
178        self.get().encode(w, s);
179    }
180}
181
182impl<S> Decode<'_, '_, S> for NonZero<u32> {
183    #[inline]
184    fn decode(r: &mut &[u8], s: &mut S) -> Self {
185        Self::new(u32::decode(r, s)).unwrap()
186    }
187}
188
189impl<S, A: Encode<S>, B: Encode<S>> Encode<S> for (A, B) {
190    #[inline]
191    fn encode(self, w: &mut Buffer, s: &mut S) {
192        self.0.encode(w, s);
193        self.1.encode(w, s);
194    }
195}
196
197impl<'a, S, A: for<'s> Decode<'a, 's, S>, B: for<'s> Decode<'a, 's, S>> Decode<'a, '_, S>
198    for (A, B)
199{
200    #[inline]
201    fn decode(r: &mut &'a [u8], s: &mut S) -> Self {
202        (Decode::decode(r, s), Decode::decode(r, s))
203    }
204}
205
206impl<S> Encode<S> for &str {
207    #[inline]
208    fn encode(self, w: &mut Buffer, s: &mut S) {
209        let bytes = self.as_bytes();
210        bytes.len().encode(w, s);
211        w.extend_from_slice(bytes);
212    }
213}
214
215impl<'a, S> Decode<'a, '_, S> for &'a str {
216    #[inline]
217    fn decode(r: &mut &'a [u8], s: &mut S) -> Self {
218        let len = usize::decode(r, s);
219        let xs = &r[..len];
220        *r = &r[len..];
221        str::from_utf8(xs).unwrap()
222    }
223}
224
225impl<S> Encode<S> for String {
226    #[inline]
227    fn encode(self, w: &mut Buffer, s: &mut S) {
228        self[..].encode(w, s);
229    }
230}
231
232impl<S> Decode<'_, '_, S> for String {
233    #[inline]
234    fn decode(r: &mut &[u8], s: &mut S) -> Self {
235        <&str>::decode(r, s).to_string()
236    }
237}
238
239impl<S, T: Encode<S>> Encode<S> for Vec<T> {
240    #[inline]
241    fn encode(self, w: &mut Buffer, s: &mut S) {
242        self.len().encode(w, s);
243        for x in self {
244            x.encode(w, s);
245        }
246    }
247}
248
249impl<'a, S, T: for<'s> Decode<'a, 's, S>> Decode<'a, '_, S> for Vec<T> {
250    #[inline]
251    fn decode(r: &mut &'a [u8], s: &mut S) -> Self {
252        let len = usize::decode(r, s);
253        let mut vec = Vec::with_capacity(len);
254        for _ in 0..len {
255            vec.push(T::decode(r, s));
256        }
257        vec
258    }
259}