Integer remainder by 1 or -1 is always zero
ID |
rust.correctness.remainder_operations_avoided |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Suspicious Construct |
Language |
Rust |
Description
Detects the integer remainder operators % and %= applied to a literal 1 or -1, including suffixed spellings such as 1_i32. Float operands are not reported, since x % 1.0 genuinely extracts a fractional part.
Rationale
Every integer divides exactly by 1 and by -1, so the result is always zero and the surrounding expression is a constant. The divisor is usually a placeholder that was never replaced, or a variable that should have been used in its place.
The following code illustrates the pattern detected by this rule:
pub fn bucket(id: i32, shard: i32) -> i32 {
// FLAGGED: Integer remainder by 1 or -1 is always zero
let a = id % 1;
// FLAGGED: Integer remainder by 1 or -1 is always zero
let b = id % -1;
// FLAGGED: Integer remainder by 1 or -1 is always zero
let c = id % 1_i32;
a + b + c + id % shard
}