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::is_local_used;
5 use clippy_utils::{path_to_local_id, paths, peel_blocks, peel_ref_operators, 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! {
16 /// Checks for naive byte counts
18 /// ### Why is this bad?
19 /// The [`bytecount`](https://crates.io/crates/bytecount)
20 /// crate has methods to count your bytes faster, especially for large slices.
22 /// ### Known problems
23 /// If you have predominantly small slices, the
24 /// `bytecount::count(..)` method may actually be slower. However, if you can
25 /// ensure that less than 2³²-1 matches arise, the `naive_count_32(..)` can be
26 /// faster in those cases.
30 /// # let vec = vec![1_u8];
31 /// &vec.iter().filter(|x| **x == 0u8).count(); // use bytecount::count instead
33 #[clippy::version = "pre 1.29.0"]
36 "use of naive `<slice>.filter(|&x| x == y).count()` to count byte values"
39 declare_lint_pass!(ByteCount => [NAIVE_BYTECOUNT]);
41 impl<'tcx> LateLintPass<'tcx> for ByteCount {
42 fn check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) {
44 if let ExprKind::MethodCall(count, _, [count_recv], _) = expr.kind;
45 if count.ident.name == sym::count;
46 if let ExprKind::MethodCall(filter, _, [filter_recv, filter_arg], _) = count_recv.kind;
47 if filter.ident.name == sym!(filter);
48 if let ExprKind::Closure(_, _, body_id, _, _) = filter_arg.kind;
49 let body = cx.tcx.hir().body(body_id);
50 if let [param] = body.params;
51 if let PatKind::Binding(_, arg_id, _, _) = strip_pat_refs(param.pat).kind;
52 if let ExprKind::Binary(ref op, l, r) = body.value.kind;
53 if op.node == BinOpKind::Eq;
55 cx.typeck_results().expr_ty(filter_recv).peel_refs(),
57 let operand_is_arg = |expr| {
58 let expr = peel_ref_operators(cx, peel_blocks(expr));
59 path_to_local_id(expr, arg_id)
61 let needle = if operand_is_arg(l) {
63 } else if operand_is_arg(r) {
68 if ty::Uint(UintTy::U8) == *cx.typeck_results().expr_ty(needle).peel_refs().kind();
69 if !is_local_used(cx, needle, arg_id);
71 let haystack = if let ExprKind::MethodCall(path, _, args, _) =
73 let p = path.ident.name;
74 if (p == sym::iter || p == sym!(iter_mut)) && args.len() == 1 {
82 let mut applicability = Applicability::MaybeIncorrect;
87 "you appear to be counting bytes the naive way",
88 "consider using the bytecount crate",
89 format!("bytecount::count({}, {})",
90 snippet_with_applicability(cx, haystack.span, "..", &mut applicability),
91 snippet_with_applicability(cx, needle.span, "..", &mut applicability)),