pint_abi/
encode.rs

1use crate::{types::essential::Word, write::Write};
2
3/// A trait for encoding types as Essential `Word`s in a manner compatible with Pint's ABI.
4pub trait Encode {
5    /// Encode `self` in words with the given writer.
6    fn encode<W: Write>(&self, w: &mut W) -> Result<(), W::Error>;
7}
8
9impl Encode for Word {
10    fn encode<W: Write>(&self, w: &mut W) -> Result<(), W::Error> {
11        w.write_word(*self)
12    }
13}
14
15impl Encode for bool {
16    fn encode<W: Write>(&self, w: &mut W) -> Result<(), W::Error> {
17        Word::from(*self).encode(w)
18    }
19}
20
21impl<T: Encode + Default> Encode for Option<T> {
22    fn encode<W: Write>(&self, w: &mut W) -> Result<(), W::Error> {
23        match self {
24            Some(val) => {
25                val.encode(w)?; // data
26                w.write_word(1) // tag
27            }
28            None => {
29                T::default().encode(w)?; // data
30                w.write_word(0) // tag
31            }
32        }
33    }
34}
35
36impl<T: Encode> Encode for [T] {
37    fn encode<W: Write>(&self, w: &mut W) -> Result<(), W::Error> {
38        for elem in self {
39            elem.encode(w)?;
40        }
41        Ok(())
42    }
43}
44
45impl<T: Encode, const N: usize> Encode for [T; N] {
46    fn encode<W: Write>(&self, w: &mut W) -> Result<(), W::Error> {
47        self[..].encode(w)?;
48        Ok(())
49    }
50}
51
52macro_rules! impl_encode_for_tuple {
53    ($($T:ident),+) => {
54        impl<$($T: Encode),+> Encode for ($($T),+) {
55            fn encode<W: Write>(&self, w: &mut W) -> Result<(), W::Error> {
56                #[allow(non_snake_case)]
57                let ($($T),+) = self;
58                $(
59                    $T.encode(w)?;
60                )+
61                Ok(())
62            }
63        }
64    };
65}
66
67impl_encode_for_tuple!(A, B);
68impl_encode_for_tuple!(A, B, C);
69impl_encode_for_tuple!(A, B, C, D);
70impl_encode_for_tuple!(A, B, C, D, E);
71impl_encode_for_tuple!(A, B, C, D, E, F);
72impl_encode_for_tuple!(A, B, C, D, E, F, G);
73impl_encode_for_tuple!(A, B, C, D, E, F, G, H);
74impl_encode_for_tuple!(A, B, C, D, E, F, G, H, I);
75impl_encode_for_tuple!(A, B, C, D, E, F, G, H, I, J);
76impl_encode_for_tuple!(A, B, C, D, E, F, G, H, I, J, K);
77impl_encode_for_tuple!(A, B, C, D, E, F, G, H, I, J, K, L);