Bit operation with an identity operand leaves the value unchanged
ID |
rust.maintainability.unnecessary_bit_operations_performed |
Severity |
info |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Redundant Code |
Language |
Rust |
Description
Detects a bitwise operation whose operand is the identity for that operator - OR or XOR with 0, AND with -1, and a shift by 0 - so the expression yields its input unchanged.
Rationale
An operation that cannot change its input is either left-over scaffolding or a sign that the intended constant was never filled in. Both readings are worth resolving: the first is clutter a reader has to reason about, and the second is a mask or a shift amount that is silently wrong, so the flag it was meant to apply is never applied.
The following code illustrates the pattern detected by this rule:
pub fn combine(flags: u32, extra: u32) -> u32 {
// FLAGGED: Bit operation with an identity operand leaves the value unchanged
let a = flags | 0;
// FLAGGED: Bit operation with an identity operand leaves the value unchanged
let b = flags ^ 0;
// FLAGGED: Bit operation with an identity operand leaves the value unchanged
let c = flags & -1;
// FLAGGED: Bit operation with an identity operand leaves the value unchanged
let d = flags << 0;
// FLAGGED: Bit operation with an identity operand leaves the value unchanged
let e = flags >> 0;
// FLAGGED: Bit operation with an identity operand leaves the value unchanged
let f = 0 | extra;
// FLAGGED: Bit operation with an identity operand leaves the value unchanged
let g = 0 ^ extra;
a | b | c | d | e | f | g
}