Skip to content

Commit e597d06

Browse files
authored
Rollup merge of #95547 - RalfJung:ptr-int-transmutes, r=scottmcm
caution against ptr-to-int transmutes I don't know how strong of a statement we want to make here, but I am very concerned that the current docs could be interpreted as saying that ptr-to-int transmutes are just as okay as transmuting `*mut T` into an `&mut T`. Examples [like this](rust-lang/unsafe-code-guidelines#286 (comment)) show that ptr-to-int transmutes are deeply suspicious -- they are either UB, or they don't round-trip properly, or we have to basically say that `transmute` will actively look for pointers and do all the things a ptr-to-int cast does (which includes a global side-effect of marking the pointed-to allocation as 'exposed'). Another alternative might be to simply not talk about them... but we *do* want people to use casts rather than transmutes for this. Cc `@rust-lang/lang`
2 parents c5e7e95 + dd85a76 commit e597d06

File tree

1 file changed

+10
-0
lines changed

1 file changed

+10
-0
lines changed

library/core/src/intrinsics.rs

+10
Original file line numberDiff line numberDiff line change
@@ -991,6 +991,16 @@ extern "rust-intrinsic" {
991991
/// let ptr_num_cast = ptr as *const i32 as usize;
992992
/// ```
993993
///
994+
/// Note that using `transmute` to turn a pointer to a `usize` is (as noted above) [undefined
995+
/// behavior][ub] in `const` contexts. Also outside of consts, this operation might not behave
996+
/// as expected -- this is touching on many unspecified aspects of the Rust memory model.
997+
/// Depending on what the code is doing, the following alternatives are preferrable to
998+
/// pointer-to-integer transmutation:
999+
/// - If the code just wants to store data of arbitrary type in some buffer and needs to pick a
1000+
/// type for that buffer, it can use [`MaybeUninit`][mem::MaybeUninit].
1001+
/// - If the code actually wants to work on the address the pointer points to, it can use `as`
1002+
/// casts or [`ptr.addr()`][pointer::addr].
1003+
///
9941004
/// Turning a `*mut T` into an `&mut T`:
9951005
///
9961006
/// ```

0 commit comments

Comments
 (0)