From bf27819f37fb7cbe5fb67972d874ab285b741538 Mon Sep 17 00:00:00 2001 From: Mara Bos Date: Thu, 11 Mar 2021 19:04:47 +0100 Subject: [PATCH] Don't implement mem::replace with mem::swap. --- library/core/src/mem/mod.rs | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/library/core/src/mem/mod.rs b/library/core/src/mem/mod.rs index afce6e55b8f..84edbd30a5d 100644 --- a/library/core/src/mem/mod.rs +++ b/library/core/src/mem/mod.rs @@ -812,9 +812,15 @@ pub fn take(dest: &mut T) -> T { #[inline] #[stable(feature = "rust1", since = "1.0.0")] #[must_use = "if you don't need the old value, you can just assign the new value directly"] -pub fn replace(dest: &mut T, mut src: T) -> T { - swap(dest, &mut src); - src +pub fn replace(dest: &mut T, src: T) -> T { + // SAFETY: We read from `dest` but directly write `src` into it afterwards, + // such that the old value is not duplicated. Nothing is dropped and + // nothing here can panic. + unsafe { + let result = ptr::read(dest); + ptr::write(dest, src); + result + } } /// Disposes of a value.