Skip to content

Commit db99f98

Browse files
Put panic code path from copy_from_slice into cold function
The previous `assert_eq` generated quite some code, which is especially problematic when this call is inlined. This commit also slightly improves the panic message from: assertion failed: `(left == right)` left: `3`, right: `2`: destination and source slices have different lengths ...to: source slice length (2) does not match destination slice length (3)
1 parent 3df25ae commit db99f98

File tree

2 files changed

+18
-3
lines changed

2 files changed

+18
-3
lines changed

library/alloc/tests/slice.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -1522,15 +1522,15 @@ fn test_copy_from_slice() {
15221522
}
15231523

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

15321532
#[test]
1533-
#[should_panic(expected = "destination and source slices have different lengths")]
1533+
#[should_panic(expected = "source slice length (4) does not match destination slice length (3)")]
15341534
fn test_copy_from_slice_dst_shorter() {
15351535
let src = [0, 1, 2, 3];
15361536
let mut dst = [0; 3];

library/core/src/slice/mod.rs

+16-1
Original file line numberDiff line numberDiff line change
@@ -2501,7 +2501,22 @@ impl<T> [T] {
25012501
where
25022502
T: Copy,
25032503
{
2504-
assert_eq!(self.len(), src.len(), "destination and source slices have different lengths");
2504+
// The panic code path was put into a cold function to not bloat the
2505+
// call site.
2506+
#[inline(never)]
2507+
#[cold]
2508+
#[track_caller]
2509+
fn len_mismatch_fail(dst_len: usize, src_len: usize) -> ! {
2510+
panic!(
2511+
"source slice length ({}) does not match destination slice length ({})",
2512+
src_len, dst_len,
2513+
);
2514+
}
2515+
2516+
if self.len() != src.len() {
2517+
len_mismatch_fail(self.len(), src.len());
2518+
}
2519+
25052520
// SAFETY: `self` is valid for `self.len()` elements by definition, and `src` was
25062521
// checked to have the same length. The slices cannot overlap because
25072522
// mutable references are exclusive.

0 commit comments

Comments
 (0)