about summary refs log tree commit diff
diff options
context:
space:
mode:
authorMatthias Krüger <matthias.krueger@famsik.de>2022-01-29 14:46:31 +0100
committerGitHub <noreply@github.com>2022-01-29 14:46:31 +0100
commit37e9cb34e574f309aaf943a597ad92c2f768ff1e (patch)
tree29fa59db09d4db6e8482a4d8b5f80c06dd2787ec
parent9e86a434a770b453ded7dabd3203efc9c61eb2e5 (diff)
parentcdd0873db690cbcea1e5a011bbfc7fc94c5d5a6e (diff)
Rollup merge of #93236 - woppopo:const_nonnull_new, r=oli-obk
Make `NonNull::new` `const`

Tracking issue: #93235
-rw-r--r--library/core/src/ptr/non_null.rs3
-rw-r--r--library/core/tests/lib.rs2
-rw-r--r--library/core/tests/ptr.rs15
3 files changed, 19 insertions, 1 deletions
diff --git a/library/core/src/ptr/non_null.rs b/library/core/src/ptr/non_null.rs
index 3a7e99faccf..3f5d3f62c96 100644
--- a/library/core/src/ptr/non_null.rs
+++ b/library/core/src/ptr/non_null.rs
@@ -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) })
diff --git a/library/core/tests/lib.rs b/library/core/tests/lib.rs
index 1d49d7e47cb..a2bef2012cf 100644
--- a/library/core/tests/lib.rs
+++ b/library/core/tests/lib.rs
@@ -17,7 +17,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)]
diff --git a/library/core/tests/ptr.rs b/library/core/tests/ptr.rs
index b9c0d75b702..bbfd2d64dda 100644
--- a/library/core/tests/ptr.rs
+++ b/library/core/tests/ptr.rs
@@ -275,6 +275,21 @@ fn test_unsized_nonnull() {
 }
 
 #[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
 // ABI, or even point to an actual executable code, because the function itself is never invoked.