@@ -81,23 +81,25 @@ func New[K comparable, V any](size int, ttl time.Duration) *Sieve[K, V] {
8181 }
8282
8383 if ttl != 0 {
84- go func (ctx context.Context ) {
85- ticker := time .NewTicker (ttl / numberOfBuckets )
86- defer ticker .Stop ()
87- for {
88- select {
89- case <- ctx .Done ():
90- return
91- case <- ticker .C :
92- cache .deleteExpired ()
93- }
94- }
95- }(cache .ctx )
84+ go cache .cleanup (cache .ctx )
9685 }
9786
9887 return cache
9988}
10089
90+ func (s * Sieve [K , V ]) cleanup (ctx context.Context ) {
91+ ticker := time .NewTicker (s .ttl / numberOfBuckets )
92+ defer ticker .Stop ()
93+ for {
94+ select {
95+ case <- ctx .Done ():
96+ return
97+ case <- ticker .C :
98+ s .deleteExpired ()
99+ }
100+ }
101+ }
102+
101103func (s * Sieve [K , V ]) Set (key K , value V ) {
102104 s .mu .Lock ()
103105 defer s .mu .Unlock ()
@@ -147,7 +149,7 @@ func (s *Sieve[K, V]) Remove(key K) (ok bool) {
147149 s .hand = s .hand .Prev ()
148150 }
149151
150- s .removeEntry (e )
152+ s .removeEntry (e , types . EvictReasonRemoved )
151153 return true
152154 }
153155
@@ -191,7 +193,7 @@ func (s *Sieve[K, V]) Purge() {
191193 defer s .mu .Unlock ()
192194
193195 for _ , e := range s .items {
194- s .removeEntry (e )
196+ s .removeEntry (e , types . EvictReasonRemoved )
195197 }
196198
197199 for i := range s .buckets {
@@ -213,9 +215,9 @@ func (s *Sieve[K, V]) Close() {
213215 s .mu .Unlock ()
214216}
215217
216- func (s * Sieve [K , V ]) removeEntry (e * entry [K , V ]) {
218+ func (s * Sieve [K , V ]) removeEntry (e * entry [K , V ], reason types. EvictReason ) {
217219 if s .callback != nil {
218- s .callback (e .key , e .value )
220+ s .callback (e .key , e .value , reason )
219221 }
220222
221223 s .ll .Remove (e .element )
@@ -249,7 +251,7 @@ func (s *Sieve[K, V]) evict() {
249251 }
250252
251253 s .hand = o .Prev ()
252- s .removeEntry (el )
254+ s .removeEntry (el , types . EvictReasonEvicted )
253255}
254256
255257func (s * Sieve [K , V ]) addToBucket (e * entry [K , V ]) {
@@ -285,7 +287,7 @@ func (s *Sieve[K, V]) deleteExpired() {
285287 }
286288
287289 for _ , e := range bucket .entries {
288- s .removeEntry (e )
290+ s .removeEntry (e , types . EvictReasonExpired )
289291 }
290292
291293 s .mu .Unlock ()
0 commit comments