Skip to content

taking reference on String::from_utf8 result whose argument is converted from slice can be rewritten in borrowed version of function #11648

Closed
@KisaragiEffective

Description

@KisaragiEffective

What it does

&String::from_utf8(slice.to_vec()).unwrap_friend() can be core::str::from_utf8(slice).unwrap_friend() where &str is expected.

Advantage

  • Remove additional allocation
  • Reduces instruction count by 2x on release mode (godbolt)

Drawbacks

n/a

Example

fn opaque(buf: &mut [u8]) {}

let mut foo = String::new();
let slice = [0u8; 1024];
opaque(&mut slice);

let ref_str: &str = &String::from_utf8(slice.to_vec()).expect("not UTF-8");

Could be written as:

let ref_str: &str = core::str::from_utf8(slice).expect("not UTF-8");

Metadata

Metadata

Assignees

Labels

A-lintArea: New lints

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions