rust-lang / rust-clippy

A bunch of lints to catch common mistakes and improve your Rust code. Book: https://doc.rust-lang.org/clippy/
https://rust-lang.github.io/rust-clippy/
Other
11.41k stars 1.54k forks source link

Suggest `String::into_bytes()` to replace `as_bytes().to_owned()` when the `String` can be consumed #13318

Open kupiakos opened 2 months ago

kupiakos commented 2 months ago

What it does

A misstep I see is taking a temporary String, like one created through format!, and calling .as_bytes() to convert it to &[u8], then to_owned or into or some other copying operation to create a new Vec<u8> with the contents of the original String.

The consuming String::into_bytes should be suggested by Clippy, since many users aren't aware that it exists. It should detect as_bytes() called on a temporary String, then any of the stdlib functions on the returned &[u8] to convert to Vec<u8> like .into(), to_owned(), and Vec::from.

An extension could identify this on a binding that is unused after the operation, such that the String being consumed does not affect the surrounding code.

Advantage

Drawbacks

Example

format!("hello {world}").as_bytes().to_owned()

Could be written as:

format!("hello {world}").into_bytes()

With the above extension to apply to more than temporaries, this:

fn foo(x: &str) -> Vec<u8> {
    let x = format!("hello {x}");
    x.as_bytes().to_owned()
}

Could be written as:

fn foo(x: &str) -> Vec<u8> {
    let x = format!("hello {x}");
    x.into_bytes()
}
Jarcho commented 2 months ago

This is an extension to reundant_clone.