Skip to content
This repository was archived by the owner on May 28, 2025. It is now read-only.

Commit d99eae4

Browse files
committed
correct suggestion for drain_collect in a no_std environment
1 parent cb0a479 commit d99eae4

File tree

4 files changed

+31
-3
lines changed

4 files changed

+31
-3
lines changed

clippy_lints/src/methods/drain_collect.rs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
use crate::methods::DRAIN_COLLECT;
22
use clippy_utils::diagnostics::span_lint_and_sugg;
3-
use clippy_utils::is_range_full;
43
use clippy_utils::source::snippet;
54
use clippy_utils::ty::is_type_lang_item;
5+
use clippy_utils::{is_range_full, std_or_core};
66
use rustc_errors::Applicability;
77
use rustc_hir::{Expr, ExprKind, LangItem, Path, QPath};
88
use rustc_lint::LateContext;
@@ -58,12 +58,13 @@ pub(super) fn check(cx: &LateContext<'_>, args: &[Expr<'_>], expr: &Expr<'_>, re
5858
.then_some("Vec")
5959
.or_else(|| check_string(cx, args, expr_ty, recv_ty_no_refs, recv_path).then_some("String"))
6060
.or_else(|| check_collections(cx, expr_ty, recv_ty_no_refs))
61+
&& let Some(exec_context) = std_or_core(cx)
6162
{
6263
let recv = snippet(cx, recv.span, "<expr>");
6364
let sugg = if let ty::Ref(..) = recv_ty.kind() {
64-
format!("std::mem::take({recv})")
65+
format!("{exec_context}::mem::take({recv})")
6566
} else {
66-
format!("std::mem::take(&mut {recv})")
67+
format!("{exec_context}::mem::take(&mut {recv})")
6768
};
6869

6970
span_lint_and_sugg(

tests/ui/drain_collect_nostd.fixed

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
#![warn(clippy::drain_collect)]
2+
#![no_std]
3+
extern crate alloc;
4+
use alloc::vec::Vec;
5+
6+
fn remove_all(v: &mut Vec<i32>) -> Vec<i32> {
7+
core::mem::take(v)
8+
}

tests/ui/drain_collect_nostd.rs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
#![warn(clippy::drain_collect)]
2+
#![no_std]
3+
extern crate alloc;
4+
use alloc::vec::Vec;
5+
6+
fn remove_all(v: &mut Vec<i32>) -> Vec<i32> {
7+
v.drain(..).collect()
8+
}

tests/ui/drain_collect_nostd.stderr

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
error: you seem to be trying to move all elements into a new `Vec`
2+
--> tests/ui/drain_collect_nostd.rs:7:5
3+
|
4+
LL | v.drain(..).collect()
5+
| ^^^^^^^^^^^^^^^^^^^^^ help: consider using `mem::take`: `core::mem::take(v)`
6+
|
7+
= note: `-D clippy::drain-collect` implied by `-D warnings`
8+
= help: to override `-D warnings` add `#[allow(clippy::drain_collect)]`
9+
10+
error: aborting due to 1 previous error
11+

0 commit comments

Comments
 (0)