forked from anacrolix/torrent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsegments.go
63 lines (54 loc) · 1 KB
/
segments.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
package segments
type Int = int64
type Length = Int
func min(i Int, rest ...Int) Int {
ret := i
for _, i := range rest {
if i < ret {
ret = i
}
}
return ret
}
type Extent struct {
Start, Length Int
}
func (e Extent) End() Int {
return e.Start + e.Length
}
type (
Callback = func(int, Extent) bool
LengthIter = func() (Length, bool)
)
func Scan(haystack LengthIter, needle Extent, callback Callback) bool {
i := 0
for needle.Length != 0 {
l, ok := haystack()
if !ok {
return false
}
if needle.Start < l || needle.Start == l && l == 0 {
e1 := Extent{
Start: needle.Start,
Length: min(l, needle.End()) - needle.Start,
}
if e1.Length >= 0 {
if !callback(i, e1) {
return true
}
needle.Start = 0
needle.Length -= e1.Length
}
} else {
needle.Start -= l
}
i++
}
return true
}
func LocaterFromLengthIter(li LengthIter) Locater {
return func(e Extent, c Callback) bool {
return Scan(li, e, c)
}
}
type Locater func(Extent, Callback) bool