-
Notifications
You must be signed in to change notification settings - Fork 0
/
linecalc.go
53 lines (43 loc) · 898 Bytes
/
linecalc.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
package bcl
import (
"fmt"
"sort"
)
type lineCalc struct {
lfs []int
}
func newLineCalc() *lineCalc {
lfs := make([]int, 0, 64)
return &lineCalc{lfs: lfs}
}
func (lc *lineCalc) add(s string, prefix int) {
for i, c := range s {
if c == '\n' {
lc.lfs = append(lc.lfs, prefix+i)
}
}
}
// lineColAt gives (line, column) pair for a given position.
// Note that pos starts at 0, while line and column start at 1.
func (lc *lineCalc) lineColAt(pos int) (int, int) {
j := sort.SearchInts(lc.lfs, pos)
if j == len(lc.lfs) {
if j == 0 {
return 1, pos + 1
}
return j + 1, pos - lc.lfs[j-1]
}
prevpos := -1
if j > 0 {
prevpos = lc.lfs[j-1]
}
return j + 1, pos - prevpos
}
func (lc *lineCalc) lineAt(pos int) int {
line, _ := lc.lineColAt(pos)
return line
}
func (lc *lineCalc) format(pos int) string {
l, p := lc.lineColAt(pos)
return fmt.Sprintf("%d:%d", l, p)
}