From 5821fbbc3072c16bc941a5e207bfd3a5e401304b Mon Sep 17 00:00:00 2001 From: y21 <30553356+y21@users.noreply.github.com> Date: Thu, 15 Jun 2023 14:16:39 +0200 Subject: [PATCH] add test case for not whole length, move sugg into variable --- clippy_lints/src/methods/drain_collect.rs | 12 +++++++----- clippy_lints/src/methods/mod.rs | 2 +- tests/ui/drain_collect.fixed | 4 ++++ tests/ui/drain_collect.rs | 4 ++++ 4 files changed, 16 insertions(+), 6 deletions(-) diff --git a/clippy_lints/src/methods/drain_collect.rs b/clippy_lints/src/methods/drain_collect.rs index 8bd8f88a2..d0c79dc11 100644 --- a/clippy_lints/src/methods/drain_collect.rs +++ b/clippy_lints/src/methods/drain_collect.rs @@ -66,17 +66,19 @@ pub(super) fn check(cx: &LateContext<'_>, args: &[Expr<'_>], expr: &Expr<'_>, re .or_else(|| check_collections(cx, expr_ty, recv_ty_no_refs)) { let recv = snippet(cx, recv.span, ""); + let sugg = if let ty::Ref(..) = recv_ty.kind() { + format!("std::mem::take({recv})") + } else { + format!("std::mem::take(&mut {recv})") + }; + span_lint_and_sugg( cx, DRAIN_COLLECT, expr.span, &format!("you seem to be trying to move all elements into a new `{typename}`"), "consider using `mem::take`", - if let ty::Ref(..) = recv_ty.kind() { - format!("std::mem::take({recv})") - } else { - format!("std::mem::take(&mut {recv})") - }, + sugg, Applicability::MachineApplicable, ); } diff --git a/clippy_lints/src/methods/mod.rs b/clippy_lints/src/methods/mod.rs index bed70207f..99c984ba6 100644 --- a/clippy_lints/src/methods/mod.rs +++ b/clippy_lints/src/methods/mod.rs @@ -3260,7 +3260,7 @@ declare_clippy_lint! { /// When using `mem::take`, the old collection is replaced with an empty one and ownership of /// the old collection is returned. /// - /// ### Drawback + /// ### Known issues /// `mem::take(&mut vec)` is almost equivalent to `vec.drain(..).collect()`, except that /// it also moves the **capacity**. The user might have explicitly written it this way /// to keep the capacity on the original `Vec`. diff --git a/tests/ui/drain_collect.fixed b/tests/ui/drain_collect.fixed index 0d40a6483..11001bd31 100644 --- a/tests/ui/drain_collect.fixed +++ b/tests/ui/drain_collect.fixed @@ -70,4 +70,8 @@ fn string_dont_lint(b: &mut String) -> HashSet { b.drain(..).collect() } +fn not_whole_length(v: &mut Vec) -> Vec { + v.drain(1..).collect() +} + fn main() {} diff --git a/tests/ui/drain_collect.rs b/tests/ui/drain_collect.rs index 7144a1847..373a3ca35 100644 --- a/tests/ui/drain_collect.rs +++ b/tests/ui/drain_collect.rs @@ -70,4 +70,8 @@ fn string_dont_lint(b: &mut String) -> HashSet { b.drain(..).collect() } +fn not_whole_length(v: &mut Vec) -> Vec { + v.drain(1..).collect() +} + fn main() {}