Skip to content

Commit 5927b49

Browse files
committed
allow Zeroable derive macro to also be applied to unions
Enabling the same behavior for unions as for structs is correct, but could be relaxed: the valid bit patterns for unions are the union of all valid bit patterns of their fields. So for a union to implement `Zeroable`, only a single field needs to implement `Zeroable`. This can be a future improvement, as it is currently only needed for unions where all fields implement `Zeroable`. There is no danger for mis-parsing with the two optional tokens (ie neither one or both tokens are parsed), as the compiler will already have rejected that before giving it as the input to the derive macro. Signed-off-by: Benno Lossin <[email protected]>
1 parent e8311e5 commit 5927b49

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

CHANGELOG.md

+1
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
1515

1616
- `InPlaceInit` now only exists when the `alloc` or `std` features are enabled
1717
- added support for visibility in `Zeroable` derive macro
18+
- added support for `union`s in `Zeroable` derive macro
1819

1920
## [0.0.9] - 2024-12-02
2021

src/macros.rs

+30
Original file line numberDiff line numberDiff line change
@@ -1412,4 +1412,34 @@ macro_rules! __derive_zeroable {
14121412
}
14131413
};
14141414
};
1415+
(parse_input:
1416+
@sig(
1417+
$(#[$($struct_attr:tt)*])*
1418+
$vis:vis union $name:ident
1419+
$(where $($whr:tt)*)?
1420+
),
1421+
@impl_generics($($impl_generics:tt)*),
1422+
@ty_generics($($ty_generics:tt)*),
1423+
@body({
1424+
$(
1425+
$(#[$($field_attr:tt)*])*
1426+
$field_vis:vis $field:ident : $field_ty:ty
1427+
),* $(,)?
1428+
}),
1429+
) => {
1430+
// SAFETY: Every field type implements `Zeroable` and padding bytes may be zero.
1431+
#[automatically_derived]
1432+
unsafe impl<$($impl_generics)*> $crate::Zeroable for $name<$($ty_generics)*>
1433+
where
1434+
$($($whr)*)?
1435+
{}
1436+
const _: () = {
1437+
fn assert_zeroable<T: ?::core::marker::Sized + $crate::Zeroable>() {}
1438+
fn ensure_zeroable<$($impl_generics)*>()
1439+
where $($($whr)*)?
1440+
{
1441+
$(assert_zeroable::<$field_ty>();)*
1442+
}
1443+
};
1444+
};
14151445
}

0 commit comments

Comments
 (0)