Files
kubesphere/vendor/github.com/open-policy-agent/opa/topdown/sets.go
hongzhouzi ef03b1e3df Upgrade dependent version: github.com/open-policy-agent/opa (#5315)
Upgrade dependent version: github.com/open-policy-agent/opa v0.18.0 -> v0.45.0

Signed-off-by: hongzhouzi <hongzhouzi@kubesphere.io>

Signed-off-by: hongzhouzi <hongzhouzi@kubesphere.io>
2022-10-31 10:58:55 +08:00

89 lines
2.0 KiB
Go

// 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) {
// The set union logic here is duplicated and manually inlined on
// purpose. By lifting this logic up a level, and not doing pairwise
// set unions, we avoid a number of heap allocations. This improves
// performance dramatically over the naive approach.
result := ast.NewSet()
inputSet, err := builtins.SetOperand(a, 1)
if err != nil {
return nil, err
}
err = inputSet.Iter(func(x *ast.Term) error {
item, err := builtins.SetOperand(x.Value, 1)
if err != nil {
return err
}
item.Foreach(result.Add)
return nil
})
return result, err
}
func init() {
RegisterFunctionalBuiltin2(ast.SetDiff.Name, builtinSetDiff)
RegisterFunctionalBuiltin1(ast.Intersection.Name, builtinSetIntersection)
RegisterFunctionalBuiltin1(ast.Union.Name, builtinSetUnion)
}