@@ -678,6 +678,56 @@ pub unsafe fn uninitialized<T>() -> T {
678678 }
679679}
680680
681+ /// Create a fresh instance of the inhabited ZST type `T`.
682+ ///
683+ /// Prefer this to [`zeroed`] or [`uninitialized`] or [`transmute_copy`]
684+ /// in places where you know that `T` is zero-sized, but don't have a bound
685+ /// (such as [`Default`]) that would allow you to instantiate it using safe code.
686+ ///
687+ /// If you're not sure whether `T` is an inhabited ZST, then you should be
688+ /// using [`MaybeUninit`], not this function.
689+ ///
690+ /// # Safety
691+ ///
692+ /// - `size_of::<T>()` must be zero.
693+ ///
694+ /// - `T` must be *inhabited*. (It must not be a zero-variant `enum`, for example.)
695+ ///
696+ /// - You must use the value only in ways which do not violate any *safety*
697+ /// invariants of the type.
698+ ///
699+ /// While it's easy to create a *valid* instance of an inhabited ZST, since having
700+ /// no bits in its representation means there's only one possible value, that
701+ /// doesn't mean that it's always *sound* to do so.
702+ ///
703+ /// For example, a library with a global semaphore could give out ZST tokens
704+ /// on `acquire`, and by them being `!Default`+`!Clone` could consume them
705+ /// in `release` to ensure that it's called at most once per `acquire`.
706+ /// Or a library could use a `!Default`+`!Send` token to ensure it's used only
707+ /// from the thread on which it was initialized.
708+ ///
709+ /// # Examples
710+ ///
711+ /// ```
712+ /// #![feature(mem_conjure_zst)]
713+ /// use std::mem::conjure_zst;
714+ ///
715+ /// assert_eq!(unsafe { conjure_zst::<()>() }, ());
716+ /// assert_eq!(unsafe { conjure_zst::<[i32; 0]>() }, []);
717+ /// ```
718+ #[ inline( always) ]
719+ #[ must_use]
720+ #[ unstable( feature = "mem_conjure_zst" , issue = "95383" ) ]
721+ #[ track_caller]
722+ pub const unsafe fn conjure_zst < T > ( ) -> T {
723+ assert ! ( size_of:: <T >( ) == 0 ) ; // FIXME: Use assert_eq! once that's allowed in const
724+
725+ // SAFETY: because the caller must guarantee that it's inhabited and zero-sized,
726+ // there's nothing in the representation that needs to be set.
727+ // `assume_init` calls `assert_inhabited`, so we don't need to here.
728+ unsafe { MaybeUninit :: uninit ( ) . assume_init ( ) }
729+ }
730+
681731/// Swaps the values at two mutable locations, without deinitializing either one.
682732///
683733/// * If you want to swap with a default or dummy value, see [`take`].
0 commit comments