reth_codecs_derive/compact/
mod.rs1use 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
20type FieldType = String;
22type UseAlternative = bool;
28#[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}
37type 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
47pub 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
65pub 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
169fn should_use_alt_impl(ftype: &str, segment: &syn::PathSegment) -> bool {
174 if ftype == "Vec" || ftype == "Option" {
175 if let syn::PathArguments::AngleBracketed(ref args) = segment.arguments {
176 if let Some(syn::GenericArgument::Type(syn::Type::Path(arg_path))) = args.args.last() {
177 if let (Some(path), 1) =
178 (arg_path.path.segments.first(), arg_path.path.segments.len())
179 {
180 if [
181 "B256",
182 "Address",
183 "Address",
184 "Bloom",
185 "TxHash",
186 "BlockHash",
187 "CompactPlaceholder",
188 ]
189 .contains(&path.ident.to_string().as_str())
190 {
191 return true
192 }
193 }
194 }
195 }
196 }
197 false
198}
199
200pub fn get_bit_size(ftype: &str) -> u8 {
203 match ftype {
204 "TransactionKind" | "TxKind" | "bool" | "Option" | "Signature" => 1,
205 "TxType" | "OpTxType" => 2,
206 "u64" | "BlockNumber" | "TxNumber" | "ChainId" | "NumTransactions" => 4,
207 "u128" => 5,
208 "U256" => 6,
209 _ => 0,
210 }
211}
212
213pub fn is_flag_type(ftype: &str) -> bool {
216 get_bit_size(ftype) > 0
217}
218
219#[cfg(test)]
220mod tests {
221 use super::*;
222 use similar_asserts::assert_eq;
223 use syn::parse2;
224
225 #[test]
226 fn compact_codec() {
227 let f_struct = quote! {
228 #[derive(Debug, PartialEq, Clone)]
229 pub struct TestStruct {
230 f_u64: u64,
231 f_u256: U256,
232 f_bool_t: bool,
233 f_bool_f: bool,
234 f_option_none: Option<U256>,
235 f_option_some: Option<B256>,
236 f_option_some_u64: Option<u64>,
237 f_vec_empty: Vec<U256>,
238 f_vec_some: Vec<Address>,
239 }
240 };
241
242 let mut output = quote! {};
244 let DeriveInput { ident, data, attrs, .. } = parse2(f_struct).unwrap();
245 let fields = get_fields(&data);
246 output.extend(generate_flag_struct(&ident, &attrs, false, &fields, false));
247 output.extend(generate_from_to(&ident, &attrs, false, &fields, None));
248
249 let should_output = quote! {
251 impl TestStruct {
252 #[doc = "Used bytes by [`TestStructFlags`]"]
253 pub const fn bitflag_encoded_bytes() -> usize {
254 2u8 as usize
255 }
256 #[doc = "Unused bits for new fields by [`TestStructFlags`]"]
257 pub const fn bitflag_unused_bits() -> usize {
258 1u8 as usize
259 }
260 }
261
262 pub use TestStruct_flags::TestStructFlags;
263
264 #[expect(non_snake_case)]
265 mod TestStruct_flags {
266 use reth_codecs::__private::Buf;
267 use reth_codecs::__private::modular_bitfield;
268 use reth_codecs::__private::modular_bitfield::prelude::*;
269 #[doc = "Fieldset that facilitates compacting the parent type. Used bytes: 2 | Unused bits: 1"]
270 #[bitfield]
271 #[derive(Clone, Copy, Debug, Default)]
272 pub struct TestStructFlags {
273 pub f_u64_len: B4,
274 pub f_u256_len: B6,
275 pub f_bool_t_len: B1,
276 pub f_bool_f_len: B1,
277 pub f_option_none_len: B1,
278 pub f_option_some_len: B1,
279 pub f_option_some_u64_len: B1,
280 #[skip]
281 unused: B1,
282 }
283 impl TestStructFlags {
284 #[doc = r" Deserializes this fieldset and returns it, alongside the original slice in an advanced position."]
285 pub fn from(mut buf: &[u8]) -> (Self, &[u8]) {
286 (
287 TestStructFlags::from_bytes([buf.get_u8(), buf.get_u8(),]),
288 buf
289 )
290 }
291 }
292 }
293 #[cfg(test)]
294 #[expect(dead_code)]
295 #[test_fuzz::test_fuzz]
296 fn fuzz_test_test_struct(obj: TestStruct) {
297 use reth_codecs::Compact;
298 let mut buf = vec![];
299 let len = obj.clone().to_compact(&mut buf);
300 let (same_obj, buf) = TestStruct::from_compact(buf.as_ref(), len);
301 assert_eq!(obj, same_obj);
302 }
303 #[test]
304 #[expect(missing_docs)]
305 pub fn fuzz_test_struct() {
306 fuzz_test_test_struct(TestStruct::default())
307 }
308 impl reth_codecs::Compact for TestStruct {
309 fn to_compact<B>(&self, buf: &mut B) -> usize where B: reth_codecs::__private::bytes::BufMut + AsMut<[u8]> {
310 let mut flags = TestStructFlags::default();
311 let mut total_length = 0;
312 let mut buffer = reth_codecs::__private::bytes::BytesMut::new();
313 let f_u64_len = self.f_u64.to_compact(&mut buffer);
314 flags.set_f_u64_len(f_u64_len as u8);
315 let f_u256_len = self.f_u256.to_compact(&mut buffer);
316 flags.set_f_u256_len(f_u256_len as u8);
317 let f_bool_t_len = self.f_bool_t.to_compact(&mut buffer);
318 flags.set_f_bool_t_len(f_bool_t_len as u8);
319 let f_bool_f_len = self.f_bool_f.to_compact(&mut buffer);
320 flags.set_f_bool_f_len(f_bool_f_len as u8);
321 let f_option_none_len = self.f_option_none.to_compact(&mut buffer);
322 flags.set_f_option_none_len(f_option_none_len as u8);
323 let f_option_some_len = self.f_option_some.specialized_to_compact(&mut buffer);
324 flags.set_f_option_some_len(f_option_some_len as u8);
325 let f_option_some_u64_len = self.f_option_some_u64.to_compact(&mut buffer);
326 flags.set_f_option_some_u64_len(f_option_some_u64_len as u8);
327 let f_vec_empty_len = self.f_vec_empty.to_compact(&mut buffer);
328 let f_vec_some_len = self.f_vec_some.specialized_to_compact(&mut buffer);
329 let flags = flags.into_bytes();
330 total_length += flags.len() + buffer.len();
331 buf.put_slice(&flags);
332 buf.put(buffer);
333 total_length
334 }
335 fn from_compact(mut buf: &[u8], len: usize) -> (Self, &[u8]) {
336 let (flags, mut buf) = TestStructFlags::from(buf);
337 let (f_u64, new_buf) = u64::from_compact(buf, flags.f_u64_len() as usize);
338 buf = new_buf;
339 let (f_u256, new_buf) = U256::from_compact(buf, flags.f_u256_len() as usize);
340 buf = new_buf;
341 let (f_bool_t, new_buf) = bool::from_compact(buf, flags.f_bool_t_len() as usize);
342 buf = new_buf;
343 let (f_bool_f, new_buf) = bool::from_compact(buf, flags.f_bool_f_len() as usize);
344 buf = new_buf;
345 let (f_option_none, new_buf) = Option::from_compact(buf, flags.f_option_none_len() as usize);
346 buf = new_buf;
347 let (f_option_some, new_buf) = Option::specialized_from_compact(buf, flags.f_option_some_len() as usize);
348 buf = new_buf;
349 let (f_option_some_u64, new_buf) = Option::from_compact(buf, flags.f_option_some_u64_len() as usize);
350 buf = new_buf;
351 let (f_vec_empty, new_buf) = Vec::from_compact(buf, buf.len());
352 buf = new_buf;
353 let (f_vec_some, new_buf) = Vec::specialized_from_compact(buf, buf.len());
354 buf = new_buf;
355 let obj = TestStruct {
356 f_u64: f_u64,
357 f_u256: f_u256,
358 f_bool_t: f_bool_t,
359 f_bool_f: f_bool_f,
360 f_option_none: f_option_none,
361 f_option_some: f_option_some,
362 f_option_some_u64: f_option_some_u64,
363 f_vec_empty: f_vec_empty,
364 f_vec_some: f_vec_some,
365 };
366 (obj, buf)
367 }
368 }
369 };
370
371 assert_eq!(
372 syn::parse2::<syn::File>(output).unwrap(),
373 syn::parse2::<syn::File>(should_output).unwrap()
374 );
375 }
376}