Description
This trait indicates a type has no internal validity requirements. Even when two types are layout compatible it is not generically safe to cast between them. Types may define additional invariants of its attributes and even unsafely depend on them, such as requiring all its constructors to perform some form of global initialization.
This is in many regards a structural marker trait. A type could safely implement/derive the trait iff all of its attributes implement the trait as well, similar to the Copy
trait. This is because an incorrect impl
could only be written by the same crate that tries to rely on its invariants, a pure logic bug in that crate, and no other safe code is affected. Adding this trait in core
would thus present a unique solution that is currently not possible to implement in a pure user-crate.
Prior art
The typic
crate has a Transparent
trait, that needs to be manually and unsafely implemented for types with private fields. It is the exact additional requirement that differentiates its transmute_safe
casts from transmute_sound
casts. However, this implementation currently has a bug as the automatic trait derive does not assert the structural condition, that all fields implement the trait as well.
In the zerocopy
and bytemuck
crates this trait is implicitely part of the FromBytes
and Pod
trait respectively.
Future directions
Similar to the Copy
trait there could be an unsafe impl Transparent
in the future, that would allow a type to implement the trait despite some attribute or structurally contained type not doing so. This served a very similar purpose than discussed in rust #25053 for UnsafellCell
, MaybeUninit
, etc. and other types where it is not possible in safe code to access the attribute of the contained type.
Another possible use would be dynamic version where the valid instance is inspected to determine if its safety invariants are met. How that interface would look could be discussed or prototyped in one of the bytecast crates, the advantages of core
implementation do not apply.