Create rule S4325: Redundant casts should be avoided (#4729)

* Add rust to rule S4325

* Update RSPEC

---------

Co-authored-by: yassin-kammoun-sonarsource <yassin-kammoun-sonarsource@users.noreply.github.com>
Co-authored-by: yassin-kammoun-sonarsource <yassin.kammoun@sonarsource.com>
This commit is contained in:
github-actions[bot] 2025-03-19 14:46:46 +00:00 committed by GitHub
parent c5bb992c80
commit ef35f53a80
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
4 changed files with 69 additions and 1 deletions

View File

@ -1,2 +1,35 @@
{ {
"title": "Redundant casts and non-null assertions should be avoided",
"type": "CODE_SMELL",
"code": {
"impacts": {
"MAINTAINABILITY": "LOW"
},
"attribute": "CLEAR"
},
"status": "ready",
"remediation": {
"func": "Constant\/Issue",
"constantCost": "1min"
},
"tags": [
"redundant",
"type-dependent"
],
"extra": {
"replacementRules": [
],
"legacyKeys": [
]
},
"defaultSeverity": "Minor",
"ruleSpecification": "RSPEC-4325",
"sqKey": "S4325",
"scope": "Main",
"defaultQualityProfiles": [
"Sonar way"
],
"quickfix": "covered"
} }

View File

@ -0,0 +1,7 @@
{
"title": "Redundant casts should be avoided",
"tags": [
"redundant",
"clippy"
]
}

View File

@ -0,0 +1,28 @@
== Why is this an issue?
In Rust, type casting is a mechanism used to convert a value from one type to another. This is often necessary when working with different types that are compatible but not the same. However, unnecessary casts can occur when the type conversion is redundant because the compiler already knows the type based on the context or explicit type declarations.
Unnecessary casts should be avoided in Rust code as they add unnecessary complexity, clutter the code, and can lead to confusion. They also make the code less idiomatic and harder to read.
[source,rust,diff-id=1,diff-type=noncompliant]
----
fn get_length(value: &str) -> usize {
let length = value.len() as usize; // Noncompliant: 'value.len()' already returns a 'usize'
length
}
----
Remove all unnecessary casts based on the contextual typing information, as inferred by the Rust compiler.
[source,rust,diff-id=1,diff-type=compliant]
----
fn get_length(value: &str) -> usize {
let length = value.len();
length
}
----
== Resources
=== Documentation
* Clippy Lints - https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_cast