1 use clippy_utils::diagnostics::span_lint_and_sugg;
2 use clippy_utils::source::snippet_with_applicability;
3 use clippy_utils::ty::match_type;
4 use clippy_utils::visitors::LocalUsedVisitor;
5 use clippy_utils::{path_to_local_id, paths, peel_ref_operators, remove_blocks, strip_pat_refs};
6 use if_chain::if_chain;
7 use rustc_errors::Applicability;
8 use rustc_hir::{BinOpKind, Expr, ExprKind, PatKind};
9 use rustc_lint::{LateContext, LateLintPass};
10 use rustc_middle::ty::{self, UintTy};
11 use rustc_session::{declare_lint_pass, declare_tool_lint};
14 declare_clippy_lint! {
15 /// **What it does:** Checks for naive byte counts
17 /// **Why is this bad?** The [`bytecount`](https://crates.io/crates/bytecount)
18 /// crate has methods to count your bytes faster, especially for large slices.
20 /// **Known problems:** If you have predominantly small slices, the
21 /// `bytecount::count(..)` method may actually be slower. However, if you can
22 /// ensure that less than 2³²-1 matches arise, the `naive_count_32(..)` can be
23 /// faster in those cases.
28 /// # let vec = vec![1_u8];
29 /// &vec.iter().filter(|x| **x == 0u8).count(); // use bytecount::count instead
33 "use of naive `<slice>.filter(|&x| x == y).count()` to count byte values"
36 declare_lint_pass!(ByteCount => [NAIVE_BYTECOUNT]);
38 impl<'tcx> LateLintPass<'tcx> for ByteCount {
39 fn check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) {
41 if let ExprKind::MethodCall(count, _, [count_recv], _) = expr.kind;
42 if count.ident.name == sym!(count);
43 if let ExprKind::MethodCall(filter, _, [filter_recv, filter_arg], _) = count_recv.kind;
44 if filter.ident.name == sym!(filter);
45 if let ExprKind::Closure(_, _, body_id, _, _) = filter_arg.kind;
46 let body = cx.tcx.hir().body(body_id);
47 if let [param] = body.params;
48 if let PatKind::Binding(_, arg_id, _, _) = strip_pat_refs(param.pat).kind;
49 if let ExprKind::Binary(ref op, l, r) = body.value.kind;
50 if op.node == BinOpKind::Eq;
52 cx.typeck_results().expr_ty(filter_recv).peel_refs(),
54 let operand_is_arg = |expr| {
55 let expr = peel_ref_operators(cx, remove_blocks(expr));
56 path_to_local_id(expr, arg_id)
58 let needle = if operand_is_arg(l) {
60 } else if operand_is_arg(r) {
65 if ty::Uint(UintTy::U8) == *cx.typeck_results().expr_ty(needle).peel_refs().kind();
66 if !LocalUsedVisitor::new(cx, arg_id).check_expr(needle);
68 let haystack = if let ExprKind::MethodCall(path, _, args, _) =
70 let p = path.ident.name;
71 if (p == sym::iter || p == sym!(iter_mut)) && args.len() == 1 {
79 let mut applicability = Applicability::MaybeIncorrect;
84 "you appear to be counting bytes the naive way",
85 "consider using the bytecount crate",
86 format!("bytecount::count({}, {})",
87 snippet_with_applicability(cx, haystack.span, "..", &mut applicability),
88 snippet_with_applicability(cx, needle.span, "..", &mut applicability)),