forked from zyedidia/sregx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.go
62 lines (53 loc) · 1.41 KB
/
util.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
package sregx
import (
"bytes"
"regexp"
)
// ReplaceAllComplementFunc returns a copy of b in which all parts that are not
// matched by re have been replaced by the return value of the function repl
// applied to the unmatched byte slice. In other words, b is split according
// to re, and all components of the split are replaced according to repl.
func ReplaceAllComplementFunc(re *regexp.Regexp, b []byte, repl func([]byte) []byte) []byte {
matches := re.FindAllIndex(b, -1)
buf := make([]byte, 0, len(b))
beg := 0
end := 0
for _, match := range matches {
end = match[0]
if match[1] != 0 {
buf = append(buf, repl(b[beg:end])...)
buf = append(buf, b[end:match[1]]...)
}
beg = match[1]
}
if end != len(b) {
buf = append(buf, repl(b[beg:])...)
}
return buf
}
// IndexN find index of n-th sep in b
func IndexN(b, sep []byte, n int) (index int) {
index, idx, sepLen := 0, -1, len(sep)
for i := 0; i < n; i++ {
if idx = bytes.Index(b, sep); idx == -1 {
break
}
b = b[idx+sepLen:]
index += idx
}
if idx == -1 {
index = -1
} else {
index += (n - 1) * sepLen
}
return
}
// ReplaceSlice returns a copy of b where the range start:end has been replaced
// with repl.
func ReplaceSlice(b []byte, start, end int, repl []byte) []byte {
dst := make([]byte, 0, len(b)-end+start+len(repl))
dst = append(dst, b[:start]...)
dst = append(dst, repl...)
dst = append(dst, b[end:]...)
return dst
}