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

add support for deriving NoUninit on enums with fields #292

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
70 changes: 57 additions & 13 deletions derive/src/traits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ impl Derivable for Pod {
match &input.data {
Data::Struct(_) => {
let assert_no_padding = if !completly_packed {
Some(generate_assert_no_padding(input)?)
Some(generate_assert_no_padding(input, None)?)
} else {
None
};
Expand Down Expand Up @@ -237,10 +237,18 @@ impl Derivable for NoUninit {
Repr::C | Repr::Transparent => Ok(()),
_ => bail!("NoUninit requires the struct to be #[repr(C)] or #[repr(transparent)]"),
},
Data::Enum(_) => if repr.repr.is_integer() {
Ok(())
} else {
bail!("NoUninit requires the enum to be an explicit #[repr(Int)]")
Data::Enum(DataEnum { variants,.. }) => {
if !enum_has_fields(variants.iter()){
if repr.repr.is_integer() {
Ok(())
} else {
bail!("NoUninit requires the enum to be an explicit #[repr(Int)]")
}
} else if matches!(repr.repr, Repr::Rust) {
bail!("NoUninit requires an explicit repr annotation because `repr(Rust)` doesn't have a specified type layout")
} else {
Ok(())
}
},
Data::Union(_) => bail!("NoUninit can only be derived on enums and structs")
}
Expand All @@ -255,7 +263,7 @@ impl Derivable for NoUninit {

match &input.data {
Data::Struct(DataStruct { .. }) => {
let assert_no_padding = generate_assert_no_padding(&input)?;
let assert_no_padding = generate_assert_no_padding(&input, None)?;
let assert_fields_are_no_padding = generate_fields_are_trait(
&input,
None,
Expand All @@ -268,8 +276,24 @@ impl Derivable for NoUninit {
))
}
Data::Enum(DataEnum { variants, .. }) => {
if variants.iter().any(|variant| !variant.fields.is_empty()) {
bail!("Only fieldless enums are supported for NoUninit")
if enum_has_fields(variants.iter()) {
variants
.iter()
.map(|variant| {
let assert_no_padding =
generate_assert_no_padding(&input, Some(variant))?;
let assert_fields_are_no_padding = generate_fields_are_trait(
&input,
Some(variant),
Self::ident(input, crate_name)?,
)?;

Ok(quote!(
#assert_no_padding
#assert_fields_are_no_padding
))
})
.collect()
} else {
Ok(quote!())
}
Expand Down Expand Up @@ -981,14 +1005,34 @@ fn generate_checked_bit_pattern_enum_with_fields(
}
}

/// Check that a struct has no padding by asserting that the size of the struct
/// is equal to the sum of the size of it's fields
fn generate_assert_no_padding(input: &DeriveInput) -> Result<TokenStream> {
/// Check that a struct or enum has no padding by asserting that the size of
/// the type is equal to the sum of the size of it's fields and enum
/// discriminant
fn generate_assert_no_padding(
input: &DeriveInput, enum_variant: Option<&Variant>,
) -> Result<TokenStream> {
let struct_type = &input.ident;
let enum_variant = None; // `no padding` check is not supported for `enum`s yet.
let fields = get_fields(input, enum_variant)?;

let mut field_types = get_field_types(&fields);
// If the type is an enum, determine the type of its discriminant.
let enum_discriminant = if matches!(input.data, Data::Enum(_)) {
let repr = get_repr(&input.attrs)?;
let integer = match repr.repr {
Repr::C => quote!(::core::ffi::c_int),
Repr::Integer(integer) | Repr::CWithDiscriminant(integer) => {
quote!(#integer)
}
_ => unreachable!(),
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
_ => unreachable!(),
_ => bail!("Deriving NoUninit is not currently supported for repr(Int) enums with fields")

#[repr(Int)] enums also have a (different) defined layout to #[repr(C)]/#[repr(C, Int)], so ideally those would also be allowed, but if you don't want to add that in this PR, then this should probably be a bail! with an error message instead of unreachable!.

E.g. this unreachable!() currently causes a "proc-macro derive panicked" for a #[repr(u8)] enum.

use bytemuck::NoUninit;

#[derive(Debug, Clone, Copy, NoUninit)]
#[repr(u8)]
enum Foo {
    A(u8),
}
error: proc-macro derive panicked
 --> src/lib.rs:3:30
  |
3 | #[derive(Debug, Clone, Copy, NoUninit)]
  |                              ^^^^^^^^
  |
  = help: message: internal error: entered unreachable code

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch, thanks! AFAICT the layout is the same if there is no padding, so adding support for this was easy. I added a test for #[repr(Int)].

};
Some(integer)
} else {
None
};

// Prepend the type of the discriminant to the types of the fields.
let mut field_types = enum_discriminant
.into_iter()
.chain(get_field_types(&fields).map(ToTokens::to_token_stream));
let size_sum = if let Some(first) = field_types.next() {
let size_first = quote!(::core::mem::size_of::<#first>());
let size_rest = quote!(#( + ::core::mem::size_of::<#field_types>() )*);
Expand Down
21 changes: 21 additions & 0 deletions derive/tests/basic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,27 @@ struct CheckedBitPatternStruct {
b: CheckedBitPatternEnumNonContiguous,
}

#[derive(Debug, Copy, Clone, NoUninit)]
#[repr(C)]
enum NoUninitEnumWithFields {
A(u32, u32),
B(u16, u16, u16, u16),
}

#[derive(Debug, Copy, Clone, NoUninit)]
#[repr(C, u16)]
enum NoUninitEnumWithFieldsAndCAndDiscriminant {
A(u16, u16),
B(u8, u8, u8, u8),
}

#[derive(Debug, Clone, Copy, NoUninit)]
#[repr(u16)]
enum NoUninitEnumWithFieldsAndDiscriminant {
A(u16, u16),
B(u8, u8, u8, u8),
}

#[derive(Debug, Copy, Clone, AnyBitPattern, PartialEq, Eq)]
#[repr(C)]
struct AnyBitPatternTest<A: AnyBitPattern, B: AnyBitPattern> {
Expand Down
Loading