From b21dc9844f07fbabca9ec3707ea96607ed35b06b Mon Sep 17 00:00:00 2001 From: Georg Semmler Date: Tue, 21 Apr 2026 16:19:12 +0200 Subject: [PATCH] Improve the documentation around layout gurantees given by `Box` This change extends the memory layout section in the documentation of `Box` to explicitly state that it is sound to convert between `Box` and `Box` as long as a cast between `*mut A` and `*mut B` is valid and the general requirements of `transmute` are satisfied. See https://rust-lang.zulipchat.com/#narrow/channel/136281-t-opsem/topic/Is.20transmuting.20between.20.60Box.3CA.3E.60.20and.20.60Box.3CB.3E.60.20UB.3F/with/585350243 for the relevant discussion. --- library/alloc/src/boxed.rs | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/library/alloc/src/boxed.rs b/library/alloc/src/boxed.rs index ef7422302d974..6e1ff350e1d8e 100644 --- a/library/alloc/src/boxed.rs +++ b/library/alloc/src/boxed.rs @@ -121,6 +121,24 @@ //! definition is just using `T*` can lead to undefined behavior, as //! described in [rust-lang/unsafe-code-guidelines#198][ucg#198]. //! +//! Converting between any `Box` and `Box` by using [`core::mem::transmute`] +//! is equivalent to the following sequence of operations: +//! +//! ```rust +//! # let boxed_value = Box::new(1_i32); +//! let ptr: *mut i32 = Box::into_raw(boxed_value); +//! let casted_ptr = ptr as *mut u32; +//! let new_box: Box = unsafe { +//! Box::from_raw(casted_ptr) +//! }; +//! ``` +//! +//! Any such conversion therefore needs to uphold the same guarantees as using +//! a [pointer-to-pointer cast][ptr-cast] to convert between a `*mut T` and a `*mut U`. +//! In addition such a `core::mem::transmute` call also needs to uphold the requirements +//! of [`core::mem::transmute`] for a transmute between `T` and `U`, especially +//! regarding to size, alignment and the validity of values for both types. +//! //! # Considerations for unsafe code //! //! **Warning: This section is not normative and is subject to change, possibly @@ -180,6 +198,7 @@ //! [`Layout`]: crate::alloc::Layout //! [`Layout::for_value(&*value)`]: crate::alloc::Layout::for_value //! [valid]: ptr#safety +//! [ptr-cast]: https://doc.rust-lang.org/reference/expressions/operator-expr.html#r-expr.as.pointer #![stable(feature = "rust1", since = "1.0.0")]