reth_codecs_derive/compact/
mod.rs

1use proc_macro::TokenStream;
2use proc_macro2::{Ident, TokenStream as TokenStream2};
3use quote::{format_ident, quote};
4use syn::{Data, DeriveInput, Generics};
5
6mod generator;
7use generator::*;
8
9mod enums;
10use enums::*;
11
12mod flags;
13use flags::*;
14
15mod structs;
16use structs::*;
17
18use crate::ZstdConfig;
19
20// Helper Alias type
21type FieldType = String;
22/// `Compact` has alternative functions that can be used as a workaround for type
23/// specialization of fixed sized types.
24///
25/// Example: `Vec<B256>` vs `Vec<U256>`. The first does not
26/// require the len of the element, while the latter one does.
27type UseAlternative = bool;
28// Helper Alias type
29#[derive(Debug, Clone, Eq, PartialEq)]
30pub struct StructFieldDescriptor {
31    name: String,
32    ftype: String,
33    is_compact: bool,
34    use_alt_impl: bool,
35    is_reference: bool,
36}
37// Helper Alias type
38type FieldList = Vec<FieldTypes>;
39
40#[derive(Debug, Clone, Eq, PartialEq)]
41pub enum FieldTypes {
42    StructField(StructFieldDescriptor),
43    EnumVariant(String),
44    EnumUnnamedField((FieldType, UseAlternative)),
45}
46
47/// Derives the `Compact` trait and its from/to implementations.
48pub fn derive(input: DeriveInput, zstd: Option<ZstdConfig>) -> TokenStream {
49    let mut output = quote! {};
50
51    let DeriveInput { ident, data, generics, attrs, .. } = input;
52
53    let has_lifetime = has_lifetime(&generics);
54
55    let fields = get_fields(&data);
56    output.extend(generate_flag_struct(&ident, &attrs, has_lifetime, &fields, zstd.is_some()));
57    output.extend(generate_from_to(&ident, &attrs, has_lifetime, &fields, zstd));
58    output.into()
59}
60
61pub fn has_lifetime(generics: &Generics) -> bool {
62    generics.lifetimes().next().is_some()
63}
64
65/// Given a list of fields on a struct, extract their fields and types.
66pub fn get_fields(data: &Data) -> FieldList {
67    let mut fields = vec![];
68
69    match data {
70        Data::Struct(data) => match data.fields {
71            syn::Fields::Named(ref data_fields) => {
72                for field in &data_fields.named {
73                    load_field(field, &mut fields, false);
74                }
75                assert_eq!(fields.len(), data_fields.named.len(), "get_fields");
76            }
77            syn::Fields::Unnamed(ref data_fields) => {
78                assert_eq!(
79                    data_fields.unnamed.len(),
80                    1,
81                    "Compact only allows one unnamed field. Consider making it a struct."
82                );
83                load_field(&data_fields.unnamed[0], &mut fields, false);
84            }
85            syn::Fields::Unit => todo!(),
86        },
87        Data::Enum(data) => {
88            for variant in &data.variants {
89                fields.push(FieldTypes::EnumVariant(variant.ident.to_string()));
90
91                match &variant.fields {
92                    syn::Fields::Named(_) => {
93                        panic!(
94                            "Not allowed to have Enum Variants with multiple named fields. Make it a struct instead."
95                        )
96                    }
97                    syn::Fields::Unnamed(data_fields) => {
98                        assert_eq!(
99                            data_fields.unnamed.len(),
100                            1,
101                            "Compact only allows one unnamed field. Consider making it a struct."
102                        );
103                        load_field(&data_fields.unnamed[0], &mut fields, true);
104                    }
105                    syn::Fields::Unit => (),
106                }
107            }
108        }
109        Data::Union(_) => todo!(),
110    }
111
112    fields
113}
114
115fn load_field(field: &syn::Field, fields: &mut FieldList, is_enum: bool) {
116    match field.ty {
117        syn::Type::Reference(ref reference) => match &*reference.elem {
118            syn::Type::Path(path) => {
119                load_field_from_segments(&path.path.segments, is_enum, fields, field)
120            }
121            _ => unimplemented!("{:?}", &field.ident),
122        },
123        syn::Type::Path(ref path) => {
124            load_field_from_segments(&path.path.segments, is_enum, fields, field)
125        }
126        _ => unimplemented!("{:?}", &field.ident),
127    }
128}
129
130fn load_field_from_segments(
131    segments: &syn::punctuated::Punctuated<syn::PathSegment, syn::token::PathSep>,
132    is_enum: bool,
133    fields: &mut Vec<FieldTypes>,
134    field: &syn::Field,
135) {
136    if !segments.is_empty() {
137        let mut ftype = String::new();
138
139        let mut use_alt_impl: UseAlternative = false;
140
141        for (index, segment) in segments.iter().enumerate() {
142            ftype.push_str(&segment.ident.to_string());
143            if index < segments.len() - 1 {
144                ftype.push_str("::");
145            }
146
147            use_alt_impl = should_use_alt_impl(&ftype, segment);
148        }
149
150        if is_enum {
151            fields.push(FieldTypes::EnumUnnamedField((ftype, use_alt_impl)));
152        } else {
153            let should_compact = is_flag_type(&ftype) ||
154                field.attrs.iter().any(|attr| {
155                    attr.path().segments.iter().any(|path| path.ident == "maybe_zero")
156                });
157
158            fields.push(FieldTypes::StructField(StructFieldDescriptor {
159                name: field.ident.as_ref().map(|i| i.to_string()).unwrap_or_default(),
160                ftype,
161                is_compact: should_compact,
162                use_alt_impl,
163                is_reference: matches!(field.ty, syn::Type::Reference(_)),
164            }));
165        }
166    }
167}
168
169/// Since there's no impl specialization in rust stable atm, once we find we have a
170/// Vec/Option we try to find out if it's a Vec/Option of a fixed size data type, e.g. `Vec<B256>`.
171///
172/// If so, we use another impl to code/decode its data.
173fn should_use_alt_impl(ftype: &str, segment: &syn::PathSegment) -> bool {
174    if (ftype == "Vec" || ftype == "Option") &&
175        let syn::PathArguments::AngleBracketed(ref args) = segment.arguments &&
176        let Some(syn::GenericArgument::Type(syn::Type::Path(arg_path))) = args.args.last() &&
177        let (Some(path), 1) = (arg_path.path.segments.first(), arg_path.path.segments.len()) &&
178        ["B256", "Address", "Address", "Bloom", "TxHash", "BlockHash", "CompactPlaceholder"]
179            .contains(&path.ident.to_string().as_str())
180    {
181        return true
182    }
183    false
184}
185
186/// Given the field type in a string format, return the amount of bits necessary to save its maximum
187/// length.
188pub fn get_bit_size(ftype: &str) -> u8 {
189    match ftype {
190        "TransactionKind" | "TxKind" | "bool" | "Option" | "Signature" => 1,
191        "TxType" | "OpTxType" => 2,
192        "u64" | "BlockNumber" | "TxNumber" | "ChainId" | "NumTransactions" => 4,
193        "u128" => 5,
194        "U256" => 6,
195        _ => 0,
196    }
197}
198
199/// Given the field type in a string format, checks if its type should be added to the
200/// `StructFlags`.
201pub fn is_flag_type(ftype: &str) -> bool {
202    get_bit_size(ftype) > 0
203}
204
205#[cfg(test)]
206mod tests {
207    use super::*;
208    use similar_asserts::assert_eq;
209    use syn::parse2;
210
211    #[test]
212    fn compact_codec() {
213        let f_struct = quote! {
214             #[derive(Debug, PartialEq, Clone)]
215             pub struct TestStruct {
216                 f_u64: u64,
217                 f_u256: U256,
218                 f_bool_t: bool,
219                 f_bool_f: bool,
220                 f_option_none: Option<U256>,
221                 f_option_some: Option<B256>,
222                 f_option_some_u64: Option<u64>,
223                 f_vec_empty: Vec<U256>,
224                 f_vec_some: Vec<Address>,
225             }
226        };
227
228        // Generate code that will impl the `Compact` trait.
229        let mut output = quote! {};
230        let DeriveInput { ident, data, attrs, .. } = parse2(f_struct).unwrap();
231        let fields = get_fields(&data);
232        output.extend(generate_flag_struct(&ident, &attrs, false, &fields, false));
233        output.extend(generate_from_to(&ident, &attrs, false, &fields, None));
234
235        // Expected output in a TokenStream format. Commas matter!
236        let should_output = quote! {
237            impl TestStruct {
238                #[doc = "Used bytes by [`TestStructFlags`]"]
239                pub const fn bitflag_encoded_bytes() -> usize {
240                    2u8 as usize
241                }
242                #[doc = "Unused bits for new fields by [`TestStructFlags`]"]
243                pub const fn bitflag_unused_bits() -> usize {
244                    1u8 as usize
245                }
246            }
247
248            pub use TestStruct_flags::TestStructFlags;
249
250            #[expect(non_snake_case)]
251            mod TestStruct_flags {
252                use reth_codecs::__private::Buf;
253                use reth_codecs::__private::modular_bitfield;
254                use reth_codecs::__private::modular_bitfield::prelude::*;
255                #[doc = "Fieldset that facilitates compacting the parent type. Used bytes: 2 | Unused bits: 1"]
256                #[bitfield]
257                #[derive(Clone, Copy, Debug, Default)]
258                pub struct TestStructFlags {
259                    pub f_u64_len: B4,
260                    pub f_u256_len: B6,
261                    pub f_bool_t_len: B1,
262                    pub f_bool_f_len: B1,
263                    pub f_option_none_len: B1,
264                    pub f_option_some_len: B1,
265                    pub f_option_some_u64_len: B1,
266                    #[skip]
267                    unused: B1,
268                }
269                impl TestStructFlags {
270                    #[doc = r" Deserializes this fieldset and returns it, alongside the original slice in an advanced position."]
271                    pub fn from(mut buf: &[u8]) -> (Self, &[u8]) {
272                        (
273                            TestStructFlags::from_bytes([buf.get_u8(), buf.get_u8(),]),
274                            buf
275                        )
276                    }
277                }
278            }
279            impl reth_codecs::Compact for TestStruct {
280                fn to_compact<B>(&self, buf: &mut B) -> usize where B: reth_codecs::__private::bytes::BufMut + AsMut<[u8]> {
281                    let mut flags = TestStructFlags::default();
282                    let mut total_length = 0;
283                    let mut buffer = reth_codecs::__private::bytes::BytesMut::new();
284                    let f_u64_len = self.f_u64.to_compact(&mut buffer);
285                    flags.set_f_u64_len(f_u64_len as u8);
286                    let f_u256_len = self.f_u256.to_compact(&mut buffer);
287                    flags.set_f_u256_len(f_u256_len as u8);
288                    let f_bool_t_len = self.f_bool_t.to_compact(&mut buffer);
289                    flags.set_f_bool_t_len(f_bool_t_len as u8);
290                    let f_bool_f_len = self.f_bool_f.to_compact(&mut buffer);
291                    flags.set_f_bool_f_len(f_bool_f_len as u8);
292                    let f_option_none_len = self.f_option_none.to_compact(&mut buffer);
293                    flags.set_f_option_none_len(f_option_none_len as u8);
294                    let f_option_some_len = self.f_option_some.specialized_to_compact(&mut buffer);
295                    flags.set_f_option_some_len(f_option_some_len as u8);
296                    let f_option_some_u64_len = self.f_option_some_u64.to_compact(&mut buffer);
297                    flags.set_f_option_some_u64_len(f_option_some_u64_len as u8);
298                    let f_vec_empty_len = self.f_vec_empty.to_compact(&mut buffer);
299                    let f_vec_some_len = self.f_vec_some.specialized_to_compact(&mut buffer);
300                    let flags = flags.into_bytes();
301                    total_length += flags.len() + buffer.len();
302                    buf.put_slice(&flags);
303                    buf.put(buffer);
304                    total_length
305                }
306                fn from_compact(mut buf: &[u8], len: usize) -> (Self, &[u8]) {
307                    let (flags, mut buf) = TestStructFlags::from(buf);
308                    let (f_u64, new_buf) = u64::from_compact(buf, flags.f_u64_len() as usize);
309                    buf = new_buf;
310                    let (f_u256, new_buf) = U256::from_compact(buf, flags.f_u256_len() as usize);
311                    buf = new_buf;
312                    let (f_bool_t, new_buf) = bool::from_compact(buf, flags.f_bool_t_len() as usize);
313                    buf = new_buf;
314                    let (f_bool_f, new_buf) = bool::from_compact(buf, flags.f_bool_f_len() as usize);
315                    buf = new_buf;
316                    let (f_option_none, new_buf) = Option::from_compact(buf, flags.f_option_none_len() as usize);
317                    buf = new_buf;
318                    let (f_option_some, new_buf) = Option::specialized_from_compact(buf, flags.f_option_some_len() as usize);
319                    buf = new_buf;
320                    let (f_option_some_u64, new_buf) = Option::from_compact(buf, flags.f_option_some_u64_len() as usize);
321                    buf = new_buf;
322                    let (f_vec_empty, new_buf) = Vec::from_compact(buf, buf.len());
323                    buf = new_buf;
324                    let (f_vec_some, new_buf) = Vec::specialized_from_compact(buf, buf.len());
325                    buf = new_buf;
326                    let obj = TestStruct {
327                        f_u64: f_u64,
328                        f_u256: f_u256,
329                        f_bool_t: f_bool_t,
330                        f_bool_f: f_bool_f,
331                        f_option_none: f_option_none,
332                        f_option_some: f_option_some,
333                        f_option_some_u64: f_option_some_u64,
334                        f_vec_empty: f_vec_empty,
335                        f_vec_some: f_vec_some,
336                    };
337                    (obj, buf)
338                }
339            }
340        };
341
342        assert_eq!(
343            syn::parse2::<syn::File>(output).unwrap(),
344            syn::parse2::<syn::File>(should_output).unwrap()
345        );
346    }
347}