Skip to content

Put panic code path from copy_from_slice into cold function #74512

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

Merged
merged 1 commit into from
Aug 13, 2020
Merged
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
4 changes: 2 additions & 2 deletions library/alloc/tests/slice.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1522,15 +1522,15 @@ fn test_copy_from_slice() {
}

#[test]
#[should_panic(expected = "destination and source slices have different lengths")]
#[should_panic(expected = "source slice length (4) does not match destination slice length (5)")]
fn test_copy_from_slice_dst_longer() {
let src = [0, 1, 2, 3];
let mut dst = [0; 5];
dst.copy_from_slice(&src);
}

#[test]
#[should_panic(expected = "destination and source slices have different lengths")]
#[should_panic(expected = "source slice length (4) does not match destination slice length (3)")]
fn test_copy_from_slice_dst_shorter() {
let src = [0, 1, 2, 3];
let mut dst = [0; 3];
Expand Down
17 changes: 16 additions & 1 deletion library/core/src/slice/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2501,7 +2501,22 @@ impl<T> [T] {
where
T: Copy,
{
assert_eq!(self.len(), src.len(), "destination and source slices have different lengths");
// The panic code path was put into a cold function to not bloat the
// call site.
#[inline(never)]
#[cold]
#[track_caller]
fn len_mismatch_fail(dst_len: usize, src_len: usize) -> ! {
panic!(
"source slice length ({}) does not match destination slice length ({})",
src_len, dst_len,
);
}

if self.len() != src.len() {
len_mismatch_fail(self.len(), src.len());
}

// SAFETY: `self` is valid for `self.len()` elements by definition, and `src` was
// checked to have the same length. The slices cannot overlap because
// mutable references are exclusive.
Expand Down