From bb62be5baa77c240965d3d9b8844b2cf5ed74d4d Mon Sep 17 00:00:00 2001 From: zachs18 <8355914+zachs18@users.noreply.github.com> Date: Sun, 11 Aug 2024 07:59:50 +0000 Subject: [PATCH] Remove "dangling" terminology for zero-sized pointees. (#262) * Update safety comment on BoxBytes pointer field. * Update mentions of "dangling" pointers elsewhere in src/allocation.rs. --- src/allocation.rs | 22 ++++++++++++---------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/src/allocation.rs b/src/allocation.rs index bb4032f..8c5ac80 100644 --- a/src/allocation.rs +++ b/src/allocation.rs @@ -68,9 +68,10 @@ pub fn try_cast_box( #[inline] pub fn try_zeroed_box() -> Result, ()> { if size_of::() == 0 { - // This will not allocate but simply create a dangling pointer. - let dangling = core::ptr::NonNull::dangling().as_ptr(); - return Ok(unsafe { Box::from_raw(dangling) }); + // This will not allocate but simply create an arbitrary non-null + // aligned pointer, valid for Box for a zero-sized pointee. + let ptr = core::ptr::NonNull::dangling().as_ptr(); + return Ok(unsafe { Box::from_raw(ptr) }); } let layout = Layout::new::(); let ptr = unsafe { alloc_zeroed(layout) }; @@ -125,10 +126,11 @@ pub fn try_zeroed_slice_box( length: usize, ) -> Result, ()> { if size_of::() == 0 || length == 0 { - // This will not allocate but simply create a dangling slice pointer. - let dangling = core::ptr::NonNull::dangling().as_ptr(); - let dangling_slice = core::ptr::slice_from_raw_parts_mut(dangling, length); - return Ok(unsafe { Box::from_raw(dangling_slice) }); + // This will not allocate but simply create an arbitrary non-null aligned + // slice pointer, valid for Box for a zero-sized pointee. + let ptr = core::ptr::NonNull::dangling().as_ptr(); + let slice_ptr = core::ptr::slice_from_raw_parts_mut(ptr, length); + return Ok(unsafe { Box::from_raw(slice_ptr) }); } let layout = core::alloc::Layout::array::(length).map_err(|_| ())?; let ptr = unsafe { alloc_zeroed(layout) }; @@ -742,9 +744,9 @@ impl> TransparentWrapperAlloc /// As `Box<[u8]>`, but remembers the original alignment. pub struct BoxBytes { - // SAFETY: `ptr` is owned, points to `layout.size()` initialized bytes, and - // was allocated with `layout` (unless `layout.size() == 0` in which case it - // is dangling). + // SAFETY: `ptr` is aligned to `layout.align()`, points to + // `layout.size()` initialized bytes, and, if `layout.size() > 0`, + // is owned and was allocated with the global allocator with `layout`. ptr: NonNull, layout: Layout, }