Skip to content

Commit

Permalink
add test case for not whole length, move sugg into variable
Browse files Browse the repository at this point in the history
  • Loading branch information
y21 committed Jun 15, 2023
1 parent 20ae597 commit 5821fbb
Show file tree
Hide file tree
Showing 4 changed files with 16 additions and 6 deletions.
12 changes: 7 additions & 5 deletions clippy_lints/src/methods/drain_collect.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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, "<expr>");
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,
);
}
Expand Down
2 changes: 1 addition & 1 deletion clippy_lints/src/methods/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
Expand Down
4 changes: 4 additions & 0 deletions tests/ui/drain_collect.fixed
Original file line number Diff line number Diff line change
Expand Up @@ -70,4 +70,8 @@ fn string_dont_lint(b: &mut String) -> HashSet<char> {
b.drain(..).collect()
}

fn not_whole_length(v: &mut Vec<i32>) -> Vec<i32> {
v.drain(1..).collect()
}

fn main() {}
4 changes: 4 additions & 0 deletions tests/ui/drain_collect.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,4 +70,8 @@ fn string_dont_lint(b: &mut String) -> HashSet<char> {
b.drain(..).collect()
}

fn not_whole_length(v: &mut Vec<i32>) -> Vec<i32> {
v.drain(1..).collect()
}

fn main() {}

0 comments on commit 5821fbb

Please sign in to comment.