Given the following type and trait:
#[repr(C)]
struct Foo<A, B: ?Sized> {
a: A,
b: B,
}
pub trait Trivial: Copy {
const INSTANCE: Self;
}
Is the following code safe?
impl<A: Trivial, B: ?Sized> Foo<A, B> {
pub fn from_ref(value: &B) -> &Foo<A, B> {
// check that layout of `A` is zero-sized and 1 aligned
assert_eq!(Layout::new::<A>(), Layout::new::<()>());
// check that there is a valid instance of `A`
// (in case invalid consts lints are ignored)
let _instance = I::INSTANCE;
// suspicious cast
unsafe { &*(value as *const B as *const Self) }
}
}
I think it should be, because
- a type with a public canonical instance and zero size can't have any validity/safety invariants
- The layouts of
B
andFoo<A, B>
are the same whenA
has the same layout as()
byrepr(C)
So it must be safe to just cast the reference.