mirror of
https://github.com/open-policy-agent/opa.git
synced 2026-08-13 03:42:35 -06:00
e43ef0a979
Earlier this evening I tried to run the Go [modernize](https://pkg.go.dev/golang.org/x/tools/gopls/internal/analysis/modernize) analyzer on OPA. That didn't go as planned: - https://github.com/golang/go/issues/73661 - https://github.com/golang/go/issues/73663 While we wait for that to be fixed, I figured an old-fashioned search-and-replace across the repo may work for at least the `interface{}` to `any` conversion. That should help make it easier to see the other fixes as applied by the modernize tool once it has had those issues resolved. Signed-off-by: Anders Eknert <anders@styra.com>
54 lines
961 B
Go
54 lines
961 B
Go
package server
|
|
|
|
import "sync"
|
|
|
|
type cache struct {
|
|
data map[string]any
|
|
keylist []string
|
|
idx int
|
|
maxSize int
|
|
mtx sync.RWMutex
|
|
}
|
|
|
|
func newCache(maxSize int) *cache {
|
|
return &cache{
|
|
data: map[string]any{},
|
|
keylist: []string{},
|
|
maxSize: maxSize,
|
|
}
|
|
}
|
|
|
|
func (c *cache) Get(k string) (any, bool) {
|
|
c.mtx.RLock()
|
|
v, ok := c.data[k]
|
|
c.mtx.RUnlock()
|
|
return v, ok
|
|
}
|
|
|
|
func (c *cache) Insert(k string, v any) {
|
|
|
|
// Short path if its already in the cache
|
|
_, ok := c.Get(k)
|
|
if ok {
|
|
return
|
|
}
|
|
|
|
// Slow path, grab the write lock and insert
|
|
c.mtx.Lock()
|
|
_, ok = c.data[k]
|
|
if !ok {
|
|
c.data[k] = v
|
|
if len(c.keylist) < c.maxSize {
|
|
// Haven't reached max size yet, keep adding keys.
|
|
c.keylist = append(c.keylist, k)
|
|
} else {
|
|
// Start recycling spots in the key list and
|
|
// dropping cache entries for them.
|
|
delete(c.data, c.keylist[c.idx])
|
|
c.keylist[c.idx] = k
|
|
c.idx = (c.idx + 1) % c.maxSize
|
|
}
|
|
}
|
|
c.mtx.Unlock()
|
|
}
|