@@ -9,24 +9,21 @@ import (
99 "github.com/sunshineplan/utils/container"
1010)
1111
12- var valueKey int
13-
1412type item [T any ] struct {
1513 sync.Mutex
1614 ctx context.Context
1715 cancel context.CancelFunc
1816 lifecycle time.Duration
17+ value T
1918 fn func () (T , error )
2019}
2120
22- func (i * item [T ]) set (value * T ) {
23- if i .ctx = context .WithValue (context .Background (), & valueKey , value ); i .lifecycle > 0 {
21+ func (i * item [T ]) set (value T ) {
22+ i .ctx = context .Background ()
23+ if i .lifecycle > 0 {
2424 i .ctx , i .cancel = context .WithTimeout (i .ctx , i .lifecycle )
2525 }
26- }
27-
28- func (i * item [T ]) value () T {
29- return * i .ctx .Value (& valueKey ).(* T )
26+ i .value = value
3027}
3128
3229func (i * item [T ]) renew () T {
@@ -35,9 +32,9 @@ func (i *item[T]) renew() T {
3532 defer i .Unlock ()
3633 if err != nil {
3734 log .Print (err )
38- v = i .value ()
35+ v = i .value
3936 }
40- i .set (& v )
37+ i .set (v )
4138 return v
4239}
4340
@@ -55,9 +52,7 @@ func NewWithRenew[Key comparable, Value any](autoRenew bool) *CacheWithRenew[Key
5552// Set sets cache value for a key, if fn is presented, this value will regenerate when expired.
5653func (c * CacheWithRenew [Key , Value ]) Set (key Key , value Value , lifecycle time.Duration , fn func () (Value , error )) {
5754 i := & item [Value ]{lifecycle : lifecycle , fn : fn }
58- i .Lock ()
59- defer i .Unlock ()
60- i .set (& value )
55+ i .set (value )
6156 if c .autoRenew && lifecycle > 0 {
6257 go func () {
6358 for {
@@ -99,7 +94,7 @@ func (c *CacheWithRenew[Key, Value]) Get(key Key) (value Value, ok bool) {
9994 }
10095 i .Lock ()
10196 defer i .Unlock ()
102- value = i .value ()
97+ value = i .value
10398 return
10499}
105100
@@ -120,16 +115,16 @@ func (c *CacheWithRenew[Key, Value]) Swap(key Key, value Value) (previous Value,
120115 if i , loaded = c .get (key ); loaded {
121116 i .Lock ()
122117 defer i .Unlock ()
123- previous = i .value ()
124- i .set (& value )
118+ previous = i .value
119+ i .set (value )
125120 }
126121 return
127122}
128123
129124// Clear deletes all values in cache.
130125func (c * CacheWithRenew [Key , Value ]) Clear () {
131- c .m .Range (func (k Key , i * item [Value ]) bool {
132- c .m .Delete (k )
126+ c .m .Range (func (key Key , i * item [Value ]) bool {
127+ c .m .Delete (key )
133128 i .Lock ()
134129 defer i .Unlock ()
135130 if i .cancel != nil {
0 commit comments