Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

support deriving Zeroable for fieldless enums #233

Merged
merged 2 commits into from
May 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 33 additions & 1 deletion derive/src/traits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -124,11 +124,43 @@ impl Derivable for Zeroable {
Ok(syn::parse_quote!(#crate_name::Zeroable))
}

fn check_attributes(ty: &Data, attributes: &[Attribute]) -> Result<()> {
let repr = get_repr(attributes)?;
match ty {
Data::Struct(_) => Ok(()),
Data::Enum(DataEnum { variants,.. }) => {
if !repr.repr.is_integer() {
bail!("Zeroable requires the enum to be an explicit #[repr(Int)]")
}

if variants.iter().any(|variant| !variant.fields.is_empty()) {
bail!("Only fieldless enums are supported for Zeroable")
}

let iter = VariantDiscriminantIterator::new(variants.iter());
let mut has_zero_variant = false;
for res in iter {
let discriminant = res?;
if discriminant == 0 {
has_zero_variant = true;
break;
}
}
if !has_zero_variant {
bail!("No variant's discriminant is 0")
}

Ok(())
},
Data::Union(_) => Ok(())
}
}

fn asserts(input: &DeriveInput, crate_name: &TokenStream) -> Result<TokenStream> {
match &input.data {
Data::Union(_) => Ok(quote!()), // unions are always `Zeroable`
Data::Struct(_) => generate_fields_are_trait(input, Self::ident(input, crate_name)?),
Data::Enum(_) => bail!("Deriving Zeroable is not supported for enums"),
Data::Enum(_) => Ok(quote!()),
}
}

Expand Down
8 changes: 8 additions & 0 deletions derive/tests/basic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,14 @@ struct ZeroGeneric<T: bytemuck::Zeroable> {
a: T,
}

#[derive(Zeroable)]
#[repr(u8)]
enum ZeroEnum {
A = 0,
B = 1,
C = 2,
}

#[derive(TransparentWrapper)]
#[repr(transparent)]
struct TransparentSingle {
Expand Down
Loading