Skip to content

Commit

Permalink
Don't implement mem::replace with mem::swap.
Browse files Browse the repository at this point in the history
  • Loading branch information
m-ou-se committed Mar 11, 2021
1 parent 1d6b0f6 commit bf27819
Showing 1 changed file with 9 additions and 3 deletions.
12 changes: 9 additions & 3 deletions library/core/src/mem/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -812,9 +812,15 @@ pub fn take<T: Default>(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<T>(dest: &mut T, mut src: T) -> T {
swap(dest, &mut src);
src
pub fn replace<T>(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.
Expand Down

0 comments on commit bf27819

Please sign in to comment.