Skip to content

Commit 37e9cb3

Browse files
authored
Rollup merge of #93236 - woppopo:const_nonnull_new, r=oli-obk
Make `NonNull::new` `const` Tracking issue: #93235
2 parents 9e86a43 + cdd0873 commit 37e9cb3

File tree

3 files changed

+19
-1
lines changed

3 files changed

+19
-1
lines changed

library/core/src/ptr/non_null.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -211,8 +211,9 @@ impl<T: ?Sized> NonNull<T> {
211211
/// }
212212
/// ```
213213
#[stable(feature = "nonnull", since = "1.25.0")]
214+
#[rustc_const_unstable(feature = "const_nonnull_new", issue = "93235")]
214215
#[inline]
215-
pub fn new(ptr: *mut T) -> Option<Self> {
216+
pub const fn new(ptr: *mut T) -> Option<Self> {
216217
if !ptr.is_null() {
217218
// SAFETY: The pointer is already checked and is not null
218219
Some(unsafe { Self::new_unchecked(ptr) })

library/core/tests/lib.rs

+2
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,9 @@
1717
#![feature(const_maybe_uninit_as_mut_ptr)]
1818
#![feature(const_maybe_uninit_assume_init)]
1919
#![feature(const_maybe_uninit_assume_init_read)]
20+
#![feature(const_nonnull_new)]
2021
#![feature(const_num_from_num)]
22+
#![feature(const_ptr_as_ref)]
2123
#![feature(const_ptr_read)]
2224
#![feature(const_ptr_write)]
2325
#![feature(const_ptr_offset)]

library/core/tests/ptr.rs

+15
Original file line numberDiff line numberDiff line change
@@ -274,6 +274,21 @@ fn test_unsized_nonnull() {
274274
assert!(ys == zs);
275275
}
276276

277+
#[test]
278+
fn test_const_nonnull_new() {
279+
const {
280+
assert!(NonNull::new(core::ptr::null_mut::<()>()).is_none());
281+
282+
let value = &mut 0u32;
283+
let mut ptr = NonNull::new(value).unwrap();
284+
unsafe { *ptr.as_mut() = 42 };
285+
286+
let reference = unsafe { &*ptr.as_ref() };
287+
assert!(*reference == *value);
288+
assert!(*reference == 42);
289+
};
290+
}
291+
277292
#[test]
278293
#[allow(warnings)]
279294
// Have a symbol for the test below. It doesn’t need to be an actual variadic function, match the

0 commit comments

Comments
 (0)