|
package oncall |
|
|
|
import ( |
|
"fmt" |
|
"sync" |
|
"time" |
|
) |
|
|
|
var ( |
|
activeCalcValuePool = &sync.Pool{ |
|
New: func() interface{} { return make([]activeCalcValue, 0, 100) }, |
|
} |
|
) |
|
|
|
|
|
type ActiveCalculator struct { |
|
*TimeIterator |
|
|
|
states []activeCalcValue |
|
|
|
init bool |
|
active activeCalcValue |
|
changed bool |
|
} |
|
type activeCalcValue struct { |
|
T int64 |
|
IsStart bool |
|
} |
|
|
|
|
|
func (t *TimeIterator) NewActiveCalculator() *ActiveCalculator { |
|
act := &ActiveCalculator{ |
|
TimeIterator: t, |
|
states: activeCalcValuePool.Get().([]activeCalcValue), |
|
} |
|
t.Register(act) |
|
|
|
return act |
|
} |
|
|
|
func (act *ActiveCalculator) StartUnix() (start int64) { |
|
if len(act.states) == 0 { |
|
return 0 |
|
} |
|
|
|
return act.states[0].T |
|
} |
|
|
|
|
|
func (act *ActiveCalculator) Init() *ActiveCalculator { |
|
if act.init { |
|
return act |
|
} |
|
act.init = true |
|
|
|
return act |
|
} |
|
|
|
|
|
|
|
|
|
|
|
func (act *ActiveCalculator) SetSpan(start, end time.Time) { |
|
if act.init { |
|
panic("cannot add spans after Init") |
|
} |
|
start = start.Truncate(act.Step()) |
|
end = end.Truncate(act.Step()) |
|
|
|
|
|
if !end.After(start) { |
|
return |
|
} |
|
|
|
|
|
if !end.After(act.Start()) { |
|
return |
|
} |
|
|
|
|
|
if !start.Before(act.End()) { |
|
return |
|
} |
|
|
|
act.set(start, true) |
|
act.set(end, false) |
|
} |
|
|
|
func (act *ActiveCalculator) set(t time.Time, isStart bool) { |
|
id := t.Unix() |
|
|
|
if len(act.states) == 0 && !isStart { |
|
panic("end registered before start") |
|
} |
|
if len(act.states) > 0 && isStart == act.states[len(act.states)-1].IsStart { |
|
panic("must not overlap shifts") |
|
} |
|
|
|
if len(act.states) > 0 && isStart && id == act.states[len(act.states)-1].T { |
|
|
|
act.states = act.states[:len(act.states)-1] |
|
return |
|
} |
|
|
|
if len(act.states) > 0 && id <= act.states[len(act.states)-1].T { |
|
panic(fmt.Sprintf("shifts must be registered in order: got %d, want > %d in %#v", id, act.states[len(act.states)-1].T, act.states)) |
|
} |
|
|
|
act.states = append(act.states, activeCalcValue{T: id, IsStart: isStart}) |
|
} |
|
|
|
|
|
func (act *ActiveCalculator) Process(t int64) int64 { |
|
if !act.init { |
|
panic("Init never called") |
|
} |
|
if len(act.states) == 0 { |
|
act.changed = false |
|
return -1 |
|
} |
|
|
|
val := act.states[0] |
|
act.changed = val.T == t |
|
if act.changed { |
|
act.active = val |
|
act.states = act.states[1:] |
|
if len(act.states) > 0 { |
|
return act.states[0].T |
|
} |
|
|
|
return -1 |
|
} |
|
|
|
return val.T |
|
} |
|
|
|
|
|
func (act *ActiveCalculator) Done() { |
|
|
|
activeCalcValuePool.Put(act.states[:0]) |
|
|
|
act.states = nil |
|
} |
|
|
|
|
|
func (act *ActiveCalculator) Active() bool { return act.active.IsStart } |
|
|
|
|
|
func (act *ActiveCalculator) Changed() bool { return act.changed } |
|
|