Skip to content

Commit ee2e306

Browse files
add int overflow check for 32-bit systems (#553)
1 parent f7b6a51 commit ee2e306

File tree

1 file changed

+7
-1
lines changed

1 file changed

+7
-1
lines changed

src/internal/cachehash/shardedcachehash.go

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,13 @@ func (c *ShardedCacheHash) Init(maxLen int, shards int) {
3535

3636
func (c *ShardedCacheHash) getShardID(k interface{}) int {
3737
kb := []byte(fmt.Sprintf("%v", k))
38-
return int(crc32.ChecksumIEEE(kb)) % c.shardsLen
38+
hash := int(crc32.ChecksumIEEE(kb))
39+
// crc32 returns a 32-bit unsigned integer. On 32-bit systems, this int cast can return negative values.
40+
// To ensure we always have 0 <= shard ID < shardsLen, we take the absolute value of the hash.
41+
if hash < 0 {
42+
hash = -hash
43+
}
44+
return hash % c.shardsLen
3945
}
4046

4147
func (c *ShardedCacheHash) getShard(k interface{}) *CacheHash {

0 commit comments

Comments
 (0)