-
Notifications
You must be signed in to change notification settings - Fork 2
/
decode.go
464 lines (396 loc) · 9.59 KB
/
decode.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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
package gs2
import (
"fmt"
"io"
"io/ioutil"
"reflect"
"strconv"
"strings"
"time"
)
const gs2TimeLayout = "2006-01-02.15:04:05"
const scanEnd = -1
// Decoder reads and decodes GS2 input. NB: year, month and day is not supported in Step attribute. Only hour, minute and seconds
// are used when decoding duration.
type Decoder struct {
options decoderOptions
rdr io.Reader
scan *scanner
buf []byte
bytesRead int
lastByteRead byte
lastScanState int
typeCache map[reflect.Type]map[string]int
}
type decoderOptions struct {
validators []Validator
}
var defaultDecoderOptions = decoderOptions{
validators: []Validator{
ValidateNoOfObjects,
ValidateTimeSeriesValues,
},
}
// DecoderOption sets configuration for a Decoder.
type DecoderOption func(*decoderOptions)
// DecodeValidators sets the validators to be run after decoding an object. Will overwrite the default ones. So remeber to add the
// defaults as well if needed.
func DecodeValidators(v ...Validator) DecoderOption {
return func(o *decoderOptions) {
o.validators = v
}
}
// NewDecoder returna a new Decoder reading from r.
func NewDecoder(r io.Reader, opt ...DecoderOption) *Decoder {
opts := defaultDecoderOptions
for _, o := range opt {
o(&opts)
}
return &Decoder{
options: opts,
rdr: r,
scan: newScanner(),
typeCache: make(map[reflect.Type]map[string]int),
}
}
// Decode reads the input and puts it in a GS2 object.
func (d *Decoder) Decode() (*GS2, error) {
result := &GS2{}
err := d.decode(reflect.ValueOf(result))
if err != nil {
return nil, err
}
for _, validator := range d.options.validators {
if err := validator(result); err != nil {
return nil, err
}
}
return result, nil
}
func (d *Decoder) decode(v reflect.Value) error {
if err := d.fillBuffer(); err != nil {
return err
}
// Scan to the first # in the file, which should be the first block. The following block will be identified by one # since
// the first # of the block will be the delimiter of the previous blocks last value. As per the specification spaces are not
// to be used as delimiters.
d.scanWhile(scanHash)
for d.bytesRead < len(d.buf) {
d.scanNext()
switch d.lastScanState {
// Scan for two ## which is the start of a block.
case scanHash:
if err := d.block(v); err != nil {
return err
}
case scanSkipSpace:
continue
default:
return fmt.Errorf("unable to find start of block. Got character %q", d.buf[d.bytesRead-1])
}
}
return nil
}
func (d *Decoder) block(v reflect.Value) error {
dataStart := d.bytesRead
var blockName []byte
loop:
for {
d.scanNext()
switch d.lastScanState {
case scanContinue:
blockName = append(blockName, d.lastByteRead)
case scanSkipSpace:
case scanHash:
break loop
default:
return fmt.Errorf("unexpected state while decoding block: %s", string(d.buf[dataStart:d.bytesRead]))
}
}
field, exists := d.getField(string(blockName), reflect.Indirect(v).Type())
if !exists {
d.skipBlock()
return nil
}
vf := reflect.Indirect(v).Field(field)
var block reflect.Value
if vf.Kind() == reflect.Slice {
block = reflect.New(vf.Type().Elem())
} else {
block = reflect.New(vf.Type())
}
for d.lastScanState == scanHash && d.peek(0) != '#' {
if err := d.attribute(block); err != nil {
return err
}
}
if vf.Kind() == reflect.Slice {
vf.Set(reflect.Append(vf, reflect.Indirect(block)))
} else {
vf.Set(reflect.Indirect(block))
}
return nil
}
func (d *Decoder) attribute(v reflect.Value) error {
dataStart := d.bytesRead
var attributeName []byte
loop:
for {
d.scanNext()
switch d.lastScanState {
case scanContinue:
attributeName = append(attributeName, d.lastByteRead)
case scanBeginValue:
break loop
default:
return fmt.Errorf("unexpected state while decoding attribute: %s", string(d.buf[dataStart:d.bytesRead]))
}
}
field, exists := d.getField(string(attributeName), reflect.Indirect(v).Type())
if !exists {
d.skipAttribute()
return nil
}
vf := reflect.Indirect(v).Field(field)
attribute := reflect.New(vf.Type())
if reflect.Indirect(attribute).Kind() == reflect.Slice {
if err := d.array(attribute); err != nil {
return err
}
} else {
if err := d.value(attribute); err != nil {
return err
}
}
vf.Set(reflect.Indirect(attribute))
return nil
}
func (d *Decoder) value(v reflect.Value) error {
dataStart := d.bytesRead
var value []byte
loop:
for {
d.scanNext()
switch d.lastScanState {
case scanContinue:
value = append(value, d.lastByteRead)
case scanSkipSpace:
case scanHash:
break loop
case scanEnd:
break loop
default:
return fmt.Errorf("unexpected state while decoding value: %s", string(d.buf[dataStart:d.bytesRead]))
}
}
indirect := reflect.Indirect(v)
switch indirect.Kind() {
case reflect.String:
indirect.SetString(string(value))
case reflect.Int:
pi, err := strconv.ParseInt(string(value), 10, 64)
if err != nil {
return err
}
indirect.SetInt(pi)
case reflect.Int64:
switch indirect.Type() {
case reflect.TypeOf((*time.Duration)(nil)).Elem():
d, err := parseDuration(string(value))
if err != nil {
return err
}
indirect.Set(reflect.ValueOf(d))
default:
return fmt.Errorf("unsupported type %q", indirect.Type().Name())
}
case reflect.Float64:
pf, err := strconv.ParseFloat(string(value), 64)
if err != nil {
return err
}
indirect.SetFloat(pf)
case reflect.Struct:
switch indirect.Type() {
case reflect.TypeOf((*time.Time)(nil)).Elem():
t, err := parseTime(string(value))
if err != nil {
return err
}
indirect.Set(reflect.ValueOf(t))
case reflect.TypeOf((*Triplet)(nil)).Elem():
t, err := parseTriplet(string(value))
if err != nil {
return err
}
indirect.Set(reflect.ValueOf(t))
default:
return fmt.Errorf("unsupported type %q", indirect.Type().Name())
}
default:
return fmt.Errorf("unsupported type %q", indirect.Type().Name())
}
return nil
}
func (d *Decoder) array(v reflect.Value) error {
dataStart := d.bytesRead
// Scan for the start of an array
d.scanWhile(scanArrayStart)
var value []byte
loop:
for {
d.scanNext()
switch d.lastScanState {
case scanContinue:
value = append(value, d.lastByteRead)
case scanArrayEnd:
fallthrough
case scanArraySeparator:
if len(value) > 0 {
indirect := reflect.Indirect(v)
switch indirect.Type().Elem().Kind() {
case reflect.Struct:
switch indirect.Type().Elem() {
case reflect.TypeOf((*Triplet)(nil)).Elem():
trip, err := parseTriplet(string(value))
if err != nil {
return err
}
indirect.Set(reflect.Append(indirect, reflect.ValueOf(trip)))
default:
return fmt.Errorf("unsupported type %q for arrays", indirect.Type().Elem())
}
default:
return fmt.Errorf("unsupported type %q for arrays", indirect.Type().Elem())
}
value = value[:0]
}
case scanSkipSpace:
case scanHash:
break loop
default:
return fmt.Errorf("unexpected state while decoding value: %s", string(d.buf[dataStart:d.bytesRead]))
}
}
return nil
}
func (d *Decoder) fillBuffer() (err error) {
d.buf, err = ioutil.ReadAll(d.rdr)
return
}
func (d *Decoder) scanNext() {
if d.bytesRead == len(d.buf) {
d.lastScanState = scanEnd
return
}
d.lastScanState = d.scan.step(d.scan, d.buf[d.bytesRead])
d.lastByteRead = d.buf[d.bytesRead]
d.bytesRead++
}
func (d *Decoder) scanWhile(state int) {
for {
if d.lastScanState == state || d.lastScanState == scanEnd {
return
}
d.scanNext()
}
}
func (d *Decoder) peek(n int) byte {
return d.buf[d.bytesRead+n]
}
func (d *Decoder) skipBlock() {
for {
d.scanNext()
switch d.lastScanState {
case scanHash:
if d.peek(0) == '#' {
return
}
case scanEnd:
return
}
}
}
func (d *Decoder) skipAttribute() {
d.scanWhile(scanHash)
}
func (d *Decoder) getField(key string, typ reflect.Type) (int, bool) {
cachedTyp, isCached := d.typeCache[typ]
if isCached {
index, exists := cachedTyp[key]
if exists {
return index, true
}
}
for i := 0; i < typ.NumField(); i++ {
tag := typ.Field(i).Tag.Get("gs2")
if strings.EqualFold(key, strings.Split(tag, ",")[0]) {
if isCached {
cachedTyp[key] = i
} else {
m := make(map[string]int)
m[key] = i
d.typeCache[typ] = m
}
return i, true
}
}
return 0, false
}
func parseTriplet(val string) (Triplet, error) {
split := strings.Split(val, "/")
var v float64
var t time.Time
var q string
var err error
if len(split) > 0 && split[0] != "" {
v, err = strconv.ParseFloat(split[0], 64)
if err != nil {
return Triplet{}, err
}
}
if len(split) > 1 && split[1] != "" {
t, err = parseTime(split[1])
if err != nil {
return Triplet{}, err
}
}
if len(split) > 2 && split[2] != "" {
q = split[2]
}
return Triplet{
Value: v,
Time: t,
Quality: q,
}, nil
}
func parseTime(s string) (time.Time, error) {
if s == "" {
return time.Time{}, nil
}
var modifier time.Duration
if strings.Contains(s, "24:00:00") {
s = strings.Replace(s, "24:00:00", "00:00:00", 1)
modifier = 24 * time.Hour
}
t, err := time.Parse(gs2TimeLayout, s)
return t.Add(modifier), err
}
func parseDuration(s string) (time.Duration, error) {
split := strings.Split(s, ".")
tp := strings.Split(split[1], ":")
var err error
var hours int
var minutes int
var seconds int
if hours, err = strconv.Atoi(tp[0]); err != nil {
return 0, err
}
if minutes, err = strconv.Atoi(tp[1]); err != nil {
return 0, err
}
if seconds, err = strconv.Atoi(tp[2]); err != nil {
return 0, err
}
return time.Duration(hours)*time.Hour + time.Duration(minutes)*time.Minute + time.Duration(seconds)*time.Second, nil
}