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

Compile time asserts #2

Closed
ollpu opened this issue Mar 28, 2023 · 2 comments
Closed

Compile time asserts #2

ollpu opened this issue Mar 28, 2023 · 2 comments

Comments

@ollpu
Copy link

ollpu commented Mar 28, 2023

When const_panic first stabilized, it didn't seem to be applicable for checking properties of generics, since const items inside functions can't be tied to the generics. However, an associated const on a struct seems to do the trick:

use std::mem::{align_of, size_of};

struct AssertSameLayout<A, B>(std::marker::PhantomData<(A, B)>);
impl<A, B> AssertSameLayout<A, B> {
    const OK: () = assert!(
        size_of::<A>() == size_of::<B>() && align_of::<A>() == align_of::<B>(),
        "types must have identical size and alignment"
    );
}

// used as
() = AssertSameLayout::<A, B>::OK;

Playground

Idea stolen from here.

@golddranks
Copy link
Owner

Oh, interesting!! Thanks for the pointer.

@golddranks
Copy link
Owner

Thank you! I implemented static asserts. This also means that might be possible to get forward with getting this to stdlib.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants