Skip to content

Implement traits for tuples #274

Open

Description

Although we do not do so currently, it's valid to implement FromZeroes and FromBytes for tuples of any size, so long as all of the elements of those tuples also implement those traits. Use this as a model for how to provide generic implementations of these traits:

zerocopy/src/lib.rs

Lines 1094 to 1108 in 0ff2dd1

safety_comment! {
/// SAFETY:
/// `Wrapping<T>` is guaranteed by its docs [1] to have the same layout as
/// `T`. Also, `Wrapping<T>` is `#[repr(transparent)]`, and has a single
/// field, which is `pub`. Per the reference [2], this means that the
/// `#[repr(transparent)]` attribute is "considered part of the public ABI".
///
/// [1] https://doc.rust-lang.org/nightly/core/num/struct.Wrapping.html#layout-1
/// [2] https://doc.rust-lang.org/nomicon/other-reprs.html#reprtransparent
unsafe_impl!(T: FromZeroes => FromZeroes for Wrapping<T>);
unsafe_impl!(T: FromBytes => FromBytes for Wrapping<T>);
unsafe_impl!(T: AsBytes => AsBytes for Wrapping<T>);
unsafe_impl!(T: Unaligned => Unaligned for Wrapping<T>);
assert_unaligned!(Wrapping<()>, Wrapping<u8>);
}

Note: We cannot implement Unaligned nor AsBytes for any tuple type other than () — all other tuple types have the default representation, and so a) there is no upper bound on their alignment and, b) there are no guarantees made about the absence of padding.

Additionally, add tests for the presence/absence of these impls for various concrete tuple types (where the tuple element types are both sufficient and insufficient for generating the impl for the entire tuple). The assert_impls! macro may be helpful for this:

assert_impls!((): FromZeroes, FromBytes, AsBytes, Unaligned);

Following the lead of the standard library, we should implement these traits for tuples up to size 12.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Labels

    compatibility-nonbreakingChanges that are (likely to be) non-breakingexperience-mediumThis issue is of medium difficulty, and requires some experiencehelp wantedExtra attention is needed

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions