Skip to content

Commit 73addb2

Browse files
authored
Merge pull request #8 from Code-Hex/fix/referenced-item
fixed referenced item
2 parents 82f85aa + 85a991f commit 73addb2

File tree

4 files changed

+18
-2
lines changed

4 files changed

+18
-2
lines changed

cache.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,8 @@ type Item[K comparable, V any] struct {
2424
ReferencedAt time.Time
2525
}
2626

27+
// Referenced increments a reference counter and updates `ReferencedAt`
28+
// to current time.
2729
func (i *Item[K, V]) Referenced() {
2830
i.ReferenceCount++
2931
i.ReferencedAt = nowFunc()

lru/lru.go

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@ func (c *Cache[K, V]) Get(key K) (zero V, _ bool) {
4343
if item.HasExpired() {
4444
return
4545
}
46+
item.Referenced()
4647
// updates cache order
4748
c.list.MoveToFront(e)
4849
return item.Value, true
@@ -56,7 +57,9 @@ func (c *Cache[K, V]) Set(key K, val V, opts ...cache.ItemOption) {
5657
if e, ok := c.items[key]; ok {
5758
// updates cache order
5859
c.list.MoveToFront(e)
59-
e.Value.(*cache.Item[K, V]).Value = val
60+
item := e.Value.(*cache.Item[K, V])
61+
item.Value = val
62+
item.Referenced()
6063
return
6164
}
6265

simple/example_test.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,11 +23,16 @@ func ExampleCache() {
2323
if !aok2 {
2424
fmt.Println("key 'a' has been deleted")
2525
}
26+
// update
27+
c.Set("b", 3)
28+
newbv, _ := c.Get("b")
29+
fmt.Println(newbv)
2630
// Output:
2731
// 1 true
2832
// 2 true
2933
// 0 false
3034
// key 'a' has been deleted
35+
// 3
3136
}
3237

3338
func ExampleCacheKeys() {

simple/simple.go

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,8 +26,13 @@ func NewCache[K comparable, V any]() *Cache[K, V] {
2626
// The default item never expires.
2727
func (c *Cache[K, V]) Set(k K, v V, opts ...cache.ItemOption) {
2828
c.mu.Lock()
29+
defer c.mu.Unlock()
30+
if item, ok := c.items[k]; ok {
31+
item.Value = v
32+
item.Referenced()
33+
return
34+
}
2935
c.items[k] = cache.NewItem(k, v, opts...)
30-
c.mu.Unlock()
3136
}
3237

3338
// Get gets an item from the cache.
@@ -43,6 +48,7 @@ func (c *Cache[K, V]) Get(k K) (val V, ok bool) {
4348
if got.HasExpired() {
4449
return
4550
}
51+
got.Referenced()
4652
return got.Value, true
4753
}
4854

0 commit comments

Comments
 (0)