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 => unimplemented!("Compact does not support unit structs"),
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(_) => unimplemented!("Compact does not support union types"),
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 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 .iter()
180 .any(|&s| path.ident == s)
181 {
182 return true
183 }
184 false
185}
186
187pub fn get_bit_size(ftype: &str) -> u8 {
190 match ftype {
191 "TransactionKind" | "TxKind" | "bool" | "Option" | "Signature" => 1,
192 "TxType" | "OpTxType" => 2,
193 "u64" | "BlockNumber" | "TxNumber" | "ChainId" | "NumTransactions" => 4,
194 "u128" => 5,
195 "U256" => 6,
196 _ => 0,
197 }
198}
199
200pub fn is_flag_type(ftype: &str) -> bool {
203 get_bit_size(ftype) > 0
204}
205
206#[cfg(test)]
207mod tests {
208 use super::*;
209 use similar_asserts::assert_eq;
210 use syn::parse2;
211
212 #[test]
213 fn compact_codec() {
214 let f_struct = quote! {
215 #[derive(Debug, PartialEq, Clone)]
216 pub struct TestStruct {
217 f_u64: u64,
218 f_u256: U256,
219 f_bool_t: bool,
220 f_bool_f: bool,
221 f_option_none: Option<U256>,
222 f_option_some: Option<B256>,
223 f_option_some_u64: Option<u64>,
224 f_vec_empty: Vec<U256>,
225 f_vec_some: Vec<Address>,
226 }
227 };
228
229 let mut output = quote! {};
231 let DeriveInput { ident, data, attrs, .. } = parse2(f_struct).unwrap();
232 let fields = get_fields(&data);
233 output.extend(generate_flag_struct(&ident, &attrs, false, &fields, false));
234 output.extend(generate_from_to(&ident, &attrs, false, &fields, None));
235
236 let should_output = quote! {
238 impl TestStruct {
239 #[doc = "Used bytes by [`TestStructFlags`]"]
240 pub const fn bitflag_encoded_bytes() -> usize {
241 2usize
242 }
243 #[doc = "Unused bits for new fields by [`TestStructFlags`]"]
244 pub const fn bitflag_unused_bits() -> usize {
245 1usize
246 }
247 }
248
249 pub use TestStruct_flags::TestStructFlags;
250
251 #[expect(non_snake_case)]
252 mod TestStruct_flags {
253 use reth_codecs::__private::Buf;
254 use reth_codecs::__private::modular_bitfield;
255 use reth_codecs::__private::modular_bitfield::prelude::*;
256 #[doc = "Fieldset that facilitates compacting the parent type. Used bytes: 2 | Unused bits: 1"]
257 #[bitfield]
258 #[derive(Clone, Copy, Debug, Default)]
259 pub struct TestStructFlags {
260 pub f_u64_len: B4,
261 pub f_u256_len: B6,
262 pub f_bool_t_len: B1,
263 pub f_bool_f_len: B1,
264 pub f_option_none_len: B1,
265 pub f_option_some_len: B1,
266 pub f_option_some_u64_len: B1,
267 #[skip]
268 unused: B1,
269 }
270 impl TestStructFlags {
271 #[doc = r" Deserializes this fieldset and returns it, alongside the original slice in an advanced position."]
272 pub fn from(mut buf: &[u8]) -> (Self, &[u8]) {
273 (
274 TestStructFlags::from_bytes([buf.get_u8(), buf.get_u8(),]),
275 buf
276 )
277 }
278 }
279 }
280 impl reth_codecs::Compact for TestStruct {
281 fn to_compact<B>(&self, buf: &mut B) -> usize where B: reth_codecs::__private::bytes::BufMut + AsMut<[u8]> {
282 let mut flags = TestStructFlags::default();
283 let mut total_length = 0;
284 let mut buffer = reth_codecs::__private::bytes::BytesMut::new();
285 let f_u64_len = self.f_u64.to_compact(&mut buffer);
286 flags.set_f_u64_len(f_u64_len as u8);
287 let f_u256_len = self.f_u256.to_compact(&mut buffer);
288 flags.set_f_u256_len(f_u256_len as u8);
289 let f_bool_t_len = self.f_bool_t.to_compact(&mut buffer);
290 flags.set_f_bool_t_len(f_bool_t_len as u8);
291 let f_bool_f_len = self.f_bool_f.to_compact(&mut buffer);
292 flags.set_f_bool_f_len(f_bool_f_len as u8);
293 let f_option_none_len = self.f_option_none.to_compact(&mut buffer);
294 flags.set_f_option_none_len(f_option_none_len as u8);
295 let f_option_some_len = self.f_option_some.specialized_to_compact(&mut buffer);
296 flags.set_f_option_some_len(f_option_some_len as u8);
297 let f_option_some_u64_len = self.f_option_some_u64.to_compact(&mut buffer);
298 flags.set_f_option_some_u64_len(f_option_some_u64_len as u8);
299 let f_vec_empty_len = self.f_vec_empty.to_compact(&mut buffer);
300 let f_vec_some_len = self.f_vec_some.specialized_to_compact(&mut buffer);
301 let flags = flags.into_bytes();
302 total_length += flags.len() + buffer.len();
303 buf.put_slice(&flags);
304 buf.put(buffer);
305 total_length
306 }
307 fn from_compact(mut buf: &[u8], len: usize) -> (Self, &[u8]) {
308 let (flags, mut buf) = TestStructFlags::from(buf);
309 let (f_u64, new_buf) = u64::from_compact(buf, flags.f_u64_len() as usize);
310 buf = new_buf;
311 let (f_u256, new_buf) = U256::from_compact(buf, flags.f_u256_len() as usize);
312 buf = new_buf;
313 let (f_bool_t, new_buf) = bool::from_compact(buf, flags.f_bool_t_len() as usize);
314 buf = new_buf;
315 let (f_bool_f, new_buf) = bool::from_compact(buf, flags.f_bool_f_len() as usize);
316 buf = new_buf;
317 let (f_option_none, new_buf) = Option::from_compact(buf, flags.f_option_none_len() as usize);
318 buf = new_buf;
319 let (f_option_some, new_buf) = Option::specialized_from_compact(buf, flags.f_option_some_len() as usize);
320 buf = new_buf;
321 let (f_option_some_u64, new_buf) = Option::from_compact(buf, flags.f_option_some_u64_len() as usize);
322 buf = new_buf;
323 let (f_vec_empty, new_buf) = Vec::from_compact(buf, buf.len());
324 buf = new_buf;
325 let (f_vec_some, new_buf) = Vec::specialized_from_compact(buf, buf.len());
326 buf = new_buf;
327 let obj = TestStruct {
328 f_u64: f_u64,
329 f_u256: f_u256,
330 f_bool_t: f_bool_t,
331 f_bool_f: f_bool_f,
332 f_option_none: f_option_none,
333 f_option_some: f_option_some,
334 f_option_some_u64: f_option_some_u64,
335 f_vec_empty: f_vec_empty,
336 f_vec_some: f_vec_some,
337 };
338 (obj, buf)
339 }
340 }
341 };
342
343 assert_eq!(
344 syn::parse2::<syn::File>(output).unwrap(),
345 syn::parse2::<syn::File>(should_output).unwrap()
346 );
347 }
348}