-
Notifications
You must be signed in to change notification settings - Fork 22
/
engine.go
76 lines (61 loc) · 1.67 KB
/
engine.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
package dsl
import (
"regexp"
"sync"
"github.com/Knetic/govaluate"
mapsutil "github.com/projectdiscovery/utils/maps"
)
var (
defaultEngine *Engine
RegexStore = &mapsutil.SyncLockMap[string, *regexp.Regexp]{Map: make(mapsutil.Map[string, *regexp.Regexp])}
)
type Engine struct {
HelperFunctions map[string]govaluate.ExpressionFunction
ExpressionStore map[string]*govaluate.EvaluableExpression
exprmux sync.RWMutex
}
func NewEngine() (*Engine, error) {
engine := &Engine{
HelperFunctions: DefaultHelperFunctions,
ExpressionStore: make(map[string]*govaluate.EvaluableExpression),
}
return engine, nil
}
func (e *Engine) EvalExpr(expr string, vars map[string]interface{}) (interface{}, error) {
e.exprmux.Lock()
defer e.exprmux.Unlock()
compiled, err := govaluate.NewEvaluableExpressionWithFunctions(expr, e.HelperFunctions)
if err != nil {
return nil, err
}
e.ExpressionStore[expr] = compiled
return compiled.Evaluate(vars)
}
func (e *Engine) EvalExprFromCache(expr string, vars map[string]interface{}) (interface{}, error) {
compiled, ok := e.ExpressionStore[expr]
if !ok {
return e.EvalExpr(expr, vars)
}
return compiled.Evaluate(vars)
}
func EvalExpr(expr string, vars map[string]interface{}) (interface{}, error) {
if defaultEngine == nil {
var err error
defaultEngine, err = NewEngine()
if err != nil {
return nil, err
}
}
return defaultEngine.EvalExprFromCache(expr, vars)
}
func Regex(regxp string) (*regexp.Regexp, error) {
if compiled, ok := RegexStore.Get(regxp); ok {
return compiled, nil
}
compiled, err := regexp.Compile(regxp)
if err != nil {
return nil, err
}
_ = RegexStore.Set(regxp, compiled)
return compiled, nil
}