diff --git a/zerocopy-derive/src/lib.rs b/zerocopy-derive/src/lib.rs index 3370780c6f..4f1e375aca 100644 --- a/zerocopy-derive/src/lib.rs +++ b/zerocopy-derive/src/lib.rs @@ -950,15 +950,26 @@ fn derive_into_bytes_enum(ast: &DeriveInput, enm: &DataEnum) -> Result Result { // See #1792 for more context. - let cfg_compile_error = quote!( - const _: () = { - #[cfg(not(zerocopy_derive_union_into_bytes))] - ::zerocopy::util::macro_util::core_reexport::compile_error!( - "requires --cfg zerocopy_derive_union_into_bytes; + // + // By checking for `zerocopy_derive_union_into_bytes` both here and in the + // generated code, we ensure that `--cfg zerocopy_derive_union_into_bytes` + // need only be passed *either* when compiling this crate *or* when + // compiling the user's crate. The former is preferable, but in some + // situations (such as when cross-compiling using `cargo build --target`), + // it doesn't get propagated to this crate's build by default. + let cfg_compile_error = if cfg!(zerocopy_derive_union_into_bytes) { + quote!() + } else { + quote!( + const _: () = { + #[cfg(not(zerocopy_derive_union_into_bytes))] + ::zerocopy::util::macro_util::core_reexport::compile_error!( + "requires --cfg zerocopy_derive_union_into_bytes; please let us know you use this feature: https://github.com/google/zerocopy/discussions/1802" - ); - }; - ); + ); + }; + ) + }; // TODO(#10): Support type parameters. if !ast.generics.params.is_empty() { diff --git a/zerocopy-derive/src/output_tests.rs b/zerocopy-derive/src/output_tests.rs index d019502ad4..caad309312 100644 --- a/zerocopy-derive/src/output_tests.rs +++ b/zerocopy-derive/src/output_tests.rs @@ -332,40 +332,6 @@ fn test_into_bytes() { } } -#[test] -fn test_union_into_bytes() { - // Rustfmt spuriously adds spaces after the newline in the middle of the - // string literal. - #[rustfmt::skip] - test! { - IntoBytes { - #[repr(C)] - union Foo { - a: u8, - } - } expands to { - const _: () = { - #[cfg(not(zerocopy_derive_union_into_bytes))] - ::zerocopy::util::macro_util::core_reexport::compile_error!( - "requires --cfg zerocopy_derive_union_into_bytes; -please let us know you use this feature: https://github.com/google/zerocopy/discussions/1802" - ); - }; - #[allow(deprecated)] - unsafe impl ::zerocopy::IntoBytes for Foo - where - u8: ::zerocopy::IntoBytes, - (): ::zerocopy::util::macro_util::PaddingFree< - Foo, - { ::zerocopy::union_has_padding!(Foo, [u8]) }, - >, - { - fn only_derive_is_allowed_to_implement_this_trait() {} - } - } no_build - } -} - #[test] fn test_unaligned() { test! {