Skip to content

Commit

Permalink
Fix the second valueFn call in (*MapOf) LoadOrCompute (#66)
Browse files Browse the repository at this point in the history
  • Loading branch information
psyhatter authored Oct 29, 2022
1 parent 210ab28 commit dc679d8
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 1 deletion.
2 changes: 1 addition & 1 deletion mapof.go
Original file line number Diff line number Diff line change
Expand Up @@ -229,7 +229,7 @@ func (m *MapOf[K, V]) doStore(key K, valueFn func() V, loadIfExists bool) (V, bo
topHashes = atomic.LoadUint64(&emptyb.topHashMutex)
atomic.StoreUint64(&emptyb.topHashMutex, storeTopHash(hash, topHashes, emptyidx))
value := valueFn()
var wv interface{} = valueFn()
var wv interface{} = value
atomic.StorePointer(&emptyb.values[emptyidx], unsafe.Pointer(&wv))
atomic.StorePointer(&emptyb.keys[emptyidx], unsafe.Pointer(&key))
unlockBucket(&rootb.topHashMutex)
Expand Down
14 changes: 14 additions & 0 deletions mapof_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -395,6 +395,20 @@ func TestMapOfSerialLoadOrCompute(t *testing.T) {
t.Errorf("values do not match for %d: %v", i, v)
}
}

t.Run("valueFn func should be called only once", func(t *testing.T) {
m := NewIntegerMapOf[int, int]()
for i := 0; i < 100; {
m.LoadOrCompute(i, func() (v int) { v, i = i, i+1; return v })
}

m.Range(func(k, v int) bool {
if k != v {
t.Fatalf("%dth key is not equal to value %d", k, v)
}
return true
})
})
}

func TestMapOfSerialStoreThenDelete(t *testing.T) {
Expand Down

0 comments on commit dc679d8

Please sign in to comment.