@@ -15,7 +15,12 @@ type Cache[K comparable, V any] struct {
15
15
mu sync.RWMutex
16
16
}
17
17
18
- var _ cache.Cache [interface {}, any ] = (* Cache [interface {}, any ])(nil )
18
+ type entry [K comparable , V any ] struct {
19
+ key K
20
+ val V
21
+ }
22
+
23
+ var _ cache.Interface [interface {}, any ] = (* Cache [interface {}, any ])(nil )
19
24
20
25
// NewCache creates a new LRU cache whose capacity is the default size (128).
21
26
func NewCache [K comparable , V any ]() * Cache [K , V ] {
@@ -39,32 +44,29 @@ func (c *Cache[K, V]) Get(key K) (zero V, _ bool) {
39
44
if ! ok {
40
45
return
41
46
}
42
- item := e .Value .(* cache.Item [K , V ])
43
- if item .HasExpired () {
44
- return
45
- }
46
- item .Referenced ()
47
47
// updates cache order
48
48
c .list .MoveToFront (e )
49
- return item .Value , true
49
+ return e .Value .( * entry [ K , V ]). val , true
50
50
}
51
51
52
52
// Set sets a value to the cache with key. replacing any existing value.
53
- func (c * Cache [K , V ]) Set (key K , val V , opts ... cache. ItemOption ) {
53
+ func (c * Cache [K , V ]) Set (key K , val V ) {
54
54
c .mu .Lock ()
55
55
defer c .mu .Unlock ()
56
56
57
57
if e , ok := c .items [key ]; ok {
58
58
// updates cache order
59
59
c .list .MoveToFront (e )
60
- item := e .Value .(* cache.Item [K , V ])
61
- item .Value = val
62
- item .Referenced ()
60
+ entry := e .Value .(* entry [K , V ])
61
+ entry .val = val
63
62
return
64
63
}
65
64
66
- item := cache .NewItem (key , val , opts ... )
67
- e := c .list .PushFront (item )
65
+ newEntry := & entry [K , V ]{
66
+ key : key ,
67
+ val : val ,
68
+ }
69
+ e := c .list .PushFront (newEntry )
68
70
c .items [key ] = e
69
71
70
72
if c .list .Len () > c .cap {
@@ -78,8 +80,8 @@ func (c *Cache[K, V]) Keys() []K {
78
80
defer c .mu .RUnlock ()
79
81
keys := make ([]K , 0 , len (c .items ))
80
82
for ent := c .list .Back (); ent != nil ; ent = ent .Prev () {
81
- item := ent .Value .(* cache. Item [K , V ])
82
- keys = append (keys , item . Key )
83
+ entry := ent .Value .(* entry [K , V ])
84
+ keys = append (keys , entry . key )
83
85
}
84
86
return keys
85
87
}
@@ -100,25 +102,13 @@ func (c *Cache[K, V]) Delete(key K) {
100
102
}
101
103
}
102
104
103
- // Contains reports whether key is within cache.
104
- func (c * Cache [K , V ]) Contains (key K ) bool {
105
- c .mu .RLock ()
106
- defer c .mu .RUnlock ()
107
- e , ok := c .items [key ]
108
- if ! ok {
109
- return false
110
- }
111
- item := e .Value .(* cache.Item [K , V ])
112
- return ! item .HasExpired ()
113
- }
114
-
115
105
func (c * Cache [K , V ]) deleteOldest () {
116
106
e := c .list .Back ()
117
107
c .delete (e )
118
108
}
119
109
120
110
func (c * Cache [K , V ]) delete (e * list.Element ) {
121
111
c .list .Remove (e )
122
- item := e .Value .(* cache. Item [K , V ])
123
- delete (c .items , item . Key )
112
+ entry := e .Value .(* entry [K , V ])
113
+ delete (c .items , entry . key )
124
114
}
0 commit comments