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

[unsafe-fields] adding enum rule into unsafe-fields macro #2034

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
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
72 changes: 71 additions & 1 deletion unsafe-fields/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -329,6 +329,44 @@ macro_rules! unsafe_fields {
)*
}
};

(
$( #[$attr:meta] )*
$vis:vis enum $name:ident {
$(
$(#[$variant_attrs:meta])*
$variant:ident $({
$(
$(#[$field_attr:ident])?
$field:ident: $field_ty:ty
),+ $(,)?
})?
$((
$(
$field_ty2:ty
),+ $(,)?
))?
),+ $(,)?
}
) => {
$(#[$attr])*
$vis enum $name {
$(
$(#[$variant_attrs])*
$variant $({
$(
$field: unsafe_fields!(@field $(#[$field_attr])? $field: $field_ty),
)*
})?
$((
$(
$field_ty2,
)+
))?
),+
}
};

(@field #[unsafe] $field:ident: $field_ty:ty) => {
$crate::Unsafe<Self, $field_ty, {$crate::macro_util::hash_field_name(stringify!($field))}>
};
Expand Down Expand Up @@ -391,10 +429,42 @@ mod tests {

#[test]
#[allow(clippy::undocumented_unsafe_blocks)]
fn test_unsafe_fieds() {
fn test_unsafe_fields() {
let mut _foo = Foo { a: unsafe { Unsafe::new(0) }, b: 0 };
let mut _bar = Bar { a: unsafe { Unsafe::new(0) }, b: unsafe { Unsafe::new(0) } };
}

unsafe_fields! {
#[allow(unused)]
enum FooEnum {
UnitA,
UnitB,
StructVariantA {
a: i32,
#[unsafe]
b: String,
},
StructVariantB {
#[unsafe]
a: usize,
#[unsafe]
b: String,
},
TupleVariant(i32, String, usize),
}
}
#[test]
#[allow(clippy::undocumented_unsafe_blocks)]
fn test_unsafe_fields_enum() {
let mut _foofoo_a =
FooEnum::StructVariantA { a: 0, b: unsafe { Unsafe::new(String::from("foo")) } };
let mut _foofoo_b = FooEnum::StructVariantB {
a: unsafe { Unsafe::new(0) },
b: unsafe { Unsafe::new(String::from("foo")) },
};
let mut _foo_c = FooEnum::UnitA;
let mut _foo_d = FooEnum::TupleVariant(1, String::from("foo"), 0);
}
}

/// This module exists so that we can use rustdoc to perform compile-fail tests
Expand Down
Loading