|
| 1 | +package blockstm |
| 2 | + |
| 3 | +import ( |
| 4 | + "sync/atomic" |
| 5 | + "testing" |
| 6 | + |
| 7 | + "github.com/stretchr/testify/require" |
| 8 | +) |
| 9 | + |
| 10 | +// TestGCachedStorage covers hit/miss memoization for both V=[]byte and V=any, |
| 11 | +// the ObjKV case is a regression guard against the nil-interface assertion panic. |
| 12 | +func TestGCachedStorage(t *testing.T) { |
| 13 | + t.Run("KV", func(t *testing.T) { |
| 14 | + parent := NewMemDB() |
| 15 | + parent.Set([]byte("k"), []byte("v")) |
| 16 | + assertCache(t, parent, []byte("v"), nil) |
| 17 | + }) |
| 18 | + |
| 19 | + t.Run("ObjKV", func(t *testing.T) { |
| 20 | + parent := NewObjMemDB() |
| 21 | + parent.Set([]byte("k"), "v") |
| 22 | + assertCache(t, parent, "v", nil) |
| 23 | + }) |
| 24 | +} |
| 25 | + |
| 26 | +func assertCache[V any](t *testing.T, parent GStorage[V], hitValue, missValue V) { |
| 27 | + t.Helper() |
| 28 | + counted := &countingStorage[V]{GStorage: parent} |
| 29 | + cached := NewGCachedStorage(counted) |
| 30 | + |
| 31 | + for i := 0; i < 3; i++ { |
| 32 | + require.Equal(t, hitValue, cached.Get([]byte("k"))) |
| 33 | + require.Equal(t, missValue, cached.Get([]byte("missing"))) |
| 34 | + } |
| 35 | + require.EqualValues(t, 2, counted.gets.Load(), "each distinct key reads parent exactly once") |
| 36 | +} |
| 37 | + |
| 38 | +type countingStorage[V any] struct { |
| 39 | + GStorage[V] |
| 40 | + gets atomic.Int64 |
| 41 | +} |
| 42 | + |
| 43 | +func (c *countingStorage[V]) Get(key []byte) V { |
| 44 | + c.gets.Add(1) |
| 45 | + return c.GStorage.Get(key) |
| 46 | +} |
0 commit comments