github.com/rajeev159/opa@v0.45.0/topdown/sets.go (about)

     1  // Copyright 2016 The OPA Authors.  All rights reserved.
     2  // Use of this source code is governed by an Apache2
     3  // license that can be found in the LICENSE file.
     4  
     5  package topdown
     6  
     7  import (
     8  	"github.com/open-policy-agent/opa/ast"
     9  	"github.com/open-policy-agent/opa/topdown/builtins"
    10  )
    11  
    12  // Deprecated in v0.4.2 in favour of minus/infix "-" operation.
    13  func builtinSetDiff(a, b ast.Value) (ast.Value, error) {
    14  
    15  	s1, err := builtins.SetOperand(a, 1)
    16  	if err != nil {
    17  		return nil, err
    18  	}
    19  
    20  	s2, err := builtins.SetOperand(b, 2)
    21  	if err != nil {
    22  		return nil, err
    23  	}
    24  
    25  	return s1.Diff(s2), nil
    26  }
    27  
    28  // builtinSetIntersection returns the intersection of the given input sets
    29  func builtinSetIntersection(a ast.Value) (ast.Value, error) {
    30  
    31  	inputSet, err := builtins.SetOperand(a, 1)
    32  	if err != nil {
    33  		return nil, err
    34  	}
    35  
    36  	// empty input set
    37  	if inputSet.Len() == 0 {
    38  		return ast.NewSet(), nil
    39  	}
    40  
    41  	var result ast.Set
    42  
    43  	err = inputSet.Iter(func(x *ast.Term) error {
    44  		n, err := builtins.SetOperand(x.Value, 1)
    45  		if err != nil {
    46  			return err
    47  		}
    48  
    49  		if result == nil {
    50  			result = n
    51  		} else {
    52  			result = result.Intersect(n)
    53  		}
    54  		return nil
    55  	})
    56  	return result, err
    57  }
    58  
    59  // builtinSetUnion returns the union of the given input sets
    60  func builtinSetUnion(a ast.Value) (ast.Value, error) {
    61  
    62  	inputSet, err := builtins.SetOperand(a, 1)
    63  	if err != nil {
    64  		return nil, err
    65  	}
    66  
    67  	result := ast.NewSet()
    68  
    69  	err = inputSet.Iter(func(x *ast.Term) error {
    70  		n, err := builtins.SetOperand(x.Value, 1)
    71  		if err != nil {
    72  			return err
    73  		}
    74  		result = result.Union(n)
    75  		return nil
    76  	})
    77  	return result, err
    78  }
    79  
    80  func init() {
    81  	RegisterFunctionalBuiltin2(ast.SetDiff.Name, builtinSetDiff)
    82  	RegisterFunctionalBuiltin1(ast.Intersection.Name, builtinSetIntersection)
    83  	RegisterFunctionalBuiltin1(ast.Union.Name, builtinSetUnion)
    84  }