-
Notifications
You must be signed in to change notification settings - Fork 13
/
field_dict.go
247 lines (206 loc) · 5.57 KB
/
field_dict.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
package starlark
import (
"errors"
"fmt"
"strings"
"github.com/circonus-labs/circonus-unified-agent/cua"
"go.starlark.net/starlark"
)
// FieldDict is a starlark.Value for the metric fields. It is heavily based on the
// starlark.Dict.
type FieldDict struct {
*Metric
}
func (d FieldDict) String() string {
buf := new(strings.Builder)
buf.WriteString("{")
sep := ""
for _, item := range d.Items() {
k, v := item[0], item[1]
buf.WriteString(sep)
buf.WriteString(k.String())
buf.WriteString(": ")
buf.WriteString(v.String())
sep = ", "
}
buf.WriteString("}")
return buf.String()
}
func (d FieldDict) Type() string {
return "Fields"
}
func (d FieldDict) Freeze() {
d.frozen = true
}
func (d FieldDict) Truth() starlark.Bool {
return len(d.metric.FieldList()) != 0
}
func (d FieldDict) Hash() (uint32, error) {
return 0, errors.New("not hashable")
}
// AttrNames implements the starlark.HasAttrs interface.
func (d FieldDict) AttrNames() []string {
return builtinAttrNames(FieldDictMethods)
}
// Attr implements the starlark.HasAttrs interface.
func (d FieldDict) Attr(name string) (starlark.Value, error) {
return builtinAttr(d, name, FieldDictMethods)
}
var FieldDictMethods = map[string]builtinMethod{
"clear": dictClear,
"get": dictGet,
"items": dictItems,
"keys": dictKeys,
"pop": dictPop,
"popitem": dictPopItem,
"setdefault": dictSetDefault,
"update": dictUpdate,
"values": dictValues,
}
// Get implements the starlark.Mapping interface.
func (d FieldDict) Get(key starlark.Value) (v starlark.Value, found bool, err error) {
if k, ok := key.(starlark.String); ok {
gv, found := d.metric.GetField(k.GoString())
if !found {
return starlark.None, false, nil
}
v, err := asStarlarkValue(gv)
if err != nil {
return starlark.None, false, err
}
return v, true, nil
}
return starlark.None, false, errors.New("key must be of type 'str'")
}
// SetKey implements the starlark.HasSetKey interface to support map update
// using x[k]=v syntax, like a dictionary.
func (d FieldDict) SetKey(k, v starlark.Value) error {
if d.fieldIterCount > 0 {
return fmt.Errorf("cannot insert during iteration")
}
key, ok := k.(starlark.String)
if !ok {
return errors.New("field key must be of type 'str'")
}
gv, err := asGoValue(v)
if err != nil {
return err
}
d.metric.AddField(key.GoString(), gv)
return nil
}
// Items implements the starlark.IterableMapping interface.
func (d FieldDict) Items() []starlark.Tuple {
items := make([]starlark.Tuple, 0, len(d.metric.FieldList()))
for _, field := range d.metric.FieldList() {
key := starlark.String(field.Key)
sv, err := asStarlarkValue(field.Value)
if err != nil {
continue
}
pair := starlark.Tuple{key, sv}
items = append(items, pair)
}
return items
}
func (d FieldDict) Clear() error {
if d.fieldIterCount > 0 {
return fmt.Errorf("cannot delete during iteration")
}
keys := make([]string, 0, len(d.metric.FieldList()))
for _, field := range d.metric.FieldList() {
keys = append(keys, field.Key)
}
for _, key := range keys {
d.metric.RemoveField(key)
}
return nil
}
func (d FieldDict) PopItem() (v starlark.Value, err error) {
if d.fieldIterCount > 0 {
return nil, fmt.Errorf("cannot delete during iteration")
}
for _, field := range d.metric.FieldList() {
k := field.Key
v := field.Value
d.metric.RemoveField(k)
sk := starlark.String(k)
sv, err := asStarlarkValue(v)
if err != nil {
return nil, fmt.Errorf("could not convert to starlark value")
}
return starlark.Tuple{sk, sv}, nil //nolint:staticcheck
}
return nil, errors.New("popitem(): field dictionary is empty")
}
func (d FieldDict) Delete(k starlark.Value) (v starlark.Value, found bool, err error) {
if d.fieldIterCount > 0 {
return nil, false, fmt.Errorf("cannot delete during iteration")
}
if key, ok := k.(starlark.String); ok {
value, ok := d.metric.GetField(key.GoString())
if ok {
d.metric.RemoveField(key.GoString())
sv, err := asStarlarkValue(value)
return sv, ok, err
}
}
return starlark.None, false, errors.New("key must be of type 'str'")
}
// Items implements the starlark.Mapping interface.
func (d FieldDict) Iterate() starlark.Iterator {
d.fieldIterCount++
return &FieldIterator{Metric: d.Metric, fields: d.metric.FieldList()}
}
type FieldIterator struct {
*Metric
fields []*cua.Field
}
// Next implements the starlark.Iterator interface.
func (i *FieldIterator) Next(p *starlark.Value) bool {
if len(i.fields) == 0 {
return false
}
field := i.fields[0]
i.fields = i.fields[1:]
*p = starlark.String(field.Key)
return true
}
// Done implements the starlark.Iterator interface.
func (i *FieldIterator) Done() {
i.fieldIterCount--
}
// AsStarlarkValue converts a field value to a starlark.Value.
func asStarlarkValue(value interface{}) (starlark.Value, error) {
switch v := value.(type) {
case float64:
return starlark.Float(v), nil
case int64:
return starlark.MakeInt64(v), nil
case uint64:
return starlark.MakeUint64(v), nil
case string:
return starlark.String(v), nil
case bool:
return starlark.Bool(v), nil
}
return starlark.None, errors.New("invalid type")
}
// AsGoValue converts a starlark.Value to a field value.
func asGoValue(value interface{}) (interface{}, error) {
switch v := value.(type) {
case starlark.Float:
return float64(v), nil
case starlark.Int:
n, ok := v.Int64()
if !ok {
return nil, errors.New("cannot represent integer as int64")
}
return n, nil
case starlark.String:
return string(v), nil
case starlark.Bool:
return bool(v), nil
}
return nil, errors.New("invalid starlark type")
}