Create rule S7431: size_of::<T> should not be used to count elements of type T (#4772)

* Create rule S7431

* 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:06:51 +00:00 committed by GitHub
parent 6edd31ee99
commit fd50acb2e3
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 56 additions and 0 deletions

View File

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

View File

@ -0,0 +1,24 @@
{
"title": "`size_of::<T>` should not be used to count elements of type `T`",
"type": "BUG",
"status": "ready",
"remediation": {
"func": "Constant\/Issue",
"constantCost": "5min"
},
"tags": [
"clippy"
],
"defaultSeverity": "Major",
"ruleSpecification": "RSPEC-7431",
"sqKey": "S7431",
"scope": "All",
"defaultQualityProfiles": ["Sonar way"],
"quickfix": "unknown",
"code": {
"impacts": {
"RELIABILITY": "MEDIUM"
},
"attribute": "LOGICAL"
}
}

View File

@ -0,0 +1,30 @@
== Why is this an issue?
Using `size_of::<T>` or `size_of_val::<T>` as a count of elements is misleading because these functions are meant to return the size in bytes, not the count of elements. This can lead to logical errors in the code.
=== Code examples
==== Noncompliant code example
[source,rust,diff-id=1,diff-type=noncompliant]
----
const SIZE: usize = 128;
let x = [2u8; SIZE];
let mut y = [2u8; SIZE];
unsafe { std::ptr::copy_nonoverlapping(x.as_ptr(), y.as_mut_ptr(), std::mem::size_of::<u8>() * SIZE) }; // Noncompliant: uses size_of::<u8>() to determine element count.
----
==== Compliant solution
[source,rust,diff-id=1,diff-type=compliant]
----
const SIZE: usize = 128;
let x = [2u8; SIZE];
let mut y = [2u8; SIZE];
unsafe { std::ptr::copy_nonoverlapping(x.as_ptr(), y.as_mut_ptr(), SIZE) }; // Compliant: uses the actual element count.
----
== Resources
=== Documentation
* Clippy Lints - https://rust-lang.github.io/rust-clippy/master/index.html#size_of_in_element_count