| | package oncall |
| |
|
| | import ( |
| | "fmt" |
| | "time" |
| | ) |
| |
|
| | |
| | type TimeIterator struct { |
| | t, start, end, step int64 |
| |
|
| | nextStep int64 |
| | init bool |
| |
|
| | sub []SubIterator |
| | } |
| |
|
| | |
| | type SubIterator interface { |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | Process(t int64) int64 |
| |
|
| | |
| | Done() |
| | } |
| |
|
| | |
| | type Startable interface { |
| | |
| | StartUnix() int64 |
| | } |
| |
|
| | |
| | type NextFunc func(int64) int64 |
| |
|
| | |
| | func (fn NextFunc) Process(t int64) int64 { return fn(t) } |
| |
|
| | |
| | func (fn NextFunc) Done() {} |
| |
|
| | |
| | func NewTimeIterator(start, end time.Time, step time.Duration) *TimeIterator { |
| | step = step.Truncate(time.Second) |
| | stepUnix := step.Nanoseconds() / int64(time.Second) |
| | start = start.Truncate(step) |
| | end = end.Truncate(step) |
| |
|
| | return &TimeIterator{ |
| | step: stepUnix, |
| | start: start.Unix(), |
| | end: end.Unix(), |
| | nextStep: start.Unix(), |
| | } |
| | } |
| |
|
| | |
| | func (iter *TimeIterator) Register(sub SubIterator) { iter.sub = append(iter.sub, sub) } |
| |
|
| | |
| | func (iter *TimeIterator) Next() bool { |
| | if !iter.init { |
| | for _, s := range iter.sub { |
| | st, ok := s.(Startable) |
| | if !ok { |
| | continue |
| | } |
| | start := st.StartUnix() |
| | start = start - start%iter.step |
| | if start != 0 && start < iter.start { |
| | iter.start = start |
| | } |
| |
|
| | } |
| | iter.nextStep = iter.start |
| | iter.init = true |
| | } |
| | if iter.t >= iter.end { |
| | return false |
| | } |
| | iter.t = iter.nextStep |
| | iter.nextStep = 0 |
| |
|
| | var nextStep int64 |
| | for _, sub := range iter.sub { |
| | nextStep = sub.Process(iter.t) |
| | if nextStep > 0 && nextStep <= iter.t { |
| | panic(fmt.Sprintf("nextStep was not in the future; got %d; want > %d (start=%d, end=%d)\n%#v", nextStep, iter.t, iter.start, iter.end, sub)) |
| | } |
| | if nextStep == -1 { |
| | |
| | nextStep = iter.end |
| | } |
| | if iter.nextStep == 0 { |
| | |
| | iter.nextStep = nextStep |
| | } else if nextStep > 0 && nextStep < iter.nextStep { |
| | |
| | iter.nextStep = nextStep |
| | } |
| | } |
| |
|
| | if iter.nextStep == 0 { |
| | |
| | iter.nextStep = iter.t + iter.step |
| | } else if iter.nextStep > iter.end { |
| | |
| | iter.nextStep = iter.end |
| | } |
| | return true |
| | } |
| |
|
| | |
| | func (iter *TimeIterator) Close() { |
| | for _, s := range iter.sub { |
| | s.Done() |
| | } |
| | } |
| |
|
| | |
| | func (iter *TimeIterator) Unix() int64 { return iter.t } |
| |
|
| | |
| | func (iter *TimeIterator) Start() time.Time { return time.Unix(iter.start, 0) } |
| |
|
| | |
| | func (iter *TimeIterator) End() time.Time { return time.Unix(iter.end, 0) } |
| |
|
| | |
| | func (iter *TimeIterator) Step() time.Duration { return time.Second * time.Duration(iter.step) } |
| |
|