/rust/registry/src/index.crates.io-1949cf8c6b5b557f/bitcode-0.6.9/src/derive/convert.rs
Line | Count | Source |
1 | | use crate::coder::{Buffer, Decoder, Encoder, Result, View}; |
2 | | use crate::derive::{Decode, Encode}; |
3 | | use core::num::NonZeroUsize; |
4 | | |
5 | | #[allow(unused)] |
6 | | macro_rules! impl_convert { |
7 | | ($want: path, $have: ty) => { |
8 | | impl_convert!($want, $have, $have); |
9 | | }; |
10 | | ($want: path, $have_encode: ty, $have_decode: ty) => { |
11 | | impl crate::derive::Encode for $want { |
12 | | type Encoder = crate::derive::convert::ConvertIntoEncoder<$have_encode>; |
13 | | } |
14 | | impl<'a> crate::derive::Decode<'a> for $want { |
15 | | type Decoder = crate::derive::convert::ConvertFromDecoder<'a, $have_decode>; |
16 | | } |
17 | | }; |
18 | | } |
19 | | |
20 | | #[allow(unused)] |
21 | | pub(crate) use impl_convert; |
22 | | |
23 | | // Like [`From`] but we can implement it ourselves. |
24 | | pub(crate) trait ConvertFrom<T>: Sized { |
25 | | fn convert_from(value: T) -> Self; |
26 | | } |
27 | | |
28 | | pub struct ConvertIntoEncoder<T: Encode>(T::Encoder); |
29 | | |
30 | | // Can't derive since it would bound T: Default. |
31 | | impl<T: Encode> Default for ConvertIntoEncoder<T> { |
32 | 0 | fn default() -> Self { |
33 | 0 | Self(Default::default()) |
34 | 0 | } |
35 | | } |
36 | | |
37 | | impl<D, T: Encode + for<'a> ConvertFrom<&'a D>> Encoder<D> for ConvertIntoEncoder<T> { |
38 | | #[inline(always)] |
39 | 0 | fn encode(&mut self, t: &D) { |
40 | 0 | self.0.encode(&T::convert_from(t)); |
41 | 0 | } |
42 | | } |
43 | | |
44 | | impl<T: Encode> Buffer for ConvertIntoEncoder<T> { |
45 | 0 | fn collect_into(&mut self, out: &mut alloc::vec::Vec<u8>) { |
46 | 0 | self.0.collect_into(out); |
47 | 0 | } |
48 | 0 | fn reserve(&mut self, additional: NonZeroUsize) { |
49 | 0 | self.0.reserve(additional); |
50 | 0 | } |
51 | | } |
52 | | |
53 | | /// Decodes a `T` and then converts it with [`ConvertFrom`]. |
54 | | pub struct ConvertFromDecoder<'a, T: Decode<'a>>(T::Decoder); |
55 | | |
56 | | // Can't derive since it would bound T: Default. |
57 | | impl<'a, T: Decode<'a>> Default for ConvertFromDecoder<'a, T> { |
58 | 0 | fn default() -> Self { |
59 | 0 | Self(Default::default()) |
60 | 0 | } |
61 | | } |
62 | | |
63 | | impl<'a, T: Decode<'a>> View<'a> for ConvertFromDecoder<'a, T> { |
64 | 0 | fn populate(&mut self, input: &mut &'a [u8], length: usize) -> Result<()> { |
65 | 0 | self.0.populate(input, length) |
66 | 0 | } |
67 | | } |
68 | | |
69 | | impl<'a, F: ConvertFrom<T>, T: Decode<'a>> Decoder<'a, F> for ConvertFromDecoder<'a, T> { |
70 | | #[inline(always)] |
71 | 0 | fn decode(&mut self) -> F { |
72 | 0 | F::convert_from(self.0.decode()) |
73 | 0 | } |
74 | | } |