forked from grafana/loki
-
Notifications
You must be signed in to change notification settings - Fork 1
/
map.go
39 lines (34 loc) · 749 Bytes
/
map.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
package util
type GenerationalMap[K comparable, V any] struct {
oldgen map[K]V
newgen map[K]V
maxSize int
newV func() V
gcCb func()
}
// NewGenMap created which maintains at most maxSize recently used entries
func NewGenMap[K comparable, V any](maxSize int, newV func() V, gcCb func()) GenerationalMap[K, V] {
return GenerationalMap[K, V]{
newgen: make(map[K]V),
maxSize: maxSize,
newV: newV,
gcCb: gcCb,
}
}
func (m *GenerationalMap[K, T]) GetOrCreate(key K) T {
v, ok := m.newgen[key]
if !ok {
if v, ok = m.oldgen[key]; !ok {
v = m.newV()
}
m.newgen[key] = v
if len(m.newgen) == m.maxSize {
m.oldgen = m.newgen
m.newgen = make(map[K]T)
if m.gcCb != nil {
m.gcCb()
}
}
}
return v
}