Skip to content

Commit

Permalink
fix hashCode function in BitArray
Browse files Browse the repository at this point in the history
  • Loading branch information
Quillraven committed Oct 26, 2024
1 parent 9b584e1 commit c7d2995
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 9 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -154,16 +154,12 @@ class BitArray(
}

override fun hashCode(): Int {
if (bits.isEmpty()) {
return 0
var result = 1
for (i in bits.size - 1 downTo 0) {
val word = bits[i]
result = 31 * result + (word xor (word ushr 32)).toInt()
}

val word = length() ushr 6
var hash = 0
for (i in 0..word) {
hash = 127 * hash + (bits[i] xor (bits[i] ushr 32)).toInt()
}
return hash
return result
}

override fun equals(other: Any?): Boolean {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -189,4 +189,33 @@ internal class BitArrayTest {
assertEquals(expected3, bits3.toString())
assertEquals(expected4, bits4.toString())
}

@Test
fun testHashCode() {
// empty BitArray
val bits = BitArray()
bits.hashCode()

// test for single long
bits.set(0)
bits.hashCode()
bits.set(1)
bits.hashCode()
bits.set(63)
bits.hashCode()

// BitArray resizes to two longs in the LongArray
bits.set(64)
bits.hashCode()
bits.set(65)
bits.hashCode()
bits.set(127)
bits.hashCode()

// BitArray resizes to more than two longs
bits.set(128)
bits.hashCode()
bits.set(129)
bits.hashCode()
}
}

0 comments on commit c7d2995

Please sign in to comment.