Skip to content

Commit c8a5c8d

Browse files
committed
Stabilize const_maybe_uninit_zeroed
Make `MaybeUninit::zeroed` const stable. Newly stable API: // core::mem, std::mem impl<T> MaybeUninit<T> { pub const fn zeroed() -> MaybeUninit<T>; } Tracking issue: rust-lang#91850
1 parent 2ba4eb2 commit c8a5c8d

File tree

2 files changed

+22
-7
lines changed

2 files changed

+22
-7
lines changed

library/alloc/src/lib.rs

-1
Original file line numberDiff line numberDiff line change
@@ -113,7 +113,6 @@
113113
#![feature(const_eval_select)]
114114
#![feature(const_maybe_uninit_as_mut_ptr)]
115115
#![feature(const_maybe_uninit_write)]
116-
#![feature(const_maybe_uninit_zeroed)]
117116
#![feature(const_pin)]
118117
#![feature(const_refs_to_cell)]
119118
#![feature(const_size_of_val)]

library/core/src/mem/maybe_uninit.rs

+22-6
Original file line numberDiff line numberDiff line change
@@ -374,6 +374,20 @@ impl<T> MaybeUninit<T> {
374374
/// assert_eq!(x, (0, false));
375375
/// ```
376376
///
377+
/// This can be used in const contexts, such as to indicate the end of plugin registration
378+
/// arrays.
379+
///
380+
/// ```
381+
/// use std::mem::MaybeUninit;
382+
///
383+
/// struct PluginInfo { id: u32, action: Option<fn(u32) -> u32> }
384+
///
385+
/// static PLUGIN_LIST: [PluginInfo; 2] = [
386+
/// PluginInfo { id: 1, action: Some(|x| x + 5) },
387+
/// unsafe { MaybeUninit::zeroed().assume_init() }
388+
/// ];
389+
/// ```
390+
///
377391
/// *Incorrect* usage of this function: calling `x.zeroed().assume_init()`
378392
/// when `0` is not a valid bit-pattern for the type:
379393
///
@@ -387,17 +401,19 @@ impl<T> MaybeUninit<T> {
387401
/// // Inside a pair, we create a `NotZero` that does not have a valid discriminant.
388402
/// // This is undefined behavior. ⚠️
389403
/// ```
390-
#[stable(feature = "maybe_uninit", since = "1.36.0")]
391-
#[rustc_const_unstable(feature = "const_maybe_uninit_zeroed", issue = "91850")]
392-
#[must_use]
393404
#[inline]
405+
#[must_use]
394406
#[rustc_diagnostic_item = "maybe_uninit_zeroed"]
407+
#[stable(feature = "maybe_uninit", since = "1.36.0")]
408+
// These are OK to allow since we do not leak &mut to user-visible API
409+
#[rustc_allow_const_fn_unstable(const_mut_refs)]
410+
#[rustc_allow_const_fn_unstable(const_ptr_write)]
411+
#[rustc_allow_const_fn_unstable(const_maybe_uninit_as_mut_ptr)]
412+
#[rustc_const_stable(feature = "const_maybe_uninit_zeroed", since = "CURRENT_RUSTC_VERSION")]
395413
pub const fn zeroed() -> MaybeUninit<T> {
396414
let mut u = MaybeUninit::<T>::uninit();
397415
// SAFETY: `u.as_mut_ptr()` points to allocated memory.
398-
unsafe {
399-
u.as_mut_ptr().write_bytes(0u8, 1);
400-
}
416+
unsafe { u.as_mut_ptr().write_bytes(0u8, 1) };
401417
u
402418
}
403419

0 commit comments

Comments
 (0)