forked from ava-labs/avalanchego
-
Notifications
You must be signed in to change notification settings - Fork 0
/
unique_cache.go
93 lines (76 loc) · 1.67 KB
/
unique_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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
// (c) 2019-2020, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package cache
import (
"container/list"
"sync"
)
// EvictableLRU is an LRU cache that notifies the objects when they are evicted.
type EvictableLRU struct {
lock sync.Mutex
entryMap map[[32]byte]*list.Element
entryList *list.List
Size int
}
// Deduplicate implements the Deduplicator interface
func (c *EvictableLRU) Deduplicate(value Evictable) Evictable {
c.lock.Lock()
defer c.lock.Unlock()
return c.deduplicate(value)
}
// Flush implements the Deduplicator interface
func (c *EvictableLRU) Flush() {
c.lock.Lock()
defer c.lock.Unlock()
c.flush()
}
func (c *EvictableLRU) init() {
if c.entryMap == nil {
c.entryMap = make(map[[32]byte]*list.Element)
}
if c.entryList == nil {
c.entryList = list.New()
}
if c.Size <= 0 {
c.Size = 1
}
}
func (c *EvictableLRU) resize() {
for c.entryList.Len() > c.Size {
e := c.entryList.Front()
c.entryList.Remove(e)
val := e.Value.(Evictable)
delete(c.entryMap, val.ID().Key())
val.Evict()
}
}
func (c *EvictableLRU) deduplicate(value Evictable) Evictable {
c.init()
c.resize()
key := value.ID().Key()
if e, ok := c.entryMap[key]; !ok {
if c.entryList.Len() >= c.Size {
e = c.entryList.Front()
c.entryList.MoveToBack(e)
val := e.Value.(Evictable)
delete(c.entryMap, val.ID().Key())
val.Evict()
e.Value = value
} else {
e = c.entryList.PushBack(value)
}
c.entryMap[key] = e
} else {
c.entryList.MoveToBack(e)
val := e.Value.(Evictable)
value = val
}
return value
}
func (c *EvictableLRU) flush() {
c.init()
size := c.Size
c.Size = 0
c.resize()
c.Size = size
}