-
Notifications
You must be signed in to change notification settings - Fork 168
/
cache.go
57 lines (44 loc) · 1.2 KB
/
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
package desc
import (
"sync"
"google.golang.org/protobuf/reflect/protoreflect"
)
type descriptorCache interface {
get(protoreflect.Descriptor) Descriptor
put(protoreflect.Descriptor, Descriptor)
}
type lockingCache struct {
cacheMu sync.RWMutex
cache mapCache
}
func (c *lockingCache) get(d protoreflect.Descriptor) Descriptor {
c.cacheMu.RLock()
defer c.cacheMu.RUnlock()
return c.cache.get(d)
}
func (c *lockingCache) put(key protoreflect.Descriptor, val Descriptor) {
c.cacheMu.Lock()
defer c.cacheMu.Unlock()
c.cache.put(key, val)
}
func (c *lockingCache) withLock(fn func(descriptorCache)) {
c.cacheMu.Lock()
defer c.cacheMu.Unlock()
// Pass the underlying mapCache. We don't want fn to use
// c.get or c.put sine we already have the lock. So those
// methods would try to re-acquire and then deadlock!
fn(c.cache)
}
type mapCache map[protoreflect.Descriptor]Descriptor
func (c mapCache) get(d protoreflect.Descriptor) Descriptor {
return c[d]
}
func (c mapCache) put(key protoreflect.Descriptor, val Descriptor) {
c[key] = val
}
type noopCache struct{}
func (noopCache) get(protoreflect.Descriptor) Descriptor {
return nil
}
func (noopCache) put(protoreflect.Descriptor, Descriptor) {
}