Skip to content

Commit

Permalink
Make sure hashmap cap is power of 2
Browse files Browse the repository at this point in the history
  • Loading branch information
zyedidia committed Apr 13, 2022
1 parent c1f83ec commit 8166217
Showing 1 changed file with 9 additions and 0 deletions.
9 changes: 9 additions & 0 deletions hashmap/map.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,20 @@ type ops[T any] struct {
hash func(t T) uint64
}

func pow2ceil(num uint64) uint64 {
power := uint64(1)
for power < num {
power *= 2
}
return power
}

// New constructs a new map with the given capacity.
func New[K, V any](capacity uint64, equals g.EqualsFn[K], hash g.HashFn[K]) *Map[K, V] {
if capacity == 0 {
capacity = 1
}
capacity = pow2ceil(capacity)
return &Map[K, V]{
entries: make([]entry[K, V], capacity),
capacity: capacity,
Expand Down

0 comments on commit 8166217

Please sign in to comment.