Skip to content

Commit c0b1c1a

Browse files
authored
Rollup merge of #117243 - chfogelman:replace-not-swap-comment, r=thomcc
Explain implementation of mem::replace This adds a comment to explain why `mem::replace` is not implemented in terms of `mem::swap` to prevent [naïfs like me](#117189) from trying to "fix" it.
2 parents 2656c98 + 94ecabf commit c0b1c1a

File tree

1 file changed

+4
-0
lines changed

1 file changed

+4
-0
lines changed

library/core/src/mem/mod.rs

+4
Original file line numberDiff line numberDiff line change
@@ -909,6 +909,10 @@ pub fn take<T: Default>(dest: &mut T) -> T {
909909
#[rustc_const_unstable(feature = "const_replace", issue = "83164")]
910910
#[cfg_attr(not(test), rustc_diagnostic_item = "mem_replace")]
911911
pub const fn replace<T>(dest: &mut T, src: T) -> T {
912+
// It may be tempting to use `swap` to avoid `unsafe` here. Don't!
913+
// The compiler optimizes the implementation below to two `memcpy`s
914+
// while `swap` would require at least three. See PR#83022 for details.
915+
912916
// SAFETY: We read from `dest` but directly write `src` into it afterwards,
913917
// such that the old value is not duplicated. Nothing is dropped and
914918
// nothing here can panic.

0 commit comments

Comments
 (0)