How to generate a reference of a wrapper type from the reference of inner type

There's a type like this

#[repr(transparent)]
struct Wrapper(Inner)

How can I implement this function (maybe unsafe needed?)

fn from_ref(inner: &Inner)->&Wrapper

I've found a way like this

impl From<&Inner> for &Wrapper {
    fn from(value: &Inner) -> Self {
        unsafe { &*(value as *const Inner as *const Wrapper) }
    }
}
2 Likes

Are there any potential security issues with this? I think the wrapper and inner is actually the same object since they have the same layout in memory with #[repr(transparent)].

Since Wrapper is marked #[repr(transparent)], your unsafe code is fine.

5 Likes

If you'd like to do this without writing any new unsafe code, you can use bytemuck::TransparentWrapper to derive it instead. (However, since it's trait-based, it makes the wrapper really transparent, in that any owner of an &Inner or &Wrapper can get the other one from it — you can no longer impose rules that only some Inners may become Wrappers.)

3 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.