bitcode/derive/
impls.rs

1use crate::bool::{BoolDecoder, BoolEncoder};
2use crate::coder::{Buffer, Decoder, Encoder, Result, View};
3use crate::derive::array::{ArrayDecoder, ArrayEncoder};
4use crate::derive::empty::EmptyCoder;
5use crate::derive::map::{MapDecoder, MapEncoder};
6use crate::derive::option::{OptionDecoder, OptionEncoder};
7use crate::derive::result::{ResultDecoder, ResultEncoder};
8use crate::derive::smart_ptr::{DerefEncoder, FromDecoder};
9use crate::derive::vec::{VecDecoder, VecEncoder};
10use crate::derive::{Decode, Encode};
11use crate::f32::{F32Decoder, F32Encoder};
12use crate::int::{CheckedIntDecoder, IntDecoder, IntEncoder};
13use crate::str::{StrDecoder, StrEncoder};
14use alloc::collections::{BTreeMap, BTreeSet, BinaryHeap, LinkedList, VecDeque};
15use alloc::string::String;
16use alloc::vec::Vec;
17use core::marker::PhantomData;
18use core::mem::MaybeUninit;
19use core::num::*;
20
21macro_rules! impl_both {
22    ($t:ty, $encoder:ident, $decoder:ident) => {
23        impl Encode for $t {
24            type Encoder = $encoder;
25        }
26        impl<'a> Decode<'a> for $t {
27            type Decoder = $decoder<'a>;
28        }
29    };
30}
31pub(crate) use impl_both;
32impl_both!(bool, BoolEncoder, BoolDecoder);
33impl_both!(f32, F32Encoder, F32Decoder);
34impl_both!(String, StrEncoder, StrDecoder);
35
36macro_rules! impl_int {
37    ($($t:ty),+) => {
38        $(
39            impl Encode for $t {
40                type Encoder = IntEncoder<$t>;
41            }
42            impl<'a> Decode<'a> for $t {
43                type Decoder = IntDecoder<'a, $t>;
44            }
45        )+
46    }
47}
48impl_int!(u8, u16, u32, u64, u128, usize);
49impl_int!(i8, i16, i32, i64, i128, isize);
50// TODO F64Encoder (once F32Encoder is sufficiently optimized).
51impl Encode for f64 {
52    type Encoder = IntEncoder<u64>;
53}
54impl<'a> Decode<'a> for f64 {
55    type Decoder = IntDecoder<'a, u64>;
56}
57
58macro_rules! impl_checked_int {
59    ($($a:ty => $b:ty),+) => {
60        $(
61            impl Encode for $a {
62                type Encoder = IntEncoder<$b>;
63            }
64            impl<'a> Decode<'a> for $a {
65                type Decoder = CheckedIntDecoder<'a, $a, $b>;
66            }
67        )+
68    }
69}
70impl_checked_int!(NonZeroU8 => u8, NonZeroU16 => u16, NonZeroU32 => u32, NonZeroU64 => u64, NonZeroU128 => u128, NonZeroUsize => usize);
71impl_checked_int!(NonZeroI8 => i8, NonZeroI16 => i16, NonZeroI32 => i32, NonZeroI64 => i64, NonZeroI128 => i128, NonZeroIsize => isize);
72impl_checked_int!(char => u32);
73
74macro_rules! impl_t {
75    ($t:ident, $encoder:ident, $decoder:ident) => {
76        impl<T: Encode> Encode for $t<T> {
77            type Encoder = $encoder<T>;
78        }
79        impl<'a, T: Decode<'a>> Decode<'a> for $t<T> {
80            type Decoder = $decoder<'a, T>;
81        }
82    };
83}
84impl_t!(LinkedList, VecEncoder, VecDecoder);
85impl_t!(Option, OptionEncoder, OptionDecoder);
86impl_t!(Vec, VecEncoder, VecDecoder);
87impl_t!(VecDeque, VecEncoder, VecDecoder);
88
89macro_rules! impl_smart_ptr {
90    ($(::$ptr: ident)*) => {
91        impl<T: Encode + ?Sized> Encode for $(::$ptr)*<T> {
92            type Encoder = DerefEncoder<T>;
93        }
94
95        impl<'a, T: Decode<'a>> Decode<'a> for $(::$ptr)*<T> {
96            type Decoder = FromDecoder<'a, T>;
97        }
98
99        impl<'a, T: Decode<'a>> Decode<'a> for $(::$ptr)*<[T]> {
100            // TODO avoid Vec<T> allocation for Rc<[T]> and Arc<[T]>.
101            type Decoder = FromDecoder<'a, Vec<T>>;
102        }
103
104        impl<'a> Decode<'a> for $(::$ptr)*<str> {
105            // TODO avoid String allocation for Rc<str> and Arc<str>.
106            type Decoder = FromDecoder<'a, String>;
107        }
108    }
109}
110impl_smart_ptr!(::alloc::boxed::Box);
111impl_smart_ptr!(::alloc::rc::Rc);
112#[cfg(target_has_atomic = "ptr")]
113impl_smart_ptr!(::alloc::sync::Arc);
114
115impl<T: Encode, const N: usize> Encode for [T; N] {
116    type Encoder = ArrayEncoder<T, N>;
117}
118impl<'a, T: Decode<'a>, const N: usize> Decode<'a> for [T; N] {
119    type Decoder = ArrayDecoder<'a, T, N>;
120}
121
122// Convenience impls copied from serde etc. Makes Box<T: Encode> work on Box<[T]>.
123impl<T: Encode> Encode for [T] {
124    type Encoder = VecEncoder<T>;
125}
126impl Encode for str {
127    type Encoder = StrEncoder;
128}
129
130// Partial zero copy deserialization like serde.
131impl Encode for &str {
132    type Encoder = StrEncoder;
133}
134impl<'a> Decode<'a> for &'a str {
135    type Decoder = StrDecoder<'a>;
136}
137
138impl<T: Encode> Encode for BinaryHeap<T> {
139    type Encoder = VecEncoder<T>;
140}
141impl<'a, T: Decode<'a> + Ord> Decode<'a> for BinaryHeap<T> {
142    type Decoder = VecDecoder<'a, T>;
143}
144impl<T: Encode> Encode for BTreeSet<T> {
145    type Encoder = VecEncoder<T>;
146}
147impl<'a, T: Decode<'a> + Ord> Decode<'a> for BTreeSet<T> {
148    type Decoder = VecDecoder<'a, T>;
149}
150
151impl<K: Encode, V: Encode> Encode for BTreeMap<K, V> {
152    type Encoder = MapEncoder<K, V>;
153}
154impl<'a, K: Decode<'a> + Ord, V: Decode<'a>> Decode<'a> for BTreeMap<K, V> {
155    type Decoder = MapDecoder<'a, K, V>;
156}
157
158impl<T: Encode, E: Encode> Encode for core::result::Result<T, E> {
159    type Encoder = ResultEncoder<T, E>;
160}
161impl<'a, T: Decode<'a>, E: Decode<'a>> Decode<'a> for core::result::Result<T, E> {
162    type Decoder = ResultDecoder<'a, T, E>;
163}
164
165#[cfg(feature = "std")]
166mod with_std {
167    use super::*;
168    use crate::derive::convert::impl_convert;
169    use core::hash::{BuildHasher, Hash};
170    use std::collections::{HashMap, HashSet};
171
172    impl<T: Encode, S> Encode for HashSet<T, S> {
173        type Encoder = VecEncoder<T>;
174    }
175    impl<'a, T: Decode<'a> + Eq + Hash, S: BuildHasher + Default> Decode<'a> for HashSet<T, S> {
176        type Decoder = VecDecoder<'a, T>;
177    }
178    impl<K: Encode, V: Encode, S> Encode for HashMap<K, V, S> {
179        type Encoder = MapEncoder<K, V>;
180    }
181    impl<'a, K: Decode<'a> + Eq + Hash, V: Decode<'a>, S: BuildHasher + Default> Decode<'a>
182        for HashMap<K, V, S>
183    {
184        type Decoder = MapDecoder<'a, K, V>;
185    }
186
187    macro_rules! impl_ipvx_addr {
188        ($addr: ident, $repr: ident) => {
189            impl_convert!(std::net::$addr, $repr);
190        };
191    }
192
193    impl_ipvx_addr!(Ipv4Addr, u32);
194    impl_ipvx_addr!(Ipv6Addr, u128);
195    impl_convert!(std::net::IpAddr, crate::derive::ip_addr::IpAddrConversion);
196    impl_convert!(
197        std::net::SocketAddrV4,
198        crate::derive::ip_addr::SocketAddrV4Conversion
199    );
200    impl_convert!(
201        std::net::SocketAddrV6,
202        crate::derive::ip_addr::SocketAddrV6Conversion
203    );
204    impl_convert!(
205        std::net::SocketAddr,
206        crate::derive::ip_addr::SocketAddrConversion
207    );
208}
209
210impl<T> Encode for PhantomData<T> {
211    type Encoder = EmptyCoder;
212}
213impl<'a, T> Decode<'a> for PhantomData<T> {
214    type Decoder = EmptyCoder;
215}
216
217macro_rules! impl_tuples {
218    ($(($($n:tt $name:ident)*))+) => {
219        $(
220            #[allow(unused, clippy::unused_unit)]
221            const _: () = {
222                impl<$($name: Encode,)*> Encode for ($($name,)*) {
223                    type Encoder = TupleEncoder<$($name,)*>;
224                }
225
226                pub struct TupleEncoder<$($name: Encode,)*>(
227                    $($name::Encoder,)*
228                );
229
230                impl<$($name: Encode,)*> Default for TupleEncoder<$($name,)*> {
231                    fn default() -> Self {
232                        Self(
233                            $($name::Encoder::default(),)*
234                        )
235                    }
236                }
237
238                impl<$($name: Encode,)*> Encoder<($($name,)*)> for TupleEncoder<$($name,)*> {
239                    #[inline(always)]
240                    fn encode(&mut self, t: &($($name,)*)) {
241                        $(
242                            self.$n.encode(&t.$n);
243                        )*
244                    }
245
246                    // #[inline(always)]
247                    fn encode_vectored<'a>(&mut self, i: impl Iterator<Item=&'a ($($name,)*)> + Clone) where ($($name,)*): 'a {
248                        $(
249                            self.$n.encode_vectored(i.clone().map(|t| &t.$n));
250                        )*
251                    }
252                }
253
254                impl<$($name: Encode,)*> Buffer for TupleEncoder<$($name,)*> {
255                    fn collect_into(&mut self, out: &mut Vec<u8>) {
256                        $(
257                            self.$n.collect_into(out);
258                        )*
259                    }
260
261                    fn reserve(&mut self, length: NonZeroUsize) {
262                        $(
263                            self.$n.reserve(length);
264                        )*
265                    }
266                }
267
268                impl<'a, $($name: Decode<'a>,)*> Decode<'a> for ($($name,)*) {
269                    type Decoder = TupleDecoder<'a, $($name,)*>;
270                }
271
272                pub struct TupleDecoder<'a, $($name: Decode<'a>,)*>(
273                    $($name::Decoder,)*
274                    core::marker::PhantomData<&'a ()>,
275                );
276
277                impl<'a, $($name: Decode<'a>,)*> Default for TupleDecoder<'a, $($name,)*> {
278                    fn default() -> Self {
279                        Self(
280                            $($name::Decoder::default(),)*
281                            Default::default(),
282                        )
283                    }
284                }
285
286                impl<'a, $($name: Decode<'a>,)*> Decoder<'a, ($($name,)*)> for TupleDecoder<'a, $($name,)*> {
287                    #[inline(always)]
288                    fn decode_in_place(&mut self, out: &mut MaybeUninit<($($name,)*)>) {
289                        $(
290                            self.$n.decode_in_place(crate::coder::uninit_field!(out.$n: $name));
291                        )*
292                    }
293                }
294
295                impl<'a, $($name: Decode<'a>,)*> View<'a> for TupleDecoder<'a, $($name,)*> {
296                    fn populate(&mut self, input: &mut &'a [u8], length: usize) -> Result<()> {
297                        $(
298                            self.$n.populate(input, length)?;
299                        )*
300                        Ok(())
301                    }
302                }
303            };
304        )+
305    }
306}
307
308impl_tuples! {
309    ()
310    (0 T0)
311    (0 T0 1 T1)
312    (0 T0 1 T1 2 T2)
313    (0 T0 1 T1 2 T2 3 T3)
314    (0 T0 1 T1 2 T2 3 T3 4 T4)
315    (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5)
316    (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6)
317    (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7)
318    (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8)
319    (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9)
320    (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10)
321    (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11)
322    (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11 12 T12)
323    (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11 12 T12 13 T13)
324    (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11 12 T12 13 T13 14 T14)
325    (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11 12 T12 13 T13 14 T14 15 T15)
326}
327
328#[cfg(test)]
329mod tests {
330    use alloc::string::String;
331    use alloc::vec::Vec;
332
333    type Tuple = (u64, u32, u8, i32, u8, u16, i8, (u8, u8, u8, u8), i8);
334    fn bench_data() -> Vec<(Tuple, Option<String>)> {
335        crate::random_data(1000)
336            .into_iter()
337            .map(|t: Tuple| (t, None))
338            .collect()
339    }
340    crate::bench_encode_decode!(tuple_vec: Vec<_>);
341}