#![cfg(feature = "max-encoded-len")]
use crate::{
trait_bounds,
utils::{self, codec_crate_path, custom_mel_trait_bound, has_dumb_trait_bound, should_skip},
};
use quote::{quote, quote_spanned};
use syn::{parse_quote, spanned::Spanned, Data, DeriveInput, Field, Fields};
pub fn derive_max_encoded_len(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
let mut input: DeriveInput = match syn::parse(input) {
Ok(input) => input,
Err(e) => return e.to_compile_error().into(),
};
let crate_path = match codec_crate_path(&input.attrs) {
Ok(crate_path) => crate_path,
Err(error) => return error.into_compile_error().into(),
};
let name = &input.ident;
if let Err(e) = trait_bounds::add(
&input.ident,
&mut input.generics,
&input.data,
custom_mel_trait_bound(&input.attrs),
parse_quote!(#crate_path::MaxEncodedLen),
None,
has_dumb_trait_bound(&input.attrs),
&crate_path,
) {
return e.to_compile_error().into()
}
let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();
let data_expr = data_length_expr(&input.data, &crate_path);
quote::quote!(
const _: () = {
impl #impl_generics #crate_path::MaxEncodedLen for #name #ty_generics #where_clause {
fn max_encoded_len() -> ::core::primitive::usize {
#data_expr
}
}
};
)
.into()
}
fn fields_length_expr(fields: &Fields, crate_path: &syn::Path) -> proc_macro2::TokenStream {
let fields_iter: Box<dyn Iterator<Item = &Field>> = match fields {
Fields::Named(ref fields) => Box::new(fields.named.iter().filter_map(|field| {
if should_skip(&field.attrs) {
None
} else {
Some(field)
}
})),
Fields::Unnamed(ref fields) => Box::new(fields.unnamed.iter().filter_map(|field| {
if should_skip(&field.attrs) {
None
} else {
Some(field)
}
})),
Fields::Unit => Box::new(std::iter::empty()),
};
let expansion = fields_iter.map(|field| {
let ty = &field.ty;
if utils::is_compact(&field) {
quote_spanned! {
ty.span() => .saturating_add(
<<#ty as #crate_path::HasCompact>::Type as #crate_path::MaxEncodedLen>::max_encoded_len()
)
}
} else {
quote_spanned! {
ty.span() => .saturating_add(<#ty as #crate_path::MaxEncodedLen>::max_encoded_len())
}
}
});
quote! {
0_usize #( #expansion )*
}
}
fn data_length_expr(data: &Data, crate_path: &syn::Path) -> proc_macro2::TokenStream {
match *data {
Data::Struct(ref data) => fields_length_expr(&data.fields, crate_path),
Data::Enum(ref data) => {
let expansion = data.variants.iter().map(|variant| {
let variant_expression = fields_length_expr(&variant.fields, crate_path);
quote! {
.max(#variant_expression)
}
});
quote! {
0_usize #( #expansion )* .saturating_add(1)
}
},
Data::Union(ref data) => {
syn::Error::new(data.union_token.span(), "Union types are not supported.")
.to_compile_error()
},
}
}