Skip to content

Lint for using the same expression for both length and capacity when constructing a vec/string #5955

@sgrif

Description

@sgrif

What it does

This lint checks for calls to String::from_raw_parts and Vec::from_raw_parts, and triggers when the same expression is used for both the length and capacity. If folks are interested in a pull request for this lint, I am happy to do the work.

Categories (optional)

  • Kind: pedantic

What is the advantage of the recommended code over the original code

When code is written this way, the author likely intended to use a borrowed type instead. The idea for this lint came after noticing a friend of mine consistently reaching for String and not &str, which requires inventing a capacity. The author will likely use the length in that case. Unless the string/vec was created using with_capacity or had shrink_to_fit called on it, it's unlikely that the length and capacity are the same.

Drawbacks

This is trying to catch a beginner mistake, and can potentially trigger on valid code. It's unclear how common this mistake actually is

Example

Vec::from_raw_parts(ptr, len, len)

Could be written as:

slice::from_raw_parts(ptr, len)
// or
Vec::from_raw_parts(ptr, len, cap)

Metadata

Metadata

Assignees

Labels

A-lintArea: New lintsgood first issueThese issues are a good way to get started with Clippy

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions