From/Into traits and mem::transmute

I need to convert a Vec3 type to another Vec3 from a different library.
They have the exact same memory layout, and I have written this:

impl From<cgmath::Point3<FLOAT>> for Vec3 {
    fn from(val: cgmath::Point3<FLOAT>) -> Self {
        use std::mem;
        unsafe { mem::transmute::<cgmath::Point3<FLOAT>, Vec3>(val) }
    }
}

I'd like a zero cost conversion, is this the right approach?

No, this code is unsound.

Unless both types are #[repr(C)], Rust DOES NOT guarantee the two different types with same type of fields in same order on definition to have same memory layout.

This should compile down to the most efficient version anyway, so if Rust happens to not decide to reorder the fields, it should be equivalent to the transmute.

impl From<cgmath::Point3<FLOAT>> for Vec3 {
    fn from(val: cgmath::Point3<FLOAT>) -> Self {
        Vec3 { x: val.x, y: val.y, z: val.z }
    }
}
2 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.