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

Complexity lint against some_string.as_bytes().len() #13434

Open
LikeLakers2 opened this issue Sep 21, 2024 · 1 comment · May be fixed by #13437
Open

Complexity lint against some_string.as_bytes().len() #13434

LikeLakers2 opened this issue Sep 21, 2024 · 1 comment · May be fixed by #13437
Assignees
Labels
A-lint Area: New lints

Comments

@LikeLakers2
Copy link

LikeLakers2 commented Sep 21, 2024

What it does

This lint would recommend changing instances of some_string.as_bytes().len() to some_string.len().

Explanation: When getting the length of a string, str::len() already returns the length in bytes. Converting a string to &[u8] using str::as_bytes(), and then getting the length of that, introduces unnecessary complexity where none is needed.

Advantage

Less complex-looking code, while still functioning the same.

Drawbacks

Applying this lint may make it less obvious that the length will be in bytes - because our intuition for getting a string's length is that it will be the number of characters. Yes, the rust documentation addresses this, but it's still quite easy to forget - especially for us english speakers, who probably only expect to deal with ASCII (which is only ever one byte in length).

Example

let string_len_in_bytes = some_string.as_bytes().len();

Could be written as:

let string_len_in_bytes = some_string.len();
@LikeLakers2 LikeLakers2 added the A-lint Area: New lints label Sep 21, 2024
@samueltardieu samueltardieu linked a pull request Sep 21, 2024 that will close this issue
@samueltardieu
Copy link
Contributor

@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