Skip to content

For small types, just swap directly #43351

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 13 additions & 2 deletions src/libcore/mem.rs
Original file line number Diff line number Diff line change
Expand Up @@ -548,8 +548,19 @@ pub unsafe fn uninitialized<T>() -> T {
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn swap<T>(x: &mut T, y: &mut T) {
unsafe {
ptr::swap_nonoverlapping(x, y, 1);
if size_of::<T>() < 32 {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Isn't 32 a bit magical? Can we get the "correct" size from some platform info?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

32 is the block size used in ptr::swap_nonoverlapping_bytes, so is the point where the simd loop there starts to potentially do something interesting.

That choice is from PR #40454, which has history and a bunch of perf numbers.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is it possible to make it so this function and swap_nonoverlapping_bytes are always in sync? e.g., If the latter is updated, can we also guarantee that the former also must be updated?

// For small types, just swap directly.
// This keeps alignment and lets debug not run the big loop.
unsafe {
let temp = ptr::read(x);
ptr::copy_nonoverlapping(y, x, 1);
ptr::write(y, temp);
}
} else {
// For large types, use the simd swapping code.
unsafe {
ptr::swap_nonoverlapping(x, y, 1);
}
}
}

Expand Down
7 changes: 7 additions & 0 deletions src/libcore/tests/mem.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,13 @@ fn test_swap() {
swap(&mut x, &mut y);
assert_eq!(x, 42);
assert_eq!(y, 31337);

// A bigger one to hit the SIMD loop
let mut x = [1u64, 2, 3, 4, 5, 6, 7, 8];
let mut y = [11, 12, 13, 14, 15, 16, 17, 18];
swap(&mut x, &mut y);
assert_eq!(x, [11, 12, 13, 14, 15, 16, 17, 18]);
assert_eq!(y, [1, 2, 3, 4, 5, 6, 7, 8]);
}

#[test]
Expand Down