diff --git a/library/core/src/mem/mod.rs b/library/core/src/mem/mod.rs index a79a204e2c6a0..da0048cca6e05 100644 --- a/library/core/src/mem/mod.rs +++ b/library/core/src/mem/mod.rs @@ -908,15 +908,9 @@ pub fn take(dest: &mut T) -> T { #[must_use = "if you don't need the old value, you can just assign the new value directly"] #[rustc_const_unstable(feature = "const_replace", issue = "83164")] #[cfg_attr(not(test), rustc_diagnostic_item = "mem_replace")] -pub const 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 - } +pub const fn replace(dest: &mut T, mut src: T) -> T { + swap(dest, &mut src); + src } /// Disposes of a value. diff --git a/src/tools/miri/tests/fail/both_borrows/aliasing_mut4.tree.stderr b/src/tools/miri/tests/fail/both_borrows/aliasing_mut4.tree.stderr index 106e5c19bf277..79c6bb67efb48 100644 --- a/src/tools/miri/tests/fail/both_borrows/aliasing_mut4.tree.stderr +++ b/src/tools/miri/tests/fail/both_borrows/aliasing_mut4.tree.stderr @@ -1,8 +1,8 @@ error: Undefined Behavior: write access through is forbidden --> RUSTLIB/core/src/mem/mod.rs:LL:CC | -LL | ptr::write(dest, src); - | ^^^^^^^^^^^^^^^^^^^^^ write access through is forbidden +LL | ptr::write(x, b); + | ^^^^^^^^^^^^^^^^ write access through is forbidden | = help: this indicates a potential bug in the program: it performed an invalid operation, but the Tree Borrows rules it violated are still experimental = help: the accessed tag is foreign to the protected tag (i.e., it is not a child) @@ -19,6 +19,8 @@ help: the protected tag was created here, in the initial state Frozen LL | pub fn safe(x: &i32, y: &mut Cell) { | ^ = note: BACKTRACE (of the first span): + = note: inside `std::mem::swap_simple::` at RUSTLIB/core/src/mem/mod.rs:LL:CC + = note: inside `std::mem::swap::` at RUSTLIB/core/src/mem/mod.rs:LL:CC = note: inside `std::mem::replace::` at RUSTLIB/core/src/mem/mod.rs:LL:CC = note: inside `std::cell::Cell::::replace` at RUSTLIB/core/src/cell.rs:LL:CC = note: inside `std::cell::Cell::::set` at RUSTLIB/core/src/cell.rs:LL:CC