Skip to content

Commit e3ca397

Browse files
authored
Rollup merge of rust-lang#102198 - lukas-code:nonnull_as_ref, r=Amanieu
`const`-stablilize `NonNull::as_ref` A bunch of pointer to reference methods have been made unstably const some time ago in rust-lang#91823 under the feature gate `const_ptr_as_ref`. Out of these, `NonNull::as_ref` can be implemented as a `const fn` in stable rust today, so i hereby propose to const stabilize this function only. Tracking issue: rust-lang#91822 ``@rustbot`` label +T-libs-api -T-libs
2 parents 27e3a74 + 855b8b8 commit e3ca397

File tree

4 files changed

+33
-2
lines changed

4 files changed

+33
-2
lines changed

library/core/src/ptr/non_null.rs

+3-2
Original file line numberDiff line numberDiff line change
@@ -367,13 +367,14 @@ impl<T: ?Sized> NonNull<T> {
367367
///
368368
/// [the module documentation]: crate::ptr#safety
369369
#[stable(feature = "nonnull", since = "1.25.0")]
370-
#[rustc_const_unstable(feature = "const_ptr_as_ref", issue = "91822")]
370+
#[rustc_const_stable(feature = "const_nonnull_as_ref", since = "CURRENT_RUSTC_VERSION")]
371371
#[must_use]
372372
#[inline(always)]
373373
pub const unsafe fn as_ref<'a>(&self) -> &'a T {
374374
// SAFETY: the caller must guarantee that `self` meets all the
375375
// requirements for a reference.
376-
unsafe { &*self.as_ptr() }
376+
// `cast_const` avoids a mutable raw pointer deref.
377+
unsafe { &*self.as_ptr().cast_const() }
377378
}
378379

379380
/// Returns a unique reference to the value. If the value may be uninitialized, [`as_uninit_mut`]
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
// check-pass
2+
3+
use std::ptr::NonNull;
4+
5+
const NON_NULL: NonNull<u8> = unsafe { NonNull::new_unchecked((&42u8 as *const u8).cast_mut()) };
6+
const _: () = assert!(42 == *unsafe { NON_NULL.as_ref() });
7+
8+
fn main() {}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
use std::ptr::NonNull;
2+
3+
const NON_NULL: NonNull<u8> = unsafe { NonNull::dangling() };
4+
const _: () = assert!(42 == *unsafe { NON_NULL.as_ref() });
5+
6+
fn main() {}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
error[E0080]: evaluation of constant value failed
2+
--> $SRC_DIR/core/src/ptr/non_null.rs:LL:COL
3+
|
4+
= note: dereferencing pointer failed: 0x1[noalloc] is a dangling pointer (it has no provenance)
5+
|
6+
note: inside `NonNull::<u8>::as_ref::<'_>`
7+
--> $SRC_DIR/core/src/ptr/non_null.rs:LL:COL
8+
note: inside `_`
9+
--> $DIR/nonnull_as_ref_ub.rs:4:39
10+
|
11+
LL | const _: () = assert!(42 == *unsafe { NON_NULL.as_ref() });
12+
| ^^^^^^^^^^^^^^^^^
13+
14+
error: aborting due to previous error
15+
16+
For more information about this error, try `rustc --explain E0080`.

0 commit comments

Comments
 (0)