-
Notifications
You must be signed in to change notification settings - Fork 216
/
logic_expressions.go
89 lines (77 loc) · 1.8 KB
/
logic_expressions.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
/*
Copyright 2021 The CloudEvents Authors
SPDX-License-Identifier: Apache-2.0
*/
package expression
import (
cesql "github.com/cloudevents/sdk-go/sql/v2"
"github.com/cloudevents/sdk-go/sql/v2/utils"
cloudevents "github.com/cloudevents/sdk-go/v2"
)
type logicExpression struct {
baseBinaryExpression
fn func(x, y bool) bool
verb string
}
func (s logicExpression) Evaluate(event cloudevents.Event) (interface{}, error) {
leftVal, err := s.left.Evaluate(event)
if err != nil {
return nil, err
}
leftVal, err = utils.Cast(leftVal, cesql.BooleanType)
if err != nil {
return nil, err
}
// Don't bother to check the other expression unless we need to
if s.verb == "AND" && leftVal.(bool) == false {
return false, nil
}
if s.verb == "OR" && leftVal.(bool) == true {
return true, nil
}
rightVal, err := s.right.Evaluate(event)
if err != nil {
return nil, err
}
rightVal, err = utils.Cast(rightVal, cesql.BooleanType)
if err != nil {
return nil, err
}
return s.fn(leftVal.(bool), rightVal.(bool)), nil
}
func NewAndExpression(left cesql.Expression, right cesql.Expression) cesql.Expression {
return logicExpression{
baseBinaryExpression: baseBinaryExpression{
left: left,
right: right,
},
fn: func(x, y bool) bool {
return x && y
},
verb: "AND",
}
}
func NewOrExpression(left cesql.Expression, right cesql.Expression) cesql.Expression {
return logicExpression{
baseBinaryExpression: baseBinaryExpression{
left: left,
right: right,
},
fn: func(x, y bool) bool {
return x || y
},
verb: "OR",
}
}
func NewXorExpression(left cesql.Expression, right cesql.Expression) cesql.Expression {
return logicExpression{
baseBinaryExpression: baseBinaryExpression{
left: left,
right: right,
},
fn: func(x, y bool) bool {
return x != y
},
verb: "XOR",
}
}