]> git.lizzy.rs Git - rust.git/blob - src/docs/bad_bit_mask.txt
Auto merge of #9421 - xphoniex:fix-#9420, r=giraffate
[rust.git] / src / docs / bad_bit_mask.txt
1 ### What it does
2 Checks for incompatible bit masks in comparisons.
3
4 The formula for detecting if an expression of the type `_ <bit_op> m
5 <cmp_op> c` (where `<bit_op>` is one of {`&`, `|`} and `<cmp_op>` is one of
6 {`!=`, `>=`, `>`, `!=`, `>=`, `>`}) can be determined from the following
7 table:
8
9 |Comparison  |Bit Op|Example      |is always|Formula               |
10 |------------|------|-------------|---------|----------------------|
11 |`==` or `!=`| `&`  |`x & 2 == 3` |`false`  |`c & m != c`          |
12 |`<`  or `>=`| `&`  |`x & 2 < 3`  |`true`   |`m < c`               |
13 |`>`  or `<=`| `&`  |`x & 1 > 1`  |`false`  |`m <= c`              |
14 |`==` or `!=`| `\|` |`x \| 1 == 0`|`false`  |`c \| m != c`         |
15 |`<`  or `>=`| `\|` |`x \| 1 < 1` |`false`  |`m >= c`              |
16 |`<=` or `>` | `\|` |`x \| 1 > 0` |`true`   |`m > c`               |
17
18 ### Why is this bad?
19 If the bits that the comparison cares about are always
20 set to zero or one by the bit mask, the comparison is constant `true` or
21 `false` (depending on mask, compared value, and operators).
22
23 So the code is actively misleading, and the only reason someone would write
24 this intentionally is to win an underhanded Rust contest or create a
25 test-case for this lint.
26
27 ### Example
28 ```
29 if (x & 1 == 2) { }
30 ```