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

Alignment Trait #3

Open
rylev opened this issue Mar 12, 2020 · 2 comments
Open

Alignment Trait #3

rylev opened this issue Mar 12, 2020 · 2 comments
Labels
new trait Proposal for a new trait to be added

Comments

@rylev
Copy link
Collaborator

rylev commented Mar 12, 2020

Having some sort of trait for talking about a type's alignment at the type level will be useful not only for safe transmute but for other things as well. This information is often known at compile time and available through const functions.

One question is whether we need a general AlignmentOf<T> trait or if it is useful enough to have an AlignmentOfOne (a.k.a. Unaligned) for types where there are no alignment concerns and any reference to T: AlignmentOfOne is valid.

This is one possible area where const generics can help:

trait Alignment {
    type Amount = const usize;
}

impl Alignment for u8 {
    type Amount = 1;
}

PriorArt

  • zerocopy provides Unaligned for declaring that a type has no alignment concerns. It does not try to generalize to a generic alignment trait.
  • typic provides AlignOf<T> which is an alias to <T as Layout>::Align where the Align associated type of Layout is an typenum::marker_traits::Unsigned.
  • bytemuck does not have an equivalent to this.
@rylev rylev added the new trait Proposal for a new trait to be added label Mar 12, 2020
@Lokathor
Copy link

My main thought is that you often need to care about alignment but only if it goes up.

In other words, while Align1 is good, what you're really testing for is

align_of::<T>() <= X

And if the align is 1 then it always will pass for any X, which is why align 1 seems so special.

However, if we're casting u32 to [i16;2] then the alignment requirement goes down in that case as well without alignment actually being 1.

I'm not saying we don't want to have an alignment trait, but because of how it's used in practice it's a lot more complicated than the usual marker traits which are a lot more "boolean" in nature (eg: "no uninit bytes")

@casey
Copy link

casey commented May 25, 2020

I think align_of::<T>() == 1 is probably useful enough that it deserves its own marker trait, like Unaligned. I'm writing a zero-copy serialization and deserialization library, and I'm ignoring padding and alignment all together, so I'll probably wind up writing my own Unaligned or using zerocopy's.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
new trait Proposal for a new trait to be added
Projects
None yet
Development

No branches or pull requests

3 participants