From 00d540f5edd8f91852a4eaae0a3b2ed3dd7e71f0 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Wed, 19 Mar 2025 14:10:07 +0000 Subject: [PATCH] Create rule S7437 Variables should be swapped using `std::mem::swap` (#4780) * Create rule S7437 * Update rule.adoc * Update metadata.json * Update metadata.json * Update metadata.json * Update metadata.json * Update metadata.json --------- Co-authored-by: sallaigy Co-authored-by: Gyula Sallai --- rules/S7437/metadata.json | 2 ++ rules/S7437/rust/metadata.json | 24 ++++++++++++++++++++++++ rules/S7437/rust/rule.adoc | 29 +++++++++++++++++++++++++++++ 3 files changed, 55 insertions(+) create mode 100644 rules/S7437/metadata.json create mode 100644 rules/S7437/rust/metadata.json create mode 100644 rules/S7437/rust/rule.adoc diff --git a/rules/S7437/metadata.json b/rules/S7437/metadata.json new file mode 100644 index 0000000000..2c63c08510 --- /dev/null +++ b/rules/S7437/metadata.json @@ -0,0 +1,2 @@ +{ +} diff --git a/rules/S7437/rust/metadata.json b/rules/S7437/rust/metadata.json new file mode 100644 index 0000000000..09afb3989b --- /dev/null +++ b/rules/S7437/rust/metadata.json @@ -0,0 +1,24 @@ +{ + "title": "Variables should be swapped using `std::mem::swap`", + "type": "BUG", + "status": "ready", + "remediation": { + "func": "Constant\/Issue", + "constantCost": "5min" + }, + "tags": [ + "clippy" + ], + "defaultSeverity": "Blocker", + "ruleSpecification": "RSPEC-7437", + "sqKey": "S7437", + "scope": "All", + "defaultQualityProfiles": ["Sonar way"], + "quickfix": "unknown", + "code": { + "impacts": { + "RELIABILITY": "HIGH" + }, + "attribute": "LOGICAL" + } +} diff --git a/rules/S7437/rust/rule.adoc b/rules/S7437/rust/rule.adoc new file mode 100644 index 0000000000..f2b99c3561 --- /dev/null +++ b/rules/S7437/rust/rule.adoc @@ -0,0 +1,29 @@ + +== Why is this an issue? +The sequence `foo = bar; bar = foo` looks like a failed attempt to swap the values of two variables. This code mistakenly reassigns both variables, leading to incorrect and unintended behavior. Using `std::mem::swap` ensures a correct and intended swap. + + +=== Code examples + +==== Noncompliant code example +[source,rust,diff-id=1,diff-type=noncompliant] +---- +let mut foo = 1; +let mut bar = 2; +foo = bar; // Noncompliant +bar = foo; // Noncompliant +---- + +==== Compliant solution + +[source,rust,diff-id=1,diff-type=compliant] +---- +let mut foo = 1; +let mut bar = 2; +std::mem::swap(&mut foo, &mut bar); // Compliant +---- + +== Resources +=== Documentation + +* Clippy Lints - https://rust-lang.github.io/rust-clippy/master/index.html#almost_swapped