forked from open-policy-agent/opa
-
Notifications
You must be signed in to change notification settings - Fork 0
/
map.go
114 lines (99 loc) · 2.29 KB
/
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
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
// Copyright 2016 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 ast
import "github.com/open-policy-agent/opa/util"
// ValueMap represents a key/value map between AST term values. Any type of term
// can be used as a key in the map.
type ValueMap struct {
hashMap *util.HashMap
}
// NewValueMap returns a new ValueMap.
func NewValueMap() *ValueMap {
vs := &ValueMap{
hashMap: util.NewHashMap(valueEq, valueHash),
}
return vs
}
// Copy returns a shallow copy of the ValueMap.
func (vs *ValueMap) Copy() *ValueMap {
if vs == nil {
return nil
}
cpy := NewValueMap()
cpy.hashMap = vs.hashMap.Copy()
return cpy
}
// Equal returns true if this ValueMap equals the other.
func (vs *ValueMap) Equal(other *ValueMap) bool {
if vs == nil {
return other == nil || other.Len() == 0
}
if other == nil {
return vs == nil || vs.Len() == 0
}
return vs.hashMap.Equal(other.hashMap)
}
// Len returns the number of elements in the map.
func (vs *ValueMap) Len() int {
if vs == nil {
return 0
}
return vs.hashMap.Len()
}
// Get returns the value in the map for k.
func (vs *ValueMap) Get(k Value) Value {
if vs != nil {
if v, ok := vs.hashMap.Get(k); ok {
return v.(Value)
}
}
return nil
}
// Hash returns a hash code for this ValueMap.
func (vs *ValueMap) Hash() int {
if vs == nil {
return 0
}
return vs.hashMap.Hash()
}
// Iter calls the iter function for each key/value pair in the map. If the iter
// function returns true, iteration stops.
func (vs *ValueMap) Iter(iter func(Value, Value) bool) bool {
if vs == nil {
return false
}
return vs.hashMap.Iter(func(kt, vt util.T) bool {
k := kt.(Value)
v := vt.(Value)
return iter(k, v)
})
}
// Put inserts a key k into the map with value v.
func (vs *ValueMap) Put(k, v Value) {
if vs == nil {
panic("put on nil value map")
}
vs.hashMap.Put(k, v)
}
// Delete removes a key k from the map.
func (vs *ValueMap) Delete(k Value) {
if vs == nil {
return
}
vs.hashMap.Delete(k)
}
func (vs *ValueMap) String() string {
if vs == nil {
return "{}"
}
return vs.hashMap.String()
}
func valueHash(v util.T) int {
return v.(Value).Hash()
}
func valueEq(a, b util.T) bool {
av := a.(Value)
bv := b.(Value)
return av.Compare(bv) == 0
}