forked from open-policy-agent/opa
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cache.go
65 lines (55 loc) · 1.27 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
58
59
60
61
62
63
64
65
// Copyright 2017 The OPA Authors. All rights reserved.
// Use of this source code is governed by an Apache2
// license that can be found in the LICENSE file.
package topdown
import (
"github.com/open-policy-agent/opa/ast"
)
type virtualCache struct {
stack []*virtualCacheElem
}
type virtualCacheElem struct {
value *ast.Term
children map[ast.Value]*virtualCacheElem
}
func newVirtualCache() *virtualCache {
cache := &virtualCache{}
cache.Push()
return cache
}
func (c *virtualCache) Push() {
c.stack = append(c.stack, newVirtualCacheElem())
}
func (c *virtualCache) Pop() {
c.stack = c.stack[:len(c.stack)]
}
func (c *virtualCache) Get(ref ast.Ref) *ast.Term {
node := c.stack[len(c.stack)-1]
for i := 0; i < len(ref); i++ {
key := ref[i].Value
next := node.children[key]
if next == nil {
return nil
}
node = next
}
return node.value
}
func (c *virtualCache) Put(ref ast.Ref, value *ast.Term) {
node := c.stack[len(c.stack)-1]
for i := 0; i < len(ref); i++ {
key := ref[i].Value
next := node.children[key]
if next == nil {
next = newVirtualCacheElem()
node.children[key] = next
}
node = next
}
node.value = value
}
func newVirtualCacheElem() *virtualCacheElem {
return &virtualCacheElem{
children: map[ast.Value]*virtualCacheElem{},
}
}