Skip to content

Commit

Permalink
Improve transmute docs
Browse files Browse the repository at this point in the history
  • Loading branch information
saethlin committed Mar 10, 2024
1 parent 6865bd3 commit e8e53b8
Showing 1 changed file with 29 additions and 0 deletions.
29 changes: 29 additions & 0 deletions library/core/src/intrinsics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1223,6 +1223,35 @@ extern "rust-intrinsic" {
/// }
/// ```
///
/// However, since pointers (and references) have provenance and integers do not, the following
/// program executes UB:
/// ```no_run
/// let ptr: *const u8 = &0;
/// let address = unsafe {
/// std::mem::transmute::<*const u8, usize>(ptr)
/// };
/// let new_ptr = unsafe {
/// std::mem::transmute::<usize, *const u8>(address)
/// };
/// unsafe {
/// assert_eq!(*ptr, 0);
/// }
/// ```
/// And this program does as well:
/// ```no_run
/// let ptr: *const u8 = &0;
/// let address = unsafe {
/// std::mem::transmute::<*const u8, usize>(ptr)
/// };
/// let new_ref = unsafe {
/// std::mem::transmute::<usize, &u8>(address)
/// };
/// ```
/// Distinguishing exactly which operation in this program is invalid touches on unspecified
/// aspects of the Rust memory model. If you need to store a pointer as another type then
/// recover the original pointer later, you cannot use `transmute` to round-trip through a
/// type which is not a pointer, reference, or [`MaybeUninit`][crate::mem::MaybeUninit].
///
/// # Alternatives
///
/// Don't despair: many uses of `transmute` can be achieved through other means.
Expand Down

0 comments on commit e8e53b8

Please sign in to comment.