Casting refs safely?

Suppose we have:

struct A { .. }
struct B(A);

Is there anyway to safely do &A -> &B or &mut A -> &mut B ?

Context: goofing around with "faking" headers in Rust, separating "data struct" from "impl of struct funcs"

bytemuck's TransparentWrapper provides a wrap_ref/mut that does this: TransparentWrapper in bytemuck - Rust

So you could write a safe function that has a TransparentWrapper bound. Of course the trait itself is unsafe, because it requires among others repr(transparent) and there's no way to require that through the type system, but there's a derive macro that ensures all of the unsafe is okay.

1 Like

You need to declare struct B with #[repr(C)] or #[repr(transparent)], otherwise your conversion is unsound, since Rust could put padding around the inner field.

1 Like

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.