Skip to content

Commit 8c7cdd3

Browse files
udoprogRalfJung
andcommitted
Document semantics of various pointer casts
Co-authored-by: Ralf Jung <[email protected]>
1 parent 9104f17 commit 8c7cdd3

File tree

1 file changed

+17
-9
lines changed

1 file changed

+17
-9
lines changed

src/expressions/operator-expr.md

+17-9
Original file line numberDiff line numberDiff line change
@@ -478,15 +478,23 @@ unsafe {
478478
assert_eq!(values[1], 3);
479479
```
480480

481-
#### Slice DST pointer to pointer cast
482-
483-
For slice types like `[T]` and `[U]`, the raw pointer types `*const [T]`, `*mut [T]`,
484-
`*const [U]`, and `*mut [U]` encode the number of elements in this slice. Casts between
485-
these raw pointer types preserve the number of elements. Note that, as a consequence,
486-
such casts do *not* necessarily preserve the size of the pointer's referent (e.g.,
487-
casting `*const [u16]` to `*const [u8]` will result in a raw pointer which refers to an
488-
object of half the size of the original). The same holds for `str` and any compound type
489-
whose unsized tail is a slice type, such as struct `Foo(i32, [u8])` or `(u64, Foo)`.
481+
#### Pointer-to-pointer cast
482+
483+
`*const T` / `*mut T` can be cast to `*const U` / `*mut U` with the following behavior:
484+
485+
- If `T` and `U` are both sized, the pointer is returned unchanged.
486+
- If `T` and `U` are both unsized, the pointer is also returned unchanged. In particular,
487+
the metadata is preserved exactly.
488+
489+
For instance, a cast from `*const [T]` to `*const [U]` preserves the number of elements.
490+
Note that, as a consequence, such casts do not necessarily preserve the size of the
491+
pointer's referent (e.g., casting `*const [u16]` to `*const [u8]` will result in a raw
492+
pointer which refers to an object of half the size of the original). The same
493+
holds for `str` and any compound type whose unsized tail is a slice type, such
494+
as `struct Foo(i32, [u8])` or `(u64, Foo)`.
495+
- If `T` is unsized and `U` is sized, the cast discards all metadata that
496+
completes the wide pointer `T` and produces a thin pointer `U` consisting
497+
of the data part of the unsized pointer.
490498

491499
## Assignment expressions
492500

0 commit comments

Comments
 (0)