Skip to content

Add traits for size and alignment comparisons #125

@joshlf

Description

@joshlf

This is a half-baked idea, and it requires the unstable associated_const_equality feature. Also, the AlignedTo impls don't currently work thanks to rust-lang/rust#103292.

trait Size {
    const SIZE: usize;
}

impl<T> Size for T {
    const SIZE: usize = core::mem::size_of::<T>();
}

trait Align {
    const ALIGN: usize;
}

impl<T> Align for T {
    const ALIGN: usize = core::mem::align_of::<T>();
}

trait Zst {}

impl<T: Size<SIZE = 0>> Zst for T {}

trait SameSizeAs<T> {}

impl<const SIZE: usize, T: Size<SIZE = { SIZE }>, U: Size<SIZE = { SIZE }>> SameSizeAs<U> for T {}

trait AlignedTo<T> {}

impl<T: Align<ALIGN = 1>, U: Align<ALIGN = 1>> AlignedTo<U> for T {}
impl<T: Align<ALIGN = 2>, U: Align<ALIGN = 2>> AlignedTo<U> for T {}
impl<T: Align<ALIGN = 2>, U: Align<ALIGN = 1>> AlignedTo<U> for T {}
impl<T: Align<ALIGN = 4>, U: Align<ALIGN = 4>> AlignedTo<U> for T {}
impl<T: Align<ALIGN = 4>, U: Align<ALIGN = 2>> AlignedTo<U> for T {}
impl<T: Align<ALIGN = 4>, U: Align<ALIGN = 1>> AlignedTo<U> for T {}

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions