From 2d74528c21d352969eb044a87d3686a92c9c02bd Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Thu, 31 Mar 2022 21:11:29 -0400 Subject: [PATCH 1/2] caution against ptr-to-int transmutes --- library/core/src/intrinsics.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/library/core/src/intrinsics.rs b/library/core/src/intrinsics.rs index 8ad4317c145ac..4962299de6f3f 100644 --- a/library/core/src/intrinsics.rs +++ b/library/core/src/intrinsics.rs @@ -991,6 +991,12 @@ extern "rust-intrinsic" { /// let ptr_num_cast = ptr as *const i32 as usize; /// ``` /// + /// Note that using `transmute` to turn a pointer to a `usize` is (as noted above) [undefined + /// behavior][ub] in `const` contexts. Also outside of consts, this operation might not behave + /// as expected -- this is touching on many unspecified aspects of the Rust memory model. To + /// make sure your code is well-defined, the conversion of pointers to integers and back should + /// always be done explicitly via casts. + /// /// Turning a `*mut T` into an `&mut T`: /// /// ``` From dd85a7682cf17103ec72eb1606fabf04bbf52971 Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Sat, 2 Apr 2022 10:25:06 -0400 Subject: [PATCH 2/2] refine wording and describe alternatives --- library/core/src/intrinsics.rs | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/library/core/src/intrinsics.rs b/library/core/src/intrinsics.rs index 4962299de6f3f..4a98b480c9d16 100644 --- a/library/core/src/intrinsics.rs +++ b/library/core/src/intrinsics.rs @@ -993,9 +993,13 @@ extern "rust-intrinsic" { /// /// Note that using `transmute` to turn a pointer to a `usize` is (as noted above) [undefined /// behavior][ub] in `const` contexts. Also outside of consts, this operation might not behave - /// as expected -- this is touching on many unspecified aspects of the Rust memory model. To - /// make sure your code is well-defined, the conversion of pointers to integers and back should - /// always be done explicitly via casts. + /// as expected -- this is touching on many unspecified aspects of the Rust memory model. + /// Depending on what the code is doing, the following alternatives are preferrable to + /// pointer-to-integer transmutation: + /// - If the code just wants to store data of arbitrary type in some buffer and needs to pick a + /// type for that buffer, it can use [`MaybeUninit`][mem::MaybeUninit]. + /// - If the code actually wants to work on the address the pointer points to, it can use `as` + /// casts or [`ptr.addr()`][pointer::addr]. /// /// Turning a `*mut T` into an `&mut T`: ///