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!("Not allowed to have Enum Variants with multiple named fields. Make it a struct instead.")
94                    }
95                    syn::Fields::Unnamed(data_fields) => {
96                        assert_eq!(
97                            data_fields.unnamed.len(),
98                            1,
99                            "Compact only allows one unnamed field. Consider making it a struct."
100                        );
101                        load_field(&data_fields.unnamed[0], &mut fields, true);
102                    }
103                    syn::Fields::Unit => (),
104                }
105            }
106        }
107        Data::Union(_) => todo!(),
108    }
109
110    fields
111}
112
113fn load_field(field: &syn::Field, fields: &mut FieldList, is_enum: bool) {
114    match field.ty {
115        syn::Type::Reference(ref reference) => match &*reference.elem {
116            syn::Type::Path(path) => {
117                load_field_from_segments(&path.path.segments, is_enum, fields, field)
118            }
119            _ => unimplemented!("{:?}", &field.ident),
120        },
121        syn::Type::Path(ref path) => {
122            load_field_from_segments(&path.path.segments, is_enum, fields, field)
123        }
124        _ => unimplemented!("{:?}", &field.ident),
125    }
126}
127
128fn load_field_from_segments(
129    segments: &syn::punctuated::Punctuated<syn::PathSegment, syn::token::PathSep>,
130    is_enum: bool,
131    fields: &mut Vec<FieldTypes>,
132    field: &syn::Field,
133) {
134    if !segments.is_empty() {
135        let mut ftype = String::new();
136
137        let mut use_alt_impl: UseAlternative = false;
138
139        for (index, segment) in segments.iter().enumerate() {
140            ftype.push_str(&segment.ident.to_string());
141            if index < segments.len() - 1 {
142                ftype.push_str("::");
143            }
144
145            use_alt_impl = should_use_alt_impl(&ftype, segment);
146        }
147
148        if is_enum {
149            fields.push(FieldTypes::EnumUnnamedField((ftype, use_alt_impl)));
150        } else {
151            let should_compact = is_flag_type(&ftype) ||
152                field.attrs.iter().any(|attr| {
153                    attr.path().segments.iter().any(|path| path.ident == "maybe_zero")
154                });
155
156            fields.push(FieldTypes::StructField(StructFieldDescriptor {
157                name: field.ident.as_ref().map(|i| i.to_string()).unwrap_or_default(),
158                ftype,
159                is_compact: should_compact,
160                use_alt_impl,
161                is_reference: matches!(field.ty, syn::Type::Reference(_)),
162            }));
163        }
164    }
165}
166
167/// Since there's no impl specialization in rust stable atm, once we find we have a
168/// Vec/Option we try to find out if it's a Vec/Option of a fixed size data type, e.g. `Vec<B256>`.
169///
170/// If so, we use another impl to code/decode its data.
171fn should_use_alt_impl(ftype: &str, segment: &syn::PathSegment) -> bool {
172    if ftype == "Vec" || ftype == "Option" {
173        if let syn::PathArguments::AngleBracketed(ref args) = segment.arguments {
174            if let Some(syn::GenericArgument::Type(syn::Type::Path(arg_path))) = args.args.last() {
175                if let (Some(path), 1) =
176                    (arg_path.path.segments.first(), arg_path.path.segments.len())
177                {
178                    if [
179                        "B256",
180                        "Address",
181                        "Address",
182                        "Bloom",
183                        "TxHash",
184                        "BlockHash",
185                        "CompactPlaceholder",
186                    ]
187                    .contains(&path.ident.to_string().as_str())
188                    {
189                        return true
190                    }
191                }
192            }
193        }
194    }
195    false
196}
197
198/// Given the field type in a string format, return the amount of bits necessary to save its maximum
199/// length.
200pub fn get_bit_size(ftype: &str) -> u8 {
201    match ftype {
202        "TransactionKind" | "TxKind" | "bool" | "Option" | "Signature" => 1,
203        "TxType" | "OpTxType" => 2,
204        "u64" | "BlockNumber" | "TxNumber" | "ChainId" | "NumTransactions" => 4,
205        "u128" => 5,
206        "U256" => 6,
207        _ => 0,
208    }
209}
210
211/// Given the field type in a string format, checks if its type should be added to the
212/// `StructFlags`.
213pub fn is_flag_type(ftype: &str) -> bool {
214    get_bit_size(ftype) > 0
215}
216
217#[cfg(test)]
218mod tests {
219    use super::*;
220    use similar_asserts::assert_eq;
221    use syn::parse2;
222
223    #[test]
224    fn gen() {
225        let f_struct = quote! {
226             #[derive(Debug, PartialEq, Clone)]
227             pub struct TestStruct {
228                 f_u64: u64,
229                 f_u256: U256,
230                 f_bool_t: bool,
231                 f_bool_f: bool,
232                 f_option_none: Option<U256>,
233                 f_option_some: Option<B256>,
234                 f_option_some_u64: Option<u64>,
235                 f_vec_empty: Vec<U256>,
236                 f_vec_some: Vec<Address>,
237             }
238        };
239
240        // Generate code that will impl the `Compact` trait.
241        let mut output = quote! {};
242        let DeriveInput { ident, data, attrs, .. } = parse2(f_struct).unwrap();
243        let fields = get_fields(&data);
244        output.extend(generate_flag_struct(&ident, &attrs, false, &fields, false));
245        output.extend(generate_from_to(&ident, &attrs, false, &fields, None));
246
247        // Expected output in a TokenStream format. Commas matter!
248        let should_output = quote! {
249            impl TestStruct {
250                #[doc = "Used bytes by [`TestStructFlags`]"]
251                pub const fn bitflag_encoded_bytes() -> usize {
252                    2u8 as usize
253                }
254                #[doc = "Unused bits for new fields by [`TestStructFlags`]"]
255                pub const fn bitflag_unused_bits() -> usize {
256                    1u8 as usize
257                }
258            }
259
260            pub use TestStruct_flags::TestStructFlags;
261
262            #[expect(non_snake_case)]
263            mod TestStruct_flags {
264                use reth_codecs::__private::Buf;
265                use reth_codecs::__private::modular_bitfield;
266                use reth_codecs::__private::modular_bitfield::prelude::*;
267                #[doc = "Fieldset that facilitates compacting the parent type. Used bytes: 2 | Unused bits: 1"]
268                #[bitfield]
269                #[derive(Clone, Copy, Debug, Default)]
270                pub struct TestStructFlags {
271                    pub f_u64_len: B4,
272                    pub f_u256_len: B6,
273                    pub f_bool_t_len: B1,
274                    pub f_bool_f_len: B1,
275                    pub f_option_none_len: B1,
276                    pub f_option_some_len: B1,
277                    pub f_option_some_u64_len: B1,
278                    #[skip]
279                    unused: B1,
280                }
281                impl TestStructFlags {
282                    #[doc = r" Deserializes this fieldset and returns it, alongside the original slice in an advanced position."]
283                    pub fn from(mut buf: &[u8]) -> (Self, &[u8]) {
284                        (
285                            TestStructFlags::from_bytes([buf.get_u8(), buf.get_u8(),]),
286                            buf
287                        )
288                    }
289                }
290            }
291            #[cfg(test)]
292            #[expect(dead_code)]
293            #[test_fuzz::test_fuzz]
294            fn fuzz_test_test_struct(obj: TestStruct) {
295                use reth_codecs::Compact;
296                let mut buf = vec![];
297                let len = obj.clone().to_compact(&mut buf);
298                let (same_obj, buf) = TestStruct::from_compact(buf.as_ref(), len);
299                assert_eq!(obj, same_obj);
300            }
301            #[test]
302            #[expect(missing_docs)]
303            pub fn fuzz_test_struct() {
304                fuzz_test_test_struct(TestStruct::default())
305            }
306            impl reth_codecs::Compact for TestStruct {
307                fn to_compact<B>(&self, buf: &mut B) -> usize where B: reth_codecs::__private::bytes::BufMut + AsMut<[u8]> {
308                    let mut flags = TestStructFlags::default();
309                    let mut total_length = 0;
310                    let mut buffer = reth_codecs::__private::bytes::BytesMut::new();
311                    let f_u64_len = self.f_u64.to_compact(&mut buffer);
312                    flags.set_f_u64_len(f_u64_len as u8);
313                    let f_u256_len = self.f_u256.to_compact(&mut buffer);
314                    flags.set_f_u256_len(f_u256_len as u8);
315                    let f_bool_t_len = self.f_bool_t.to_compact(&mut buffer);
316                    flags.set_f_bool_t_len(f_bool_t_len as u8);
317                    let f_bool_f_len = self.f_bool_f.to_compact(&mut buffer);
318                    flags.set_f_bool_f_len(f_bool_f_len as u8);
319                    let f_option_none_len = self.f_option_none.to_compact(&mut buffer);
320                    flags.set_f_option_none_len(f_option_none_len as u8);
321                    let f_option_some_len = self.f_option_some.specialized_to_compact(&mut buffer);
322                    flags.set_f_option_some_len(f_option_some_len as u8);
323                    let f_option_some_u64_len = self.f_option_some_u64.to_compact(&mut buffer);
324                    flags.set_f_option_some_u64_len(f_option_some_u64_len as u8);
325                    let f_vec_empty_len = self.f_vec_empty.to_compact(&mut buffer);
326                    let f_vec_some_len = self.f_vec_some.specialized_to_compact(&mut buffer);
327                    let flags = flags.into_bytes();
328                    total_length += flags.len() + buffer.len();
329                    buf.put_slice(&flags);
330                    buf.put(buffer);
331                    total_length
332                }
333                fn from_compact(mut buf: &[u8], len: usize) -> (Self, &[u8]) {
334                    let (flags, mut buf) = TestStructFlags::from(buf);
335                    let (f_u64, new_buf) = u64::from_compact(buf, flags.f_u64_len() as usize);
336                    buf = new_buf;
337                    let (f_u256, new_buf) = U256::from_compact(buf, flags.f_u256_len() as usize);
338                    buf = new_buf;
339                    let (f_bool_t, new_buf) = bool::from_compact(buf, flags.f_bool_t_len() as usize);
340                    buf = new_buf;
341                    let (f_bool_f, new_buf) = bool::from_compact(buf, flags.f_bool_f_len() as usize);
342                    buf = new_buf;
343                    let (f_option_none, new_buf) = Option::from_compact(buf, flags.f_option_none_len() as usize);
344                    buf = new_buf;
345                    let (f_option_some, new_buf) = Option::specialized_from_compact(buf, flags.f_option_some_len() as usize);
346                    buf = new_buf;
347                    let (f_option_some_u64, new_buf) = Option::from_compact(buf, flags.f_option_some_u64_len() as usize);
348                    buf = new_buf;
349                    let (f_vec_empty, new_buf) = Vec::from_compact(buf, buf.len());
350                    buf = new_buf;
351                    let (f_vec_some, new_buf) = Vec::specialized_from_compact(buf, buf.len());
352                    buf = new_buf;
353                    let obj = TestStruct {
354                        f_u64: f_u64,
355                        f_u256: f_u256,
356                        f_bool_t: f_bool_t,
357                        f_bool_f: f_bool_f,
358                        f_option_none: f_option_none,
359                        f_option_some: f_option_some,
360                        f_option_some_u64: f_option_some_u64,
361                        f_vec_empty: f_vec_empty,
362                        f_vec_some: f_vec_some,
363                    };
364                    (obj, buf)
365                }
366            }
367        };
368
369        assert_eq!(
370            syn::parse2::<syn::File>(output).unwrap(),
371            syn::parse2::<syn::File>(should_output).unwrap()
372        );
373    }
374}