Skip to content
This repository was archived by the owner on May 28, 2025. It is now read-only.

Commit 4ec2193

Browse files
committed
Fix size computation when element is a slice
In this case, a dereference is needed before using `mem::size_of_val()`.
1 parent 40bead0 commit 4ec2193

File tree

4 files changed

+38
-2
lines changed

4 files changed

+38
-2
lines changed

clippy_lints/src/manual_slice_size_calculation.rs

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,11 @@ impl<'tcx> LateLintPass<'tcx> for ManualSliceSizeCalculation {
4949
{
5050
let ctxt = expr.span.ctxt();
5151
let mut app = Applicability::MachineApplicable;
52-
let deref = "*".repeat(refs_count - 1);
52+
let deref = if refs_count > 0 {
53+
"*".repeat(refs_count - 1)
54+
} else {
55+
"&".into()
56+
};
5357
let val_name = snippet_with_context(cx, receiver.span, ctxt, "slice", &mut app).0;
5458
let Some(sugg) = std_or_core(cx) else { return };
5559

tests/ui/manual_slice_size_calculation.fixed

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,3 +64,16 @@ const fn _const(s_i32: &[i32]) {
6464
// True negative:
6565
let _ = s_i32.len() * size_of::<i32>(); // Ok, can't use size_of_val in const
6666
}
67+
68+
fn issue_14802() {
69+
struct IcedSlice {
70+
dst: [u8],
71+
}
72+
73+
impl IcedSlice {
74+
fn get_len(&self) -> usize {
75+
std::mem::size_of_val(&self.dst)
76+
//~^ manual_slice_size_calculation
77+
}
78+
}
79+
}

tests/ui/manual_slice_size_calculation.rs

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,3 +64,16 @@ const fn _const(s_i32: &[i32]) {
6464
// True negative:
6565
let _ = s_i32.len() * size_of::<i32>(); // Ok, can't use size_of_val in const
6666
}
67+
68+
fn issue_14802() {
69+
struct IcedSlice {
70+
dst: [u8],
71+
}
72+
73+
impl IcedSlice {
74+
fn get_len(&self) -> usize {
75+
self.dst.len() * size_of::<u8>()
76+
//~^ manual_slice_size_calculation
77+
}
78+
}
79+
}

tests/ui/manual_slice_size_calculation.stderr

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,5 +55,11 @@ error: manual slice size calculation
5555
LL | let _ = external!(&[1u64][..]).len() * size_of::<u64>();
5656
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `std::mem::size_of_val(external!(&[1u64][..]))`
5757

58-
error: aborting due to 9 previous errors
58+
error: manual slice size calculation
59+
--> tests/ui/manual_slice_size_calculation.rs:75:13
60+
|
61+
LL | self.dst.len() * size_of::<u8>()
62+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `std::mem::size_of_val(&self.dst)`
63+
64+
error: aborting due to 10 previous errors
5965

0 commit comments

Comments
 (0)