Skip to content

Commit 963b0aa

Browse files
authored
Rollup merge of rust-lang#69794 - TimDiekmann:dangling, r=Amanieu
Add `Layout::dangling()` to return a well-aligned `NonNull<u8>` Adds a convenient function to `Layout` to create a `NonNull<u8>` out of a layout to be returned on ZST allocations. This is the first item on the roadmap to support ZSTs in `AllocRef`: rust-lang/wg-allocators#38 (comment) r? @Amanieu
2 parents f1f4864 + 09d3ba1 commit 963b0aa

File tree

3 files changed

+16
-0
lines changed

3 files changed

+16
-0
lines changed

src/libcore/alloc.rs

+12
Original file line numberDiff line numberDiff line change
@@ -140,6 +140,18 @@ impl Layout {
140140
unsafe { Layout::from_size_align_unchecked(size, align) }
141141
}
142142

143+
/// Creates a `NonNull` that is dangling, but well-aligned for this Layout.
144+
///
145+
/// Note that the pointer value may potentially represent a valid pointer,
146+
/// which means this must not be used as a "not yet initialized"
147+
/// sentinel value. Types that lazily allocate must track initialization by
148+
/// some other means.
149+
#[unstable(feature = "alloc_layout_extra", issue = "55724")]
150+
pub const fn dangling(&self) -> NonNull<u8> {
151+
// align is non-zero and a power of two
152+
unsafe { NonNull::new_unchecked(self.align() as *mut u8) }
153+
}
154+
143155
/// Creates a layout describing the record that can hold a value
144156
/// of the same layout as `self`, but that also is aligned to
145157
/// alignment `align` (measured in bytes).

src/libcore/tests/alloc.rs

+3
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,13 @@
11
use core::alloc::Layout;
2+
use core::ptr::NonNull;
23

34
#[test]
45
fn const_unchecked_layout() {
56
const SIZE: usize = 0x2000;
67
const ALIGN: usize = 0x1000;
78
const LAYOUT: Layout = unsafe { Layout::from_size_align_unchecked(SIZE, ALIGN) };
9+
const DANGLING: NonNull<u8> = LAYOUT.dangling();
810
assert_eq!(LAYOUT.size(), SIZE);
911
assert_eq!(LAYOUT.align(), ALIGN);
12+
assert_eq!(Some(DANGLING), NonNull::new(ALIGN as *mut u8));
1013
}

src/libcore/tests/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
#![feature(alloc_layout_extra)]
12
#![feature(bool_to_option)]
23
#![feature(bound_cloned)]
34
#![feature(box_syntax)]

0 commit comments

Comments
 (0)