Compare commits

...

2 Commits

Author SHA1 Message Date
yassin-kammoun-sonarsource
65157f31ee Update RSPEC 2025-03-27 10:16:04 +01:00
yassin-kammoun-sonarsource
4be3c6eb3a Create rule S7463 2025-03-27 09:07:48 +00:00
3 changed files with 54 additions and 0 deletions

View File

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

View File

@ -0,0 +1,24 @@
{
"title": "`saturating_sub` should be used to avoid subtraction underflow",
"type": "BUG",
"status": "ready",
"remediation": {
"func": "Constant\/Issue",
"constantCost": "5min"
},
"tags": [
"clippy"
],
"defaultSeverity": "Major",
"ruleSpecification": "RSPEC-7463",
"sqKey": "S7463",
"scope": "All",
"defaultQualityProfiles": ["Sonar way"],
"quickfix": "unknown",
"code": {
"impacts": {
"RELIABILITY": "MEDIUM"
},
"attribute": "LOGICAL"
}
}

View File

@ -0,0 +1,28 @@
== Why is this an issue?
Using conditional subtraction ``++if a > b { b - a } else { 0 }++`` can lead to an unintended underflow, which can cause bugs or unexpected behaviors. The ``++saturating_sub++`` method ensures that the subtraction does not underflow by returning zero if the result would have been negative.
=== Code examples
==== Noncompliant code example
[source,rust,diff-id=1,diff-type=noncompliant]
----
let a = 12u32;
let b = 13u32;
let result = if a > b { b - a } else { 0 }; // Noncompliant: Potential underflow condition.
----
==== Compliant solution
[source,rust,diff-id=1,diff-type=compliant]
----
let a = 12u32;
let b = 13u32;
let result = a.saturating_sub(b); // Compliant: Safe subtraction using saturating_sub.
----
== Resources
=== Documentation
* Clippy Lints - https://rust-lang.github.io/rust-clippy/master/index.html#inverted_saturating_sub