3838
3939// Item is an item
4040type Item [K comparable , V any ] struct {
41- Key K
42- Value V
43- Expiration time.Time
41+ Key K
42+ Value V
43+ Expiration time.Time
44+ InitialReferenceCount int
4445}
4546
4647// Expired returns true if the item has expired.
@@ -51,13 +52,20 @@ func (item *Item[K, V]) Expired() bool {
5152 return nowFunc ().After (item .Expiration )
5253}
5354
55+ // GetReferenceCount returns reference count to be used when setting
56+ // the cache item for the first time.
57+ func (item * Item [K , V ]) GetReferenceCount () int {
58+ return item .InitialReferenceCount
59+ }
60+
5461var nowFunc = time .Now
5562
5663// ItemOption is an option for cache item.
5764type ItemOption func (* itemOptions )
5865
5966type itemOptions struct {
60- expiration time.Time // default none
67+ expiration time.Time // default none
68+ referenceCount int
6169}
6270
6371// WithExpiration is an option to set expiration time for any items.
@@ -68,23 +76,34 @@ func WithExpiration(exp time.Duration) ItemOption {
6876 }
6977}
7078
79+ // WithReferenceCount is an option to set reference count for any items.
80+ // This option is only applicable to cache policies that have a reference count (e.g., Clock, LFU).
81+ // referenceCount specifies the reference count value to set for the cache item.
82+ //
83+ // the default is 1.
84+ func WithReferenceCount (referenceCount int ) ItemOption {
85+ return func (o * itemOptions ) {
86+ o .referenceCount = referenceCount
87+ }
88+ }
89+
7190// newItem creates a new item with specified any options.
7291func newItem [K comparable , V any ](key K , val V , opts ... ItemOption ) * Item [K , V ] {
7392 o := new (itemOptions )
7493 for _ , optFunc := range opts {
7594 optFunc (o )
7695 }
7796 return & Item [K , V ]{
78- Key : key ,
79- Value : val ,
80- Expiration : o .expiration ,
97+ Key : key ,
98+ Value : val ,
99+ Expiration : o .expiration ,
100+ InitialReferenceCount : o .referenceCount ,
81101 }
82102}
83103
84104// Cache is a thread safe cache.
85105type Cache [K comparable , V any ] struct {
86106 cache Interface [K , * Item [K , V ]]
87- //expirations map[K]chan struct{}
88107 // mu is used to do lock in some method process.
89108 mu sync.Mutex
90109 janitor * janitor
0 commit comments