rust-lang / rust-lang/rust-clippy
Complexity lint against `some_string[0..some_len].len()`
Nobody has claimed this yet.
- Dominant language
- Rust
- Stars
- 13.5k
- Forks
- 2.2k
- Avg merge
- 2d 10h
- Merged PRs (30d)
- 32
Description
What it does
I apologize if this comes across as confusing - I'm not entirely sure how to word it.
This lint would look for instances where the user is getting a slice of a string, with the starting point of the range being 0, and then calling len() on that slice.
The reason I believe this works is because impl SliceIndex<str> for Range<usize> states the following:
Returns a slice of the given string from the byte range [
begin,end).
This means that, if you're getting a string slice from 0 to some_var, some_var will already need to be a length in bytes. Thus, some_string[0..some_calculated_len] will always be some_calculated_len bytes long. And thus, some_string[0..some_calculated_len].len() will always be the same as just some_calculated_len.
Advantage
Less complex-looking code, while still functioning the same.
Drawbacks
None that I'm aware of - the code should function exactly the same afterwards.
Example
let len_in_bytes = some_string[0..the_len_we_want].len();
Could be written as:
let len_in_bytes = the_len_we_want;
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by reading the linked Rust SliceIndex for Range documentation and inspecting how Clippy represents complexity lints. Done means the proposed pattern is recognized safely and covered by appropriate lint tests, with the issue's example producing the simpler equivalent.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- rust
- Domain
- tooling
- Issue type
- Feature
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100