mirror of
https://github.com/rust-lang/rust-clippy
synced 2024-11-23 21:23:56 +00:00
Suggest from_utf8_unchecked in const contexts
This commit is contained in:
parent
db5739ac55
commit
7a80c23f83
3 changed files with 23 additions and 12 deletions
|
@ -32,17 +32,19 @@ pub(super) fn check<'tcx>(
|
|||
""
|
||||
};
|
||||
|
||||
let snippet = snippet(cx, arg.span, "..");
|
||||
|
||||
span_lint_and_sugg(
|
||||
cx,
|
||||
TRANSMUTE_BYTES_TO_STR,
|
||||
e.span,
|
||||
&format!("transmute from a `{}` to a `{}`", from_ty, to_ty),
|
||||
"consider using",
|
||||
format!(
|
||||
"std::str::from_utf8{}({}).unwrap()",
|
||||
postfix,
|
||||
snippet(cx, arg.span, ".."),
|
||||
),
|
||||
if const_context {
|
||||
format!("unsafe {{ std::str::from_utf8_unchecked{postfix}({snippet}) }}")
|
||||
} else {
|
||||
format!("std::str::from_utf8{postfix}({snippet}).unwrap()")
|
||||
},
|
||||
Applicability::Unspecified,
|
||||
);
|
||||
triggered = true;
|
||||
|
|
|
@ -134,9 +134,12 @@ mod num_to_bytes {
|
|||
}
|
||||
}
|
||||
|
||||
fn bytes_to_str(b: &[u8], mb: &mut [u8]) {
|
||||
let _: &str = unsafe { std::mem::transmute(b) };
|
||||
fn bytes_to_str(mb: &mut [u8]) {
|
||||
const B: &[u8] = b"";
|
||||
|
||||
let _: &str = unsafe { std::mem::transmute(B) };
|
||||
let _: &mut str = unsafe { std::mem::transmute(mb) };
|
||||
const _: &str = unsafe { std::mem::transmute(B) };
|
||||
}
|
||||
|
||||
fn main() {}
|
||||
|
|
|
@ -227,18 +227,24 @@ LL | let _: [u8; 16] = std::mem::transmute(0i128);
|
|||
| ^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider using `to_ne_bytes()`: `0i128.to_ne_bytes()`
|
||||
|
||||
error: transmute from a `&[u8]` to a `&str`
|
||||
--> $DIR/transmute.rs:138:28
|
||||
--> $DIR/transmute.rs:140:28
|
||||
|
|
||||
LL | let _: &str = unsafe { std::mem::transmute(b) };
|
||||
| ^^^^^^^^^^^^^^^^^^^^^^ help: consider using: `std::str::from_utf8(b).unwrap()`
|
||||
LL | let _: &str = unsafe { std::mem::transmute(B) };
|
||||
| ^^^^^^^^^^^^^^^^^^^^^^ help: consider using: `std::str::from_utf8(B).unwrap()`
|
||||
|
|
||||
= note: `-D clippy::transmute-bytes-to-str` implied by `-D warnings`
|
||||
|
||||
error: transmute from a `&mut [u8]` to a `&mut str`
|
||||
--> $DIR/transmute.rs:139:32
|
||||
--> $DIR/transmute.rs:141:32
|
||||
|
|
||||
LL | let _: &mut str = unsafe { std::mem::transmute(mb) };
|
||||
| ^^^^^^^^^^^^^^^^^^^^^^^ help: consider using: `std::str::from_utf8_mut(mb).unwrap()`
|
||||
|
||||
error: aborting due to 38 previous errors
|
||||
error: transmute from a `&[u8]` to a `&str`
|
||||
--> $DIR/transmute.rs:142:30
|
||||
|
|
||||
LL | const _: &str = unsafe { std::mem::transmute(B) };
|
||||
| ^^^^^^^^^^^^^^^^^^^^^^ help: consider using: `unsafe { std::str::from_utf8_unchecked(B) }`
|
||||
|
||||
error: aborting due to 39 previous errors
|
||||
|
||||
|
|
Loading…
Reference in a new issue