38
38
39
39
// Item is an item
40
40
type 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
44
45
}
45
46
46
47
// Expired returns true if the item has expired.
@@ -51,13 +52,20 @@ func (item *Item[K, V]) Expired() bool {
51
52
return nowFunc ().After (item .Expiration )
52
53
}
53
54
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
+
54
61
var nowFunc = time .Now
55
62
56
63
// ItemOption is an option for cache item.
57
64
type ItemOption func (* itemOptions )
58
65
59
66
type itemOptions struct {
60
- expiration time.Time // default none
67
+ expiration time.Time // default none
68
+ referenceCount int
61
69
}
62
70
63
71
// WithExpiration is an option to set expiration time for any items.
@@ -68,23 +76,34 @@ func WithExpiration(exp time.Duration) ItemOption {
68
76
}
69
77
}
70
78
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
+
71
90
// newItem creates a new item with specified any options.
72
91
func newItem [K comparable , V any ](key K , val V , opts ... ItemOption ) * Item [K , V ] {
73
92
o := new (itemOptions )
74
93
for _ , optFunc := range opts {
75
94
optFunc (o )
76
95
}
77
96
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 ,
81
101
}
82
102
}
83
103
84
104
// Cache is a thread safe cache.
85
105
type Cache [K comparable , V any ] struct {
86
106
cache Interface [K , * Item [K , V ]]
87
- //expirations map[K]chan struct{}
88
107
// mu is used to do lock in some method process.
89
108
mu sync.Mutex
90
109
janitor * janitor
0 commit comments