2020-05-31 19:00:19 +08:00
|
|
|
package segments
|
|
|
|
|
|
|
|
import (
|
|
|
|
"sort"
|
|
|
|
)
|
|
|
|
|
|
|
|
func NewIndex(segments LengthIter) (ret Index) {
|
|
|
|
var start Length
|
|
|
|
for l, ok := segments(); ok; l, ok = segments() {
|
|
|
|
ret.segments = append(ret.segments, Extent{start, l})
|
|
|
|
start += l
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
type Index struct {
|
|
|
|
segments []Extent
|
|
|
|
}
|
|
|
|
|
|
|
|
func (me Index) iterSegments() func() (Length, bool) {
|
|
|
|
return func() (Length, bool) {
|
|
|
|
if len(me.segments) == 0 {
|
|
|
|
return 0, false
|
|
|
|
} else {
|
|
|
|
l := me.segments[0].Length
|
|
|
|
me.segments = me.segments[1:]
|
|
|
|
return l, true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-06-01 16:25:45 +08:00
|
|
|
func (me Index) Locate(e Extent, output Callback) bool {
|
2020-05-31 19:00:19 +08:00
|
|
|
first := sort.Search(len(me.segments), func(i int) bool {
|
|
|
|
_e := me.segments[i]
|
|
|
|
return _e.End() > e.Start
|
|
|
|
})
|
|
|
|
if first == len(me.segments) {
|
2020-06-01 16:25:45 +08:00
|
|
|
return false
|
2020-05-31 19:00:19 +08:00
|
|
|
}
|
|
|
|
e.Start -= me.segments[first].Start
|
|
|
|
me.segments = me.segments[first:]
|
2020-06-01 16:25:45 +08:00
|
|
|
return Scan(me.iterSegments(), e, func(i int, e Extent) bool {
|
2020-05-31 19:00:19 +08:00
|
|
|
return output(i+first, e)
|
|
|
|
})
|
|
|
|
}
|