Create rule S7441: Lines read from the standard input should be trimmed (#4784)

* Create rule S7441

* Update RSPEC

---------

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:36 +00:00 committed by GitHub
parent 32d452498a
commit 314d4b0ed2
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 54 additions and 0 deletions

View File

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

View File

@ -0,0 +1,24 @@
{
"title": "Lines read from the standard input should be trimmed",
"type": "BUG",
"status": "ready",
"remediation": {
"func": "Constant\/Issue",
"constantCost": "5min"
},
"tags": [
"clippy"
],
"defaultSeverity": "Major",
"ruleSpecification": "RSPEC-7441",
"sqKey": "S7441",
"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 `Stdin::read_line` without trimming the newline character can cause runtime issues, especially when parsing the input into another type (e.g., `i32`). The operation will fail if the string contains a trailing newline character, making the code unreliable.
=== Code examples
==== Noncompliant code example
[source,rust,diff-id=1,diff-type=noncompliant]
----
let mut input = String::new();
std::io::stdin().read_line(&mut input).expect("Failed to read a line");
let num: i32 = input.parse().expect("Not a number!"); // Noncompliant: The input string may contain a newline character.
----
==== Compliant solution
[source,rust,diff-id=1,diff-type=compliant]
----
let mut input = String::new();
std::io::stdin().read_line(&mut input).expect("Failed to read a line");
let num: i32 = input.trim_end().parse().expect("Not a number!"); // Compliant: Trims the trailing newline character.
----
== Resources
=== Documentation
* Clippy Lints - https://rust-lang.github.io/rust-clippy/master/index.html#read_line_without_trim