43 lines
1.4 KiB
Plaintext
43 lines
1.4 KiB
Plaintext
![]() |
|
||
|
== Why is this an issue?
|
||
|
If the bits that the comparison cares about are always set to zero or one by the bit mask, the comparison is constant true or false (depending on mask, compared value, and operators). This results in dead code, potential security vulnerabilities, confusion for developers, and wasted processing time on redundant checks.
|
||
|
|
||
|
== How to fix it
|
||
|
|
||
|
Ensuring valid bitwise operations in comparisons requires:
|
||
|
|
||
|
* For `&` (AND) operations:
|
||
|
** `x & mask == value` is valid if all bits set in `value` are also set in `mask`
|
||
|
** `x & mask < value` is valid if `mask < value`
|
||
|
** `x & mask > value` is valid if `mask > value`
|
||
|
* For `|` (OR) operations:
|
||
|
** `x | mask == value` is valid if all bits set in `mask` are also set in `value`
|
||
|
|
||
|
Correct the bit mask or comparison value to create a valid logical expression that can be both true and false depending on input. This ensures the bitwise operations in the comparisons result in meaningful code execution.
|
||
|
|
||
|
=== Code examples
|
||
|
|
||
|
==== Noncompliant code example
|
||
|
[source,rust,diff-id=1,diff-type=noncompliant]
|
||
|
----
|
||
|
let x = 1;
|
||
|
if (x & 1 == 2) {
|
||
|
// This code will never execute
|
||
|
}
|
||
|
----
|
||
|
|
||
|
==== Compliant solution
|
||
|
|
||
|
[source,rust,diff-id=1,diff-type=compliant]
|
||
|
----
|
||
|
let x = 1;
|
||
|
if (x & 2 == 2) {
|
||
|
// This code will execute when the second bit of x is set
|
||
|
}
|
||
|
----
|
||
|
|
||
|
== Resources
|
||
|
=== Documentation
|
||
|
|
||
|
* Clippy Lints - https://rust-lang.github.io/rust-clippy/master/index.html#bad_bit_mask
|