A hash code taken modulo a size is used as an index, which is negative for negative hash codes
What it finds
GetHashCode() returns negative values as often as positive ones, and the remainder of a negative value is negative, so buckets[key.GetHashCode() % buckets.Length] throws IndexOutOfRangeException for about half of all keys. Clearing the sign bit first, or an unsigned remainder, keeps the index in range.
From the rule's source, negative_hash_index.rs.
class Table{ object[] buckets = new object[16]; object Find(object key) => buckets[key.GetHashCode() % buckets.Length];tx0 reports: a hash code can be negative, and so can this index object Safe(object key) => buckets[(key.GetHashCode() & int.MaxValue) % buckets.Length];} Turn it on, off or suppress it
The rule runs from the recommended tier up. To turn it on in a lower tier, give it a level in tx0.toml:
[rules]
"tx0/csharp:negative-hash-index" = "warning"To keep one finding, suppress it with a reason. tx0 suppress ID --reason "..." writes the comment on the line before the code:
// tx0: ignore[tx0/csharp:negative-hash-index] reason="..."tx0 explain tx0/csharp:negative-hash-index shows the same in the terminal. Found a false positive? Report it.