-
Notifications
You must be signed in to change notification settings - Fork 805
/
expression.go
86 lines (75 loc) · 2.31 KB
/
expression.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
package field
import (
"bytes"
"github.com/benthosdev/benthos/v4/internal/message"
)
// Message is an interface type to be given to a function interpolator, it
// allows the function to resolve fields and metadata from a message.
type Message interface {
Get(p int) *message.Part
Len() int
}
//------------------------------------------------------------------------------
// NewExpression creates a field expression from a slice of resolvers.
func NewExpression(resolvers ...Resolver) *Expression {
e := &Expression{
resolvers: resolvers,
}
var staticBuf bytes.Buffer
for _, r := range resolvers {
if s, is := r.(StaticResolver); is {
staticBuf.Write(s.ResolveBytes(0, message.QuickBatch(nil), false))
} else {
e.dynamicExpressions++
}
}
if e.dynamicExpressions > 0 || staticBuf.Len() == 0 {
return e
}
return &Expression{
static: staticBuf.String(),
}
}
//------------------------------------------------------------------------------
// Expression represents a Benthos dynamic field expression, used to configure
// string fields where the contents should change based on the contents of
// messages and other factors.
//
// Each function here resolves the expression for a particular message of a
// batch, this is why an index is expected.
type Expression struct {
static string
resolvers []Resolver
dynamicExpressions int
}
func (e *Expression) resolve(index int, msg Message, escaped bool) []byte {
if len(e.resolvers) == 1 {
return e.resolvers[0].ResolveBytes(index, msg, escaped)
}
var buf bytes.Buffer
for _, r := range e.resolvers {
buf.Write(r.ResolveBytes(index, msg, escaped))
}
return buf.Bytes()
}
// NumDynamicExpressions returns the number of dynamic interpolation functions
// within the expression.
func (e *Expression) NumDynamicExpressions() int {
return e.dynamicExpressions
}
// Bytes returns a byte slice representing the expression resolved for a message
// of a batch.
func (e *Expression) Bytes(index int, msg Message) []byte {
if len(e.resolvers) == 0 {
return []byte(e.static)
}
return e.resolve(index, msg, false)
}
// String returns a string representing the expression resolved for a message of
// a batch.
func (e *Expression) String(index int, msg Message) string {
if len(e.resolvers) == 0 {
return e.static
}
return string(e.Bytes(index, msg))
}