Create rule S7422: Unit values should not be hashed (#4763)

* Create rule S7422

* Update RSPEC

* Update snippets

---------

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 13:07:14 +00:00 committed by GitHub
parent 66bae183f4
commit 1379adbc47
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 68 additions and 0 deletions

View File

@ -0,0 +1,2 @@
{
}

View File

@ -0,0 +1,24 @@
{
"title": "Unit values should not be hashed",
"type": "BUG",
"status": "ready",
"remediation": {
"func": "Constant\/Issue",
"constantCost": "5min"
},
"tags": [
"clippy"
],
"defaultSeverity": "Major",
"ruleSpecification": "RSPEC-7422",
"sqKey": "S7422",
"scope": "All",
"defaultQualityProfiles": ["Sonar way"],
"quickfix": "unknown",
"code": {
"impacts": {
"RELIABILITY": "HIGH"
},
"attribute": "LOGICAL"
}
}

View File

@ -0,0 +1,42 @@
== Why is this an issue?
Hashing a unit value doesn't accomplish anything because the implementation of `Hash` for `()` is a no-op. This can lead to confusion or misleading code, as it implies some hashing operation is actually taking place, when in reality it does nothing.
=== Code examples
==== Noncompliant code example
[source,rust,diff-id=1,diff-type=noncompliant]
----
enum Foo { Empty, WithValue(u8) }
use Foo::*;
let mut state = DefaultHasher::new();
let my_enum = Foo::Empty;
match my_enum {
Empty => ().hash(&mut state), // Noncompliant
WithValue(x) => x.hash(&mut state),
}
----
==== Compliant solution
[source,rust,diff-id=1,diff-type=compliant]
----
enum Foo { Empty, WithValue(u8) }
use Foo::*;
let mut state = DefaultHasher::new();
let my_enum = Foo::Empty;
match my_enum {
Empty => 0_u8.hash(&mut state), // Compliant
WithValue(x) => x.hash(&mut state),
}
----
== Resources
=== Documentation
* Clippy Lints - https://rust-lang.github.io/rust-clippy/master/index.html#unit_hash