Skip to content

Commit 0b62380

Browse files
committed
cast_possible_truncation: do not lint on size_of
1 parent 6eff441 commit 0b62380

File tree

2 files changed

+16
-13
lines changed

2 files changed

+16
-13
lines changed

clippy_lints/src/casts/cast_possible_truncation.rs

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ use rustc_hir::def::{DefKind, Res};
99
use rustc_hir::{BinOpKind, Expr, ExprKind};
1010
use rustc_lint::LateContext;
1111
use rustc_middle::ty::{self, FloatTy, Ty};
12+
use rustc_span::symbol::sym;
1213
use rustc_span::Span;
1314
use rustc_target::abi::IntegerType;
1415

@@ -80,6 +81,20 @@ fn apply_reductions(cx: &LateContext<'_>, nbits: u64, expr: &Expr<'_>, signed: b
8081
}
8182
},
8283
ExprKind::Path(ref _qpath) => get_constant_bits(cx, expr).unwrap_or(nbits),
84+
// mem::size_of::<T>();
85+
ExprKind::Call(func, []) => {
86+
if let ExprKind::Path(ref func_qpath) = func.kind
87+
&& let Some(def_id) = cx.qpath_res(func_qpath, func.hir_id).opt_def_id()
88+
&& cx.tcx.is_diagnostic_item(sym::mem_size_of, def_id)
89+
&& let Some(ty) = cx.typeck_results().node_args(func.hir_id).types().next()
90+
&& let Ok(layout) = cx.tcx.layout_of(cx.param_env.and(ty))
91+
{
92+
let size: u64 = layout.layout.size().bytes();
93+
(64 - size.leading_zeros()).into()
94+
} else {
95+
nbits
96+
}
97+
},
8398
_ => nbits,
8499
}
85100
}

tests/ui/cast.stderr

Lines changed: 1 addition & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -731,17 +731,5 @@ help: ... or use `try_from` and handle the error accordingly
731731
LL | u8::try_from(255 % 999999u64);
732732
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
733733

734-
error: casting `usize` to `u32` may truncate the value on targets with 64-bit wide pointers
735-
--> tests/ui/cast.rs:509:5
736-
|
737-
LL | core::mem::size_of::<String>() as u32;
738-
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
739-
|
740-
= help: if this is intentional allow the lint with `#[allow(clippy::cast_possible_truncation)]` ...
741-
help: ... or use `try_from` and handle the error accordingly
742-
|
743-
LL | u32::try_from(core::mem::size_of::<String>());
744-
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
745-
746-
error: aborting due to 93 previous errors
734+
error: aborting due to 92 previous errors
747735

0 commit comments

Comments
 (0)