forked from loov/lensm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcode_lineset.go
86 lines (72 loc) · 1.81 KB
/
code_lineset.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package main
import (
"sort"
"golang.org/x/exp/slices"
)
// LineSet represents a set of needed lines.
type LineSet struct {
list []int
}
// Add adds line to the needed set.
func (rs *LineSet) Add(line int) {
if len(rs.list) == 0 {
rs.list = append(rs.list, line)
return
}
at := sort.SearchInts(rs.list, line)
if at >= len(rs.list) {
rs.list = append(rs.list, line)
} else if rs.list[at] != line {
rs.list = slices.Insert(rs.list, at, line)
}
}
// Ranges converts line set to line ranges and adds context for extra information.
func (rs *LineSet) Ranges(context int) []LineRange {
if len(rs.list) == 0 {
return nil
}
var all []LineRange
current := LineRange{From: rs.list[0] - context, To: rs.list[0] + context + 1}
if current.From < 1 {
current.From = 1
}
for _, line := range rs.list {
if line-context <= current.To {
current.To = line + context + 1
} else {
all = append(all, current)
current = LineRange{From: line - context, To: line + context + 1}
}
}
all = append(all, current)
return all
}
// RangesZero returns a ranges without expanding by context.
func (rs *LineSet) RangesZero() []LineRange {
if len(rs.list) == 0 {
return nil
}
var all []LineRange
current := LineRange{From: rs.list[0], To: rs.list[0] + 1}
for _, line := range rs.list {
if line <= current.To {
current.To = line + 1
} else {
all = append(all, current)
current = LineRange{From: line, To: line + 1}
}
}
all = append(all, current)
return all
}
// LineRange represents a list of lines.
type LineRange struct{ From, To int }
// LineRangesContain checks whether line a or line b is contained in the ranges.
func LineRangesContain(ranges []LineRange, a, b int) bool {
for _, r := range ranges {
if (r.From <= a && a < r.To) || (r.From <= b && b < r.To) {
return true
}
}
return false
}