-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmatches.go
82 lines (60 loc) · 1.97 KB
/
matches.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
package grammarbot
// CorrectMatchesBytes - returns corrected text with first replacements in matches
func CorrectMatchesBytes(text []byte, matches []*Match) []byte {
if len(matches) < 1 {
return nil
}
var (
i int
extraSize int
)
for i = 0; i < len(matches); i++ {
extraSize += len(matches[i].Replacements[0].Value) - matches[i].Length
}
buf := make([]byte, len(text) + extraSize)
currentPos := 0
nextPos := matches[0].Offset
offset := copy(buf[:], text[currentPos:nextPos])
offset += copy(buf[offset:], matches[0].Replacements[0].Value)
for i = 1; i < len(matches); i++ {
currentPos = matches[i - 1].Offset + matches[i - 1].Length
nextPos = matches[i].Offset
offset += copy(buf[offset:], text[currentPos:nextPos])
offset += copy(buf[offset:], matches[i].Replacements[0].Value)
}
currentPos = matches[i - 1].Offset + matches[i - 1].Length
nextPos = len(text)
copy(buf[offset:], text[currentPos:nextPos])
return buf
}
// CorrectMatches - returns corrected text with first replacements in matches
func CorrectMatches(text string, matches []*Match) string {
/*
s2b cast creates undefined behavior (runtime might ask for cap), so here's copy/paste from FixMatchesBytes
*/
if len(matches) < 1 {
return ""
}
var (
i int
extraSize int
)
for i = 0; i < len(matches); i++ {
extraSize += len(matches[i].Replacements[0].Value) - matches[i].Length
}
buf := make([]byte, len(text) + extraSize)
currentPos := 0
nextPos := matches[0].Offset
offset := copy(buf[:], text[currentPos:nextPos])
offset += copy(buf[offset:], matches[0].Replacements[0].Value)
for i = 1; i < len(matches); i++ {
currentPos = matches[i - 1].Offset + matches[i - 1].Length
nextPos = matches[i].Offset
offset += copy(buf[offset:], text[currentPos:nextPos])
offset += copy(buf[offset:], matches[i].Replacements[0].Value)
}
currentPos = matches[i - 1].Offset + matches[i - 1].Length
nextPos = len(text)
copy(buf[offset:], text[currentPos:nextPos])
return string(buf)
}