Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Layout::dangling() to return a well-aligned NonNull<u8> #69794

Merged
merged 2 commits into from Mar 8, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
12 changes: 12 additions & 0 deletions src/libcore/alloc.rs
Expand Up @@ -140,6 +140,18 @@ impl Layout {
unsafe { Layout::from_size_align_unchecked(size, align) }
}

/// Creates a `NonNull` that is dangling, but well-aligned for this Layout.
///
/// Note that the pointer value may potentially represent a valid pointer,
/// which means this must not be used as a "not yet initialized"
/// sentinel value. Types that lazily allocate must track initialization by
/// some other means.
#[unstable(feature = "alloc_layout_extra", issue = "55724")]
pub const fn dangling(&self) -> NonNull<u8> {
// align is non-zero and a power of two
unsafe { NonNull::new_unchecked(self.align() as *mut u8) }
}

/// Creates a layout describing the record that can hold a value
/// of the same layout as `self`, but that also is aligned to
/// alignment `align` (measured in bytes).
Expand Down
3 changes: 3 additions & 0 deletions src/libcore/tests/alloc.rs
@@ -1,10 +1,13 @@
use core::alloc::Layout;
use core::ptr::NonNull;

#[test]
fn const_unchecked_layout() {
const SIZE: usize = 0x2000;
const ALIGN: usize = 0x1000;
const LAYOUT: Layout = unsafe { Layout::from_size_align_unchecked(SIZE, ALIGN) };
const DANGLING: NonNull<u8> = LAYOUT.dangling();
assert_eq!(LAYOUT.size(), SIZE);
assert_eq!(LAYOUT.align(), ALIGN);
assert_eq!(Some(DANGLING), NonNull::new(ALIGN as *mut u8));
}
1 change: 1 addition & 0 deletions src/libcore/tests/lib.rs
@@ -1,3 +1,4 @@
#![feature(alloc_layout_extra)]
#![feature(bool_to_option)]
#![feature(bound_cloned)]
#![feature(box_syntax)]
Expand Down