core: optimize ptr::replace

This commit is contained in:
joboet
2024-03-16 17:51:00 +01:00
parent c5b571310d
commit f2721338f6

View File

@@ -1114,7 +1114,7 @@ const unsafe fn swap_nonoverlapping_simple_untyped<T>(x: *mut T, y: *mut T, coun
#[stable(feature = "rust1", since = "1.0.0")] #[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_unstable(feature = "const_replace", issue = "83164")] #[rustc_const_unstable(feature = "const_replace", issue = "83164")]
#[rustc_diagnostic_item = "ptr_replace"] #[rustc_diagnostic_item = "ptr_replace"]
pub const unsafe fn replace<T>(dst: *mut T, mut src: T) -> T { pub const unsafe fn replace<T>(dst: *mut T, src: T) -> T {
// SAFETY: the caller must guarantee that `dst` is valid to be // SAFETY: the caller must guarantee that `dst` is valid to be
// cast to a mutable reference (valid for writes, aligned, initialized), // cast to a mutable reference (valid for writes, aligned, initialized),
// and cannot overlap `src` since `dst` must point to a distinct // and cannot overlap `src` since `dst` must point to a distinct
@@ -1128,9 +1128,8 @@ pub const unsafe fn replace<T>(dst: *mut T, mut src: T) -> T {
align: usize = align_of::<T>(), align: usize = align_of::<T>(),
) => is_aligned_and_not_null(addr, align) ) => is_aligned_and_not_null(addr, align)
); );
mem::swap(&mut *dst, &mut src); // cannot overlap mem::replace(&mut *dst, src)
} }
src
} }
/// Reads the value from `src` without moving it. This leaves the /// Reads the value from `src` without moving it. This leaves the