-
Notifications
You must be signed in to change notification settings - Fork 2
/
timeserie.go
60 lines (53 loc) · 1.3 KB
/
timeserie.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
package ops
import (
"context"
"time"
"github.com/licaonfee/selina"
"github.com/licaonfee/tserie"
)
var _ selina.Worker = (*TimeSerie)(nil)
// TimeSerieOptions customize optiosn for generation
type TimeSerieOptions struct {
Start time.Time
Stop time.Time
Step time.Duration
Generator func(time.Time) float64
WriteFormat selina.Marshaler
}
// TimeSerie generate time and values in a given time range
type TimeSerie struct {
opts TimeSerieOptions
}
// Process generate timeseries and put it out in a channel
func (t *TimeSerie) Process(ctx context.Context, args selina.ProcessArgs) error {
defer close(args.Output)
ts := tserie.NewTimeIterator(t.opts.Start, t.opts.Stop, t.opts.Step, t.opts.Generator)
if t.opts.WriteFormat == nil {
t.opts.WriteFormat = selina.DefaultMarshaler
}
for {
select {
case _, ok := <-args.Input:
if !ok {
return nil
}
default:
if !ts.Next() {
return nil
}
b, err := t.opts.WriteFormat(ts.Item())
if err != nil {
return err
}
buff := selina.GetBuffer()
buff.Write(b)
if err := selina.SendContext(ctx, buff, args.Output); err != nil {
return err
}
}
}
}
// NewTimeSerie create a new TimeSerie generator with given options
func NewTimeSerie(opts TimeSerieOptions) *TimeSerie {
return &TimeSerie{opts: opts}
}