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:
parent
6edd31ee99
commit
fd50acb2e3
2
rules/S7431/metadata.json
Normal file
2
rules/S7431/metadata.json
Normal file
@ -0,0 +1,2 @@
|
||||
{
|
||||
}
|
24
rules/S7431/rust/metadata.json
Normal file
24
rules/S7431/rust/metadata.json
Normal 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"
|
||||
}
|
||||
}
|
30
rules/S7431/rust/rule.adoc
Normal file
30
rules/S7431/rust/rule.adoc
Normal 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
|
Loading…
x
Reference in New Issue
Block a user