Skip to content

Commit 1abe120

Browse files
dgryskideadprogram
authored andcommitted
src/runtime: make hashmap calculations more uintptr-size independent
1 parent 8b360ec commit 1abe120

File tree

1 file changed

+14
-19
lines changed

1 file changed

+14
-19
lines changed

src/runtime/hashmap.go

Lines changed: 14 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -109,27 +109,22 @@ func hashmapKeyHashAlg(alg hashmapAlgorithm) func(key unsafe.Pointer, n uintptr)
109109
}
110110

111111
func hashmapShouldGrow(m *hashmap) bool {
112-
// with 29 bucket bits, we have potentially 8*(1 << 29) == 2^32 elements
113-
if m.bucketBits <= 29 {
114-
// "maximum" number of elements is 0.75 * buckets * elements per bucket
115-
// to avoid overflow, this is calculated as
116-
// max = 3 * (1/4 * buckets * elements per bucket)
117-
// = 3 * (buckets * (elements per bucket)/4)
118-
// = 3 * (buckets * (8/4)
119-
// = 3 * (buckets * 2)
120-
// = 6 * buckets
121-
max := (uintptr(6) << m.bucketBits)
122-
return m.count > max
123-
}
124-
125-
if m.bucketBits == 30 && m.count > uintptr(0xe0000000) {
126-
return true
112+
if m.bucketBits > uint8((unsafe.Sizeof(uintptr(0))*8)-3) {
113+
// Over this limit, we're likely to overflow uintptrs during calculations
114+
// or numbers of hash elements. Don't allow any more growth.
115+
// With 29 bits, this is 2^32 elements anyway.
116+
return false
127117
}
128118

129-
// bucketBits == 32 will cause overflow problems on 32-bit platforms, so we limit it to 31.
130-
// We're also likely to overflow the `int`-sized map length, causing other issues.
131-
132-
return false
119+
// "maximum" number of elements is 0.75 * buckets * elements per bucket
120+
// to avoid overflow, this is calculated as
121+
// max = 3 * (1/4 * buckets * elements per bucket)
122+
// = 3 * (buckets * (elements per bucket)/4)
123+
// = 3 * (buckets * (8/4)
124+
// = 3 * (buckets * 2)
125+
// = 6 * buckets
126+
max := (uintptr(6) << m.bucketBits)
127+
return m.count > max
133128
}
134129

135130
// Return the number of entries in this hashmap, called from the len builtin.

0 commit comments

Comments
 (0)