Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
KisaragiEffective opened this issue Oct 9, 2023 · 1 comment · Fixed by #11656
Assignees
Labels
A-lint Area: New lints

Comments

@KisaragiEffective
Copy link
Contributor

KisaragiEffective commented Oct 9, 2023

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");
@KisaragiEffective KisaragiEffective added the A-lint Area: New lints label Oct 9, 2023
@KisaragiEffective KisaragiEffective changed the title taking reference on String::from_utf8 result whose argument is converted from slice taking reference on String::from_utf8 result whose argument is converted from slice can be rewritten in borrowed version of function Oct 9, 2023
@y21
Copy link
Member

y21 commented Oct 9, 2023

@rustbot claim

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
A-lint Area: New lints
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants