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

[derive] Implement an IntoBytes-based PartialEq/Eq derive #2285

Merged
merged 2 commits into from
Feb 3, 2025
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
11 changes: 11 additions & 0 deletions src/lib.rs
Copy link
Collaborator

Choose a reason for hiding this comment

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

I'm surprised that rustfmt didn't catch this — something to dig into, I think.

Original file line number Diff line number Diff line change
Expand Up @@ -5456,6 +5456,17 @@ pub unsafe trait Unaligned {
#[cfg_attr(doc_cfg, doc(cfg(feature = "derive")))]
pub use zerocopy_derive::ByteHash;

/// Derives an optimized implementation of [`PartialEq`] and [`Eq`] for types
/// that implement [`IntoBytes`] and [`Immutable`].
///
/// The standard library's derive for [`PartialEq`] generates a recursive
/// descent into the fields of the type it is applied to. Instead, the
/// implementation derived by this macro performs a single slice comparison of
/// the bytes of the two values being compared.
#[cfg(any(feature = "derive", test))]
#[cfg_attr(doc_cfg, doc(cfg(feature = "derive")))]
pub use zerocopy_derive::ByteEq;

#[cfg(feature = "alloc")]
#[cfg_attr(doc_cfg, doc(cfg(feature = "alloc")))]
#[cfg(zerocopy_panic_in_const_and_vec_try_reserve_1_57_0)]
Expand Down
47 changes: 47 additions & 0 deletions zerocopy-derive/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@ derive!(FromBytes => derive_from_bytes => derive_from_bytes_inner);
derive!(IntoBytes => derive_into_bytes => derive_into_bytes_inner);
derive!(Unaligned => derive_unaligned => derive_unaligned_inner);
derive!(ByteHash => derive_hash => derive_hash_inner);
derive!(ByteEq => derive_eq => derive_eq_inner);

/// Deprecated: prefer [`FromZeros`] instead.
#[deprecated(since = "0.8.0", note = "`FromZeroes` was renamed to `FromZeros`")]
Expand Down Expand Up @@ -577,6 +578,50 @@ fn derive_hash_inner(ast: &DeriveInput, _top_level: Trait) -> Result<TokenStream
})
}

fn derive_eq_inner(ast: &DeriveInput, _top_level: Trait) -> Result<TokenStream, Error> {
// This doesn't delegate to `impl_block` because `impl_block` assumes it is deriving a
// `zerocopy`-defined trait, and these trait impls share a common shape that `Eq` does not.
// In particular, `zerocopy` traits contain a method that only `zerocopy_derive` macros
// are supposed to implement, and `impl_block` generating this trait method is incompatible
// with `Eq`.
let type_ident = &ast.ident;
let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl();
let where_predicates = where_clause.map(|clause| &clause.predicates);
Ok(quote! {
// TODO(#553): Add a test that generates a warning when
// `#[allow(deprecated)]` isn't present.
#[allow(deprecated)]
// While there are not currently any warnings that this suppresses (that
// we're aware of), it's good future-proofing hygiene.
#[automatically_derived]
impl #impl_generics ::zerocopy::util::macro_util::core_reexport::cmp::PartialEq for #type_ident #ty_generics
where
Self: ::zerocopy::IntoBytes + ::zerocopy::Immutable,
#where_predicates
{
fn eq(&self, other: &Self) -> bool {
::zerocopy::util::macro_util::core_reexport::cmp::PartialEq::eq(
::zerocopy::IntoBytes::as_bytes(self),
::zerocopy::IntoBytes::as_bytes(other),
)
}
}

// TODO(#553): Add a test that generates a warning when
// `#[allow(deprecated)]` isn't present.
#[allow(deprecated)]
// While there are not currently any warnings that this suppresses (that
// we're aware of), it's good future-proofing hygiene.
#[automatically_derived]
impl #impl_generics ::zerocopy::util::macro_util::core_reexport::cmp::Eq for #type_ident #ty_generics
where
Self: ::zerocopy::IntoBytes + ::zerocopy::Immutable,
#where_predicates
{
}
})
}

/// A struct is `TryFromBytes` if:
/// - all fields are `TryFromBytes`
fn derive_try_from_bytes_struct(
Expand Down Expand Up @@ -1344,6 +1389,7 @@ enum Trait {
Unaligned,
Sized,
ByteHash,
ByteEq,
}

impl ToTokens for Trait {
Expand All @@ -1367,6 +1413,7 @@ impl ToTokens for Trait {
Trait::Unaligned => "Unaligned",
Trait::Sized => "Sized",
Trait::ByteHash => "ByteHash",
Trait::ByteEq => "ByteEq",
};
let ident = Ident::new(s, Span::call_site());
tokens.extend(core::iter::once(TokenTree::Ident(ident)));
Expand Down
34 changes: 34 additions & 0 deletions zerocopy-derive/src/output_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ use_as_trait_name!(
IntoBytes => derive_into_bytes_inner,
Unaligned => derive_unaligned_inner,
ByteHash => derive_hash_inner,
ByteEq => derive_eq_inner,
);

/// Test that the given derive input expands to the expected output.
Expand Down Expand Up @@ -2020,3 +2021,36 @@ fn test_hash() {
} no_build
}
}

#[test]
fn test_eq() {
test! {
ByteEq {
struct Foo<T: Clone>(T) where Self: Sized;
} expands to {
#[allow(deprecated)]
#[automatically_derived]
impl<T: Clone> ::zerocopy::util::macro_util::core_reexport::cmp::PartialEq for Foo<T>
where
Self: ::zerocopy::IntoBytes + ::zerocopy::Immutable,
Self: Sized,
{
fn eq(&self, other: &Self) -> bool {
::zerocopy::util::macro_util::core_reexport::cmp::PartialEq::eq(
::zerocopy::IntoBytes::as_bytes(self),
::zerocopy::IntoBytes::as_bytes(other),
)
}
}

#[allow(deprecated)]
#[automatically_derived]
impl<T: Clone> ::zerocopy::util::macro_util::core_reexport::cmp::Eq for Foo<T>
where
Self: ::zerocopy::IntoBytes + ::zerocopy::Immutable,
Self: Sized,
{
}
} no_build
}
}
33 changes: 33 additions & 0 deletions zerocopy-derive/tests/eq.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
// Copyright 2024 The Fuchsia Authors
//
// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0
// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT
// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option.
// This file may not be copied, modified, or distributed except according to
// those terms.

// See comment in `include.rs` for why we disable the prelude.
#![no_implicit_prelude]
#![allow(warnings)]

include!("include.rs");

#[derive(imp::Debug, imp::IntoBytes, imp::Immutable, imp::ByteEq)]
#[repr(C)]
struct Struct {
a: u64,
b: u32,
c: u32,
}

util_assert_impl_all!(Struct: imp::IntoBytes, imp::PartialEq, imp::Eq);

#[test]
fn test_eq() {
use imp::{assert_eq, assert_ne};
let a = Struct { a: 10, b: 15, c: 20 };
let b = Struct { a: 10, b: 15, c: 25 };
assert_eq!(a, a);
assert_ne!(a, b);
assert_ne!(b, a);
}
2 changes: 1 addition & 1 deletion zerocopy-derive/tests/include.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ mod imp {
#[allow(unused)]
pub use {
::core::{
assert_eq,
assert_eq, assert_ne,
cell::UnsafeCell,
convert::TryFrom,
hash,
Expand Down
Loading