You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Our rules for `as` casts document which pointer-to-pointer casts are
valid. For unsized types, this validity is based on the compatibility
of the pointer metadata. Using this and our layout equivalences, we
can define when a pointer transmute will produce the same pointer
value as would a cast. Let's define that.
Copy file name to clipboardExpand all lines: src/types/pointer.md
+22Lines changed: 22 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -63,6 +63,23 @@ r[type.pointer.smart]
63
63
64
64
The standard library contains additional 'smart pointer' types beyond references and raw pointers.
65
65
66
+
r[type.pointer.transmute]
67
+
## Transmutation
68
+
69
+
r[type.pointer.transmute.cast]
70
+
When `*const T` and `*const U` have the same layout (per [layout.pointer.parametric]), transmuting a `*const T` to a `*const U` reinterprets the pointer value --- its address and [metadata] --- unchanged. When `T` and `U` are both sized or both have a slice or `str` as their [unsized tail], this produces the same value as a [pointer-to-pointer cast] from `*const T` to `*const U` (where such a cast is permitted), since the cast copies the metadata unchanged. The same holds between `*mut T` and `*mut U`. Transmuting between the reference types `&T` and `&U`, or between `&mut T` and `&mut U`, reinterprets the pointer value the same way, but is sound only when the result is aligned for the target type and points to a valid value of it, as required by [undefined.validity.reference-box] and [undefined.validity.wide].
71
+
72
+
```rust
73
+
letptr:*consti8=&1;
74
+
letcast=ptras*constu8;
75
+
// Transmuting this pointer is equivalent to casting it with `as`.
> This equivalence with the cast does not extend to trait objects. The conversions permitted for `as` casts between trait-object pointers --- adding or removing an auto trait, and a [trait object upcast] (converting `*const dyn Sub` to `*const dyn Super` when `Super` is a supertrait of `Sub`) --- are [unsized coercions][unsized coercion], not pointer-to-pointer casts. The conversion builds a vtable for the target type, whereas a transmute keeps the source vtable. For an auto-trait change the kept vtable is still valid, so the transmute is sound but does not necessarily produce the same pointer value as the cast. For an upcast, the kept vtable is `Sub`'s, which is not valid for `Super`, so the transmuted pointer is invalid.
82
+
66
83
r[type.pointer.validity]
67
84
## Bit validity
68
85
@@ -75,5 +92,10 @@ For thin raw pointers (i.e., for `P = *const T` or `P = *mut T` for `T: Sized`),
0 commit comments