Skip to content

Commit a4fc9c4

Browse files
committed
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<A>` and `Box<B>` 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.
1 parent 3179a47 commit a4fc9c4

1 file changed

Lines changed: 20 additions & 0 deletions

File tree

library/alloc/src/boxed.rs

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,25 @@
121121
//! definition is just using `T*` can lead to undefined behavior, as
122122
//! described in [rust-lang/unsafe-code-guidelines#198][ucg#198].
123123
//!
124+
//! Converting between any `Box<T>` and `Box<U>` by using [`core::mem::transmute`]
125+
//! is equivalent to the following sequence of operations:
126+
//!
127+
//! ```rust
128+
//! # let boxed_value = Box::new(1_i32);
129+
//! let ptr: *mut i32 = Box::into_raw(boxed_value);
130+
//! let casted_ptr = ptr as *mut u32;
131+
//! let new_box: Box<u32> = unsafe {
132+
//! Box::from_raw(casted_ptr)
133+
//! };
134+
//! ```
135+
//!
136+
//! Any such conversion therefore needs to uphold the same guarantees as using
137+
//! a [pointer-to-pointer cast][ptr-cast] to convert between a `*mut T` and a `*mut U`.
138+
//! In addition such a `core::mem::transmute` call also needs to uphold the requirements
139+
//! of [`core::mem::transmute`] for a transmute between `T` and `U`, especially
140+
//! regarding to size, alignment and the validity of values for both types. Finally
141+
//! it is required that the pointer `*mut T` is well aligned for both types `T` and `U`.
142+
//!
124143
//! # Considerations for unsafe code
125144
//!
126145
//! **Warning: This section is not normative and is subject to change, possibly
@@ -180,6 +199,7 @@
180199
//! [`Layout`]: crate::alloc::Layout
181200
//! [`Layout::for_value(&*value)`]: crate::alloc::Layout::for_value
182201
//! [valid]: ptr#safety
202+
//! [ptr-cast]: https://doc.rust-lang.org/reference/expressions/operator-expr.html#r-expr.as.pointer
183203
184204
#![stable(feature = "rust1", since = "1.0.0")]
185205

0 commit comments

Comments
 (0)