]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/transmute/transmute_num_to_bytes.rs
5ba58a764940191728d0266f5c77b2e2cc113ef2
[rust.git] / clippy_lints / src / transmute / transmute_num_to_bytes.rs
1 use super::TRANSMUTE_NUM_TO_BYTES;
2 use clippy_utils::diagnostics::span_lint_and_then;
3 use clippy_utils::sugg;
4 use rustc_errors::Applicability;
5 use rustc_hir::Expr;
6 use rustc_lint::LateContext;
7 use rustc_middle::ty::{self, Ty, UintTy};
8
9 /// Checks for `transmute_int_to_float` lint.
10 /// Returns `true` if it's triggered, otherwise returns `false`.
11 pub(super) fn check<'tcx>(
12     cx: &LateContext<'tcx>,
13     e: &'tcx Expr<'_>,
14     from_ty: Ty<'tcx>,
15     to_ty: Ty<'tcx>,
16     args: &'tcx [Expr<'_>],
17     const_context: bool,
18 ) -> bool {
19     match (&from_ty.kind(), &to_ty.kind()) {
20         (ty::Int(_) | ty::Uint(_) | ty::Float(_), ty::Array(arr_ty, _)) => {
21             if !matches!(arr_ty.kind(), ty::Uint(UintTy::U8)) {
22                 return false;
23             }
24             if matches!(from_ty.kind(), ty::Float(_)) && const_context {
25                 // TODO: Remove when const_float_bits_conv is stabilized
26                 // rust#72447
27                 return false;
28             }
29
30             span_lint_and_then(
31                 cx,
32                 TRANSMUTE_NUM_TO_BYTES,
33                 e.span,
34                 &format!("transmute from a `{}` to a `{}`", from_ty, to_ty),
35                 |diag| {
36                     let arg = sugg::Sugg::hir(cx, &args[0], "..");
37                     diag.span_suggestion(
38                         e.span,
39                         "consider using `to_ne_bytes()`",
40                         format!("{}.to_ne_bytes()", arg),
41                         Applicability::Unspecified,
42                     );
43                 },
44             );
45             true
46         },
47         _ => false,
48     }
49 }