Total Lines | 47 |
Duplicated Lines | 0 % |
Changes | 0 |
1 | // Package weakcache implements Weak Cache, eviction of entries are controlled by GC |
||
2 | package weakcache |
||
3 | |||
4 | import ( |
||
5 | "github.com/arazmj/gerdu/metrics" |
||
6 | "github.com/ivanrad/go-weakref/weakref" |
||
7 | "sync" |
||
8 | ) |
||
9 | |||
10 | // WeakCache data structure |
||
11 | type WeakCache struct { |
||
12 | sync.Map |
||
13 | } |
||
14 | |||
15 | // NewWeakCache constructor |
||
16 | func NewWeakCache() *WeakCache { |
||
17 | return &WeakCache{} |
||
18 | } |
||
19 | |||
20 | // Put a new key value pair |
||
21 | func (c *WeakCache) Put(key string, value string) (created bool) { |
||
22 | metrics.Adds.Inc() |
||
23 | ref := weakref.NewWeakRef(value) |
||
24 | c.Store(key, ref) |
||
25 | return true |
||
26 | } |
||
27 | |||
28 | // Get value by key |
||
29 | func (c *WeakCache) Get(key string) (value string, ok bool) { |
||
30 | v, ok := c.Load(key) |
||
31 | if ok { |
||
32 | ref := v.(*weakref.WeakRef) |
||
33 | if ref.IsAlive() { |
||
34 | metrics.Hits.Inc() |
||
35 | return ref.GetTarget().(string), true |
||
36 | } |
||
37 | metrics.Deletes.Inc() |
||
38 | c.Delete(key) |
||
39 | } |
||
40 | metrics.Miss.Inc() |
||
41 | return "", false |
||
42 | } |
||
43 | |||
44 | //Delete deletes the key |
||
45 | func (c *WeakCache) Delete(key string) bool { |
||
46 | metrics.Deletes.Inc() |
||
47 | c.Map.Delete(key) |
||
48 | return true |
||
49 | } |
||
50 |