Skip to content

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

@sffc

Description

@sffc

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions