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
Removes an unnecessary heap allocation and copy.
Informs users of this helpful stdlib function.
Drawbacks
None. This will only be invoked for temporaries or bindings that would be able to consume the value anyways.
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()
}
What it does
A misstep I see is taking a temporary
String
, like one created throughformat!
, and calling.as_bytes()
to convert it to&[u8]
, thento_owned
orinto
or some other copying operation to create a newVec<u8>
with the contents of the originalString
.The consuming
String::into_bytes
should be suggested by Clippy, since many users aren't aware that it exists. It should detectas_bytes()
called on a temporaryString
, then any of the stdlib functions on the returned&[u8]
to convert toVec<u8>
like.into()
,to_owned()
, andVec::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
Could be written as:
With the above extension to apply to more than temporaries, this:
Could be written as: