fix: string_from_utf8_as_bytes wrongly unmangled macros

This commit is contained in:
Linshu Yang
2026-01-02 05:20:23 +00:00
parent ac505cc2cb
commit 15fc6cfd1c
4 changed files with 30 additions and 3 deletions
+2 -1
View File
@@ -273,6 +273,7 @@ fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) {
let string_expression = &expressions[0].0;
let snippet_app = snippet_with_applicability(cx, string_expression.span, "..", &mut applicability);
let (right_snip, _) = snippet_with_context(cx, right.span, e.span.ctxt(), "..", &mut applicability);
span_lint_and_sugg(
cx,
@@ -280,7 +281,7 @@ fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) {
e.span,
"calling a slice of `as_bytes()` with `from_utf8` should be not necessary",
"try",
format!("Some(&{snippet_app}[{}])", snippet(cx, right.span, "..")),
format!("Some(&{snippet_app}[{right_snip}])"),
applicability,
);
}
+10
View File
@@ -1,6 +1,16 @@
#![warn(clippy::string_from_utf8_as_bytes)]
macro_rules! test_range {
($start:expr, $end:expr) => {
$start..$end
};
}
fn main() {
let _ = Some(&"Hello World!"[6..11]);
//~^ string_from_utf8_as_bytes
let s = "Hello World!";
let _ = Some(&s[test_range!(6, 11)]);
//~^ string_from_utf8_as_bytes
}
+10
View File
@@ -1,6 +1,16 @@
#![warn(clippy::string_from_utf8_as_bytes)]
macro_rules! test_range {
($start:expr, $end:expr) => {
$start..$end
};
}
fn main() {
let _ = std::str::from_utf8(&"Hello World!".as_bytes()[6..11]);
//~^ string_from_utf8_as_bytes
let s = "Hello World!";
let _ = std::str::from_utf8(&s.as_bytes()[test_range!(6, 11)]);
//~^ string_from_utf8_as_bytes
}
+8 -2
View File
@@ -1,5 +1,5 @@
error: calling a slice of `as_bytes()` with `from_utf8` should be not necessary
--> tests/ui/string_from_utf8_as_bytes.rs:4:13
--> tests/ui/string_from_utf8_as_bytes.rs:10:13
|
LL | let _ = std::str::from_utf8(&"Hello World!".as_bytes()[6..11]);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `Some(&"Hello World!"[6..11])`
@@ -7,5 +7,11 @@ LL | let _ = std::str::from_utf8(&"Hello World!".as_bytes()[6..11]);
= note: `-D clippy::string-from-utf8-as-bytes` implied by `-D warnings`
= help: to override `-D warnings` add `#[allow(clippy::string_from_utf8_as_bytes)]`
error: aborting due to 1 previous error
error: calling a slice of `as_bytes()` with `from_utf8` should be not necessary
--> tests/ui/string_from_utf8_as_bytes.rs:14:13
|
LL | let _ = std::str::from_utf8(&s.as_bytes()[test_range!(6, 11)]);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `Some(&s[test_range!(6, 11)])`
error: aborting due to 2 previous errors