forked from open-policy-agent/opa
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvarset.go
88 lines (76 loc) · 1.66 KB
/
varset.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
// 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 (
"fmt"
"sort"
)
// VarSet represents a set of variables.
type VarSet map[Var]struct{}
// NewVarSet returns a new VarSet containing the specified variables.
func NewVarSet(vs ...Var) VarSet {
s := VarSet{}
for _, v := range vs {
s.Add(v)
}
return s
}
// Add updates the set to include the variable "v".
func (s VarSet) Add(v Var) {
s[v] = struct{}{}
}
// Contains returns true if the set contains the variable "v".
func (s VarSet) Contains(v Var) bool {
_, ok := s[v]
return ok
}
// Copy returns a shallow copy of the VarSet.
func (s VarSet) Copy() VarSet {
cpy := VarSet{}
for v := range s {
cpy.Add(v)
}
return cpy
}
// Diff returns a VarSet containing variables in s that are not in vs.
func (s VarSet) Diff(vs VarSet) VarSet {
r := VarSet{}
for v := range s {
if !vs.Contains(v) {
r.Add(v)
}
}
return r
}
// Equal returns true if s contains exactly the same elements as vs.
func (s VarSet) Equal(vs VarSet) bool {
if len(s.Diff(vs)) > 0 {
return false
}
return len(vs.Diff(s)) == 0
}
// Intersect returns a VarSet containing variables in s that are in vs.
func (s VarSet) Intersect(vs VarSet) VarSet {
r := VarSet{}
for v := range s {
if vs.Contains(v) {
r.Add(v)
}
}
return r
}
// Update merges the other VarSet into this VarSet.
func (s VarSet) Update(vs VarSet) {
for v := range vs {
s.Add(v)
}
}
func (s VarSet) String() string {
tmp := []string{}
for v := range s {
tmp = append(tmp, string(v))
}
sort.Strings(tmp)
return fmt.Sprintf("%v", tmp)
}