Skip to content

Commit 545ef9d

Browse files
committed
Add Layout::dangling() to return a well-aligned NonNull<u8>
1 parent 2890b37 commit 545ef9d

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 to
146+
/// a `T`, 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)