Skip to content

Commit

Permalink
fix policy updateCost
Browse files Browse the repository at this point in the history
  • Loading branch information
Yiling-J committed Oct 29, 2024
1 parent 32c6708 commit 4ccae57
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 5 deletions.
6 changes: 1 addition & 5 deletions internal/tlfu.go
Original file line number Diff line number Diff line change
Expand Up @@ -223,11 +223,7 @@ func (t *TinyLfu[K, V]) UpdateCost(entry *Entry[K, V], weightChange int64) {

// entry's policy weigh already updated
// so update weightedSize to keep sync
if weightChange > 0 {
t.weightedSize += uint(weightChange)
} else {
t.weightedSize -= uint(weightChange)
}
t.weightedSize += uint(weightChange)

// update window/slru
// if entry new weight > max size
Expand Down
21 changes: 21 additions & 0 deletions internal/tlfu_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -578,3 +578,24 @@ func TestTlfu_SketchResize(t *testing.T) {
require.Equal(t, size, len(tlfu.sketch.Table))
}
}

func TestTlfu_UpdateCost(t *testing.T) {
hasher := NewHasher[int](nil)
tlfu := NewTinyLfu[int, int](100, hasher)
e1 := &Entry[int, int]{key: 1, value: 1, policyWeight: 1}
e2 := &Entry[int, int]{key: 2, value: 1, policyWeight: 2}
e3 := &Entry[int, int]{key: 3, value: 1, policyWeight: 3}

tlfu.Set(e1)
tlfu.Set(e2)
tlfu.Set(e3)
require.Equal(t, 6, int(tlfu.weightedSize))

e1.policyWeight = 3
e2.policyWeight = 2
e3.policyWeight = 1
tlfu.UpdateCost(e1, 2)
tlfu.UpdateCost(e2, 0)
tlfu.UpdateCost(e3, -2)
require.Equal(t, 6, int(tlfu.weightedSize))
}

0 comments on commit 4ccae57

Please sign in to comment.