|
| 1 | +use crate::methods::method_call; |
| 2 | +use clippy_utils::diagnostics::span_lint; |
| 3 | +use rustc_hir::Expr; |
| 4 | +use rustc_lint::{LateContext, LateLintPass}; |
| 5 | +use rustc_middle::ty::{self}; |
| 6 | +use rustc_session::declare_lint_pass; |
| 7 | + |
| 8 | +declare_clippy_lint! { |
| 9 | + /// ### What it does |
| 10 | + /// Checks for usage of `iter().any()` on slices of `u8` or `i8` and suggests using `contains()` instead. |
| 11 | + /// |
| 12 | + /// ### Why is this bad? |
| 13 | + /// `iter().any()` on slices of `u8` or `i8` is optimized to use `memchr`. |
| 14 | + /// |
| 15 | + /// ### Example |
| 16 | + /// ```no_run |
| 17 | + /// fn foo(values: &[u8]) -> bool { |
| 18 | + /// values.iter().any(|&v| v == 10) |
| 19 | + /// } |
| 20 | + /// ``` |
| 21 | + /// Use instead: |
| 22 | + /// ```no_run |
| 23 | + /// fn foo(values: &[u8]) -> bool { |
| 24 | + /// values.contains(&10) |
| 25 | + /// } |
| 26 | + /// ``` |
| 27 | + #[clippy::version = "1.85.0"] |
| 28 | + pub CONTAINS_FOR_SLICE, |
| 29 | + perf, |
| 30 | + "using `contains()` instead of `iter().any()` on u8/i8 slices is more efficient" |
| 31 | +} |
| 32 | + |
| 33 | +declare_lint_pass!(ContainsForSlice => [CONTAINS_FOR_SLICE]); |
| 34 | + |
| 35 | +impl LateLintPass<'_> for ContainsForSlice { |
| 36 | + fn check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) { |
| 37 | + if !expr.span.from_expansion() |
| 38 | + // any() |
| 39 | + && let Some((name, recv, _, _, _)) = method_call(expr) |
| 40 | + && name == "any" |
| 41 | + // iter() |
| 42 | + && let Some((name, recv, _, _, _)) = method_call(recv) |
| 43 | + && name == "iter" |
| 44 | + { |
| 45 | + // check if the receiver is a u8/i8 slice |
| 46 | + let ref_type = cx.typeck_results().expr_ty(recv); |
| 47 | + |
| 48 | + match ref_type.kind() { |
| 49 | + ty::Ref(_, inner_type, _) |
| 50 | + if inner_type.is_slice() |
| 51 | + && let ty::Slice(slice_type) = inner_type.kind() |
| 52 | + && (slice_type.to_string() == "u8" || slice_type.to_string() == "i8") => |
| 53 | + { |
| 54 | + span_lint( |
| 55 | + cx, |
| 56 | + CONTAINS_FOR_SLICE, |
| 57 | + expr.span, |
| 58 | + "using `contains()` instead of `iter().any()` on u8/i8 slices is more efficient", |
| 59 | + ); |
| 60 | + }, |
| 61 | + _ => {}, |
| 62 | + } |
| 63 | + } |
| 64 | + } |
| 65 | +} |
0 commit comments