forked from open-policy-agent/opa
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sets.go
84 lines (67 loc) · 1.75 KB
/
sets.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
// 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 topdown
import (
"github.com/open-policy-agent/opa/ast"
"github.com/open-policy-agent/opa/topdown/builtins"
)
// Deprecated in v0.4.2 in favour of minus/infix "-" operation.
func builtinSetDiff(a, b ast.Value) (ast.Value, error) {
s1, err := builtins.SetOperand(a, 1)
if err != nil {
return nil, err
}
s2, err := builtins.SetOperand(b, 2)
if err != nil {
return nil, err
}
return s1.Diff(s2), nil
}
// builtinSetIntersection returns the intersection of the given input sets
func builtinSetIntersection(a ast.Value) (ast.Value, error) {
inputSet, err := builtins.SetOperand(a, 1)
if err != nil {
return nil, err
}
// empty input set
if inputSet.Len() == 0 {
return ast.NewSet(), nil
}
var result ast.Set
err = inputSet.Iter(func(x *ast.Term) error {
n, err := builtins.SetOperand(x.Value, 1)
if err != nil {
return err
}
if result == nil {
result = n
} else {
result = result.Intersect(n)
}
return nil
})
return result, err
}
// builtinSetUnion returns the union of the given input sets
func builtinSetUnion(a ast.Value) (ast.Value, error) {
inputSet, err := builtins.SetOperand(a, 1)
if err != nil {
return nil, err
}
result := ast.NewSet()
err = inputSet.Iter(func(x *ast.Term) error {
n, err := builtins.SetOperand(x.Value, 1)
if err != nil {
return err
}
result = result.Union(n)
return nil
})
return result, err
}
func init() {
RegisterFunctionalBuiltin2(ast.SetDiff.Name, builtinSetDiff)
RegisterFunctionalBuiltin1(ast.Intersection.Name, builtinSetIntersection)
RegisterFunctionalBuiltin1(ast.Union.Name, builtinSetUnion)
}