Skip to content

Commit fd77782

Browse files
committedJul 18, 2022
Use absolute value of hash as bucket
On 32 bits architechtures, string hashes tend to have negative values. Such values cannot be used as bucket identifiers for hashtables. Using absolute value in case of negative hash solves this issue. Signed-off-by: Julien Rische <jrische@redhat.com>
1 parent 7120f23 commit fd77782

File tree

1 file changed

+9
-1
lines changed

1 file changed

+9
-1
lines changed
 

‎hashtable/hashtable.go

+9-1
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,14 @@ type Hash struct {
1414
size int
1515
}
1616

17+
func abs(x int) int {
18+
if x < 0 {
19+
return -x
20+
} else {
21+
return x
22+
}
23+
}
24+
1725
func (self *entry) Put(key Hashable, value interface{}) (e *entry, appended bool) {
1826
if self == nil {
1927
return &entry{key, value, nil}, true
@@ -57,7 +65,7 @@ func NewHashTable(initial_size int) *Hash {
5765
}
5866

5967
func (self *Hash) bucket(key Hashable) int {
60-
return key.Hash() % len(self.table)
68+
return abs(key.Hash()) % len(self.table)
6169
}
6270

6371
func (self *Hash) Size() int { return self.size }

0 commit comments

Comments
 (0)
Please sign in to comment.