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

Safe transmute between #[repr(transparent)] and the type it contains #11

Open
sffc opened this issue Sep 22, 2021 · 0 comments
Open

Safe transmute between #[repr(transparent)] and the type it contains #11

sffc opened this issue Sep 22, 2021 · 0 comments

Comments

@sffc
Copy link

sffc commented Sep 22, 2021

I'd like to write the following code:

/// A newtype wrapper around u32 that guarantees the number is even
#[repr(transparent)]
pub struct EvenU32(u32);

impl EvenU32 {
  pub fn try_from_u32_ref(value: &u32) -> Result<&Self, ()> {
    if *value % 2 == 0 {
      Ok(safe_transmute(value))
    } else {
      Err(())
    }
  }
}

To enforce the invariant of the wrapper type, safe_transmute should look at the visibility of the field. For example, the following code in a different module would not work:

// Should not compile, because the `u32` field is inaccessible from the outside
let _: EvenU32 = safe_transmute(&100);

CC @Manishearth

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

1 participant