forked from influxdata/telegraf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ttl_cache.go
62 lines (52 loc) · 1.16 KB
/
ttl_cache.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package ifname
import (
"runtime"
"time"
)
type TTLValType struct {
time time.Time // when entry was added
val valType
}
type timeFunc func() time.Time
type TTLCache struct {
validDuration time.Duration
lru LRUCache
now timeFunc
}
func NewTTLCache(valid time.Duration, capacity uint) TTLCache {
return TTLCache{
lru: NewLRUCache(capacity),
validDuration: valid,
now: time.Now,
}
}
func (c *TTLCache) Get(key keyType) (valType, bool, time.Duration) {
v, ok := c.lru.Get(key)
if !ok {
return valType{}, false, 0
}
if runtime.GOOS == "windows" {
// Sometimes on Windows `c.now().Sub(v.time) == 0` due to clock resolution issues:
// https://github.com/golang/go/issues/17696
// https://github.com/golang/go/issues/29485
// Force clock to refresh:
time.Sleep(time.Nanosecond)
}
age := c.now().Sub(v.time)
if age < c.validDuration {
return v.val, ok, age
} else {
c.lru.Delete(key)
return valType{}, false, 0
}
}
func (c *TTLCache) Put(key keyType, value valType) {
v := TTLValType{
val: value,
time: c.now(),
}
c.lru.Put(key, v)
}
func (c *TTLCache) Delete(key keyType) {
c.lru.Delete(key)
}