Skip to content

Commit

Permalink
Inline TryFromBytes derive for variant structs (#1709)
Browse files Browse the repository at this point in the history
  • Loading branch information
djkoloski authored Sep 24, 2024
1 parent bc9c38f commit 5dcc4c7
Show file tree
Hide file tree
Showing 4 changed files with 478 additions and 45 deletions.
16 changes: 12 additions & 4 deletions zerocopy-derive/src/enum.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,9 @@
use ::proc_macro2::TokenStream;
use ::quote::quote;
use ::syn::{DataEnum, Fields, Generics, Ident};
use syn::parse_quote;

use crate::{EnumRepr, Trait};
use crate::{derive_try_from_bytes_inner, EnumRepr, Trait};

/// Returns the repr for the tag enum, given the collection of reprs on the
/// enum.
Expand Down Expand Up @@ -141,19 +142,26 @@ fn generate_variant_structs(
return None;
}

let trait_path = Trait::TryFromBytes.derive_path();
let variant_struct_ident = variant_struct_ident(&variant.ident);
let field_types = variant.fields.iter().map(|f| &f.ty);

Some(quote! {
let variant_struct = parse_quote! {
#[repr(C)]
#[allow(non_snake_case)]
#[derive(#trait_path)]
struct #variant_struct_ident #impl_generics (
core_reexport::mem::MaybeUninit<___ZerocopyInnerTag>,
#(#field_types,)*
#phantom_ty,
) #where_clause;
};

// We do this rather than emitting `#[derive(::zerocopy::TryFromBytes)]`
// because that is not hygienic, and this is also more performant.
let try_from_bytes_impl = derive_try_from_bytes_inner(&variant_struct);

Some(quote! {
#variant_struct
#try_from_bytes_impl
})
});

Expand Down
7 changes: 0 additions & 7 deletions zerocopy-derive/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1083,13 +1083,6 @@ impl Trait {
_ => parse_quote!(::zerocopy::#self),
}
}

fn derive_path(&self) -> Path {
match self {
Self::Sized => panic!("no derive path for builtin types"),
_ => parse_quote!(::zerocopy_derive::#self),
}
}
}

#[derive(Debug, Eq, PartialEq)]
Expand Down
Loading

0 comments on commit 5dcc4c7

Please sign in to comment.