pub unsafe trait Validity: Sealed { }Expand description
The validity invariant of a [Ptr][super::Ptr].
§Safety
In this section, we will use Ptr<T, V> as a shorthand for Ptr<T, I: Invariants<Validity = V>> for brevity.
Each V: Validity defines a set of bit values which may appear in the
referent of a Ptr<T, V>, denoted S(T, V). Each V: Validity, in its
documentation, provides a definition of S(T, V) which must be valid for
all T: ?Sized. Any V: Validity must guarantee that this set is only a
function of the bit validity of the referent type, T, and not of any
other property of T. As a consequence, given V: Validity, T, and U
where T and U have the same bit validity, S(V, T) = S(V, U).
It is guaranteed that the referent of any ptr: Ptr<T, V> is a member of
S(T, V). Unsafe code must ensure that this guarantee will be upheld for
any existing Ptrs or any Ptrs that that code creates.
An important implication of this guarantee is that it restricts what
transmutes are sound, where “transmute” is used in this context to refer to
changing the referent type or validity invariant of a Ptr, as either
change may change the set of bit values permitted to appear in the referent.
In particular, the following are necessary (but not sufficient) conditions
in order for a transmute from src: Ptr<T, V> to dst: Ptr<U, W> to be
sound:
- If
S(T, V) = S(U, W), then no restrictions apply; otherwise, - If
dstpermits mutation of its referent (e.g. viaExclusivealiasing or interior mutation underSharedaliasing), then it must hold thatS(T, V) ⊇ S(U, W)- in other words, the transmute must not expand the set of allowed referent bit patterns. A violation of this requirement would permit usingdstto writexwherex ∈ S(U, W)butx ∉ S(T, V), which would violate the guarantee thatsrc’s referent may only contain values inS(T, V). - If the referent may be mutated without going through
dstwhiledstis live (e.g. via interior mutation on aShared-aliasedPtror&reference), then it must hold thatS(T, V) ⊆ S(U, W)- in other words, the transmute must not shrink the set of allowed referent bit patterns. A violation of this requirement would permit usingsrcor another mechanism (e.g. a&reference used to derivesrc) to writexwherex ∈ S(T, V)butx ∉ S(U, W), which would violate the guarantee thatdst’s referent may only contain values inS(U, W).