Skip to content

Commit

Permalink
Pass where clause on struct through bitsize macros
Browse files Browse the repository at this point in the history
  • Loading branch information
kitlith committed Sep 5, 2023
1 parent 123ee67 commit c3cc057
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 22 deletions.
26 changes: 5 additions & 21 deletions bilge-impl/src/bitsize.rs
Original file line number Diff line number Diff line change
Expand Up @@ -121,38 +121,22 @@ fn analyze_enum(bitsize: BitSize, variants: Iter<Variant>) {
}

fn generate_struct(item: &ItemStruct, declared_bitsize: u8) -> TokenStream {
let ItemStruct {
vis,
ident,
fields,
generics,
..
} = item;
let ItemStruct { ident, fields, generics, .. } = item;
let declared_bitsize = declared_bitsize as usize;

let computed_bitsize = fields.iter().fold(quote!(0), |acc, next| {
let field_size = shared::generate_type_bitsize(&next.ty);
quote!(#acc + #field_size)
});

// we could remove this if the whole struct gets passed
let is_tuple_struct = fields.iter().any(|field| field.ident.is_none());
let fields_def = if is_tuple_struct {
let fields = fields.iter();
quote! {
( #(#fields,)* );
}
} else {
let fields = fields.iter();
quote! {
{ #(#fields,)* }
}
};
// The only part of the struct we don't want to pass through are the attributes
let mut item = item.clone();
item.attrs = Vec::new();

let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();

quote! {
#vis struct #ident #generics #fields_def
#item

impl #impl_generics #ident #ty_generics #where_clause {
// constness: when we get const blocks evaluated at compile time, add a const computed_bitsize
Expand Down
2 changes: 1 addition & 1 deletion bilge-impl/src/bitsize_internal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ fn generate_struct(struct_data: &ItemStruct, arb_int: &TokenStream) -> TokenStre
let const_ = if cfg!(feature = "nightly") { quote!(const) } else { quote!() };

quote! {
#vis struct #ident #generics {
#vis struct #ident #generics #where_clause {
/// WARNING: modifying this value directly can break invariants
value: #arb_int,
_phantom: ::core::marker::PhantomData<(#(#phantom),*)>
Expand Down

0 comments on commit c3cc057

Please sign in to comment.