Skip to content

Commit

Permalink
Rollup merge of rust-lang#93236 - woppopo:const_nonnull_new, r=oli-obk
Browse files Browse the repository at this point in the history
Make `NonNull::new` `const`

Tracking issue: rust-lang#93235
  • Loading branch information
matthiaskrgr authored Jan 29, 2022
2 parents ee9307d + cdd0873 commit 5cbe671
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 1 deletion.
3 changes: 2 additions & 1 deletion library/core/src/ptr/non_null.rs
Original file line number Diff line number Diff line change
Expand Up @@ -211,8 +211,9 @@ impl<T: ?Sized> NonNull<T> {
/// }
/// ```
#[stable(feature = "nonnull", since = "1.25.0")]
#[rustc_const_unstable(feature = "const_nonnull_new", issue = "93235")]
#[inline]
pub fn new(ptr: *mut T) -> Option<Self> {
pub const fn new(ptr: *mut T) -> Option<Self> {
if !ptr.is_null() {
// SAFETY: The pointer is already checked and is not null
Some(unsafe { Self::new_unchecked(ptr) })
Expand Down
2 changes: 2 additions & 0 deletions library/core/tests/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,9 @@
#![feature(const_maybe_uninit_as_mut_ptr)]
#![feature(const_maybe_uninit_assume_init)]
#![feature(const_maybe_uninit_assume_init_read)]
#![feature(const_nonnull_new)]
#![feature(const_num_from_num)]
#![feature(const_ptr_as_ref)]
#![feature(const_ptr_read)]
#![feature(const_ptr_write)]
#![feature(const_ptr_offset)]
Expand Down
15 changes: 15 additions & 0 deletions library/core/tests/ptr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -274,6 +274,21 @@ fn test_unsized_nonnull() {
assert!(ys == zs);
}

#[test]
fn test_const_nonnull_new() {
const {
assert!(NonNull::new(core::ptr::null_mut::<()>()).is_none());

let value = &mut 0u32;
let mut ptr = NonNull::new(value).unwrap();
unsafe { *ptr.as_mut() = 42 };

let reference = unsafe { &*ptr.as_ref() };
assert!(*reference == *value);
assert!(*reference == 42);
};
}

#[test]
#[allow(warnings)]
// Have a symbol for the test below. It doesn’t need to be an actual variadic function, match the
Expand Down

0 comments on commit 5cbe671

Please sign in to comment.