-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbytes.go
More file actions
120 lines (107 loc) · 2.45 KB
/
Copy pathbytes.go
File metadata and controls
120 lines (107 loc) · 2.45 KB
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
package ybase
import "bytes"
type Bytes []byte
// LineColumn calculates line number and column from offset.
func (b Bytes) LineColumn(offset int) (int, int, bool) {
if offset < 0 || offset >= len(b) {
return 0, 0, false
}
target := b[:offset]
xs := bytes.Split(target, []byte("\n"))
line := len(xs)
last := string(xs[len(xs)-1])
column := len(last) + 1
return line, column, true
}
// Offset calculates offset from line number and column.
func (b Bytes) Offset(line, column int) (int, bool) {
if line < 1 || column < 1 {
return 0, false
}
xs := bytes.Split(b, []byte("\n"))
if line-1 >= len(xs) {
return 0, false
}
lineRow := string(xs[line-1])
if column-1 >= len(lineRow) {
return 0, false
}
var offset int
for _, x := range xs[:line-1] {
offset += len(x)
}
offset += len(xs[:line-1]) - 1
offset += len([]byte(lineRow[:column]))
return offset, true
}
type ContextLine struct {
Linum int
Line []byte
}
type Context struct {
Target *ContextLine
Lines []*ContextLine
}
// Context retrieves lines before and after a specified line number.
//
// It returns the surrounding context, including the given number
// of lines before and after the specified line.
func (b Bytes) Context(line, count int) (*Context, bool) {
if line < 1 || count < 0 {
return nil, false
}
xs := bytes.Split(b, []byte("\n"))
if line-1 >= len(xs) {
return nil, false
}
target := &ContextLine{
Linum: line,
Line: xs[line-1],
}
lines := []*ContextLine{}
for linum := line - count; linum <= line+count; linum++ {
index := linum - 1
if 0 <= index && index < len(xs) {
lines = append(lines, &ContextLine{
Linum: linum,
Line: xs[index],
})
}
}
return &Context{
Target: target,
Lines: lines,
}, true
}
type Adjacency struct {
Linum int
Column int
Focus rune
String string
Line string
}
// Adjacency retrieves runes before and after a specified line and column.
func (b Bytes) Adjacency(line, column, count int) (*Adjacency, bool) {
if line < 1 || column < 1 || count < 0 {
return nil, false
}
xs := bytes.Split(b, []byte("\n"))
if line-1 >= len(xs) {
return nil, false
}
target := bytes.Runes(xs[line-1])
if column-1 >= len(target) {
return nil, false
}
focus := target[column-1]
start := max(column-1-count, 0)
end := min(column+count, len(target))
targetString := string(target[start:end])
return &Adjacency{
Linum: line,
Column: column,
Focus: focus,
String: targetString,
Line: string(target),
}, true
}