Skip to main content

cast_box

Function cast_box 

Source
pub(crate) unsafe fn cast_box<T: VarULE + ?Sized>(bytes: Box<[u8]>) -> Box<T>
Expand description

Reconstructs a Box<T> from a Box<[u8]> while preserving unique pointer provenance and correctly resolving DST metadata.

This is an internal helper used to safely convert a heap-allocated byte buffer into an owned Box<T> where T is an unsized VarULE type.

§Why this is needed

Reconstructing a Box<T> is tricky because:

  1. Provenance: If we derive the pointer from a temporary shared reference (e.g., &[u8]), Miri/Stacked Borrows will tag the pointer as SharedReadOnly. Reclaiming unique ownership and deallocating through a pointer with shared provenance is Undefined Behavior. To avoid this, we must derive the final pointer directly from Box::into_raw (which carries Unique provenance).
  2. DST Metadata: Unsized types (like VarTupleULE) may have custom metadata that is not simply the byte length of the allocation. We must use T::from_bytes_unchecked to construct a reference with the correct metadata, and then combine that metadata with the unique thin pointer from Box::into_raw without clobbering the provenance.

§Safety

  • T::from_bytes_unchecked must be safe to call on the slice behind bytes