-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreplace.go
More file actions
97 lines (88 loc) · 1.83 KB
/
replace.go
File metadata and controls
97 lines (88 loc) · 1.83 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
package sr
import "bytes"
// ReplaceSlice replaces b[i:] with the contents of replace, calling Extend if needed.
func ReplaceSlice(b []byte, i int, replace []byte) []byte {
n := len(b) - i
m := len(replace)
o := m - n
if o > 0 {
b = Extend(b, o)
}
copy(b[i:], replace)
if o < 0 {
b = Truncate(b, len(b)+o)
}
return b
}
// ReplaceSlice2 replaces b[i:j] with the contents of replace, calling Extend if needed.
func ReplaceSlice2(b []byte, i int, j int, replace []byte) []byte {
n := j - i
m := len(replace)
o := m - n
if o > 0 {
b = Extend(b, o)
}
copy(b[i+m:], b[j:])
if o < 0 {
b = Truncate(b, len(b)+o)
}
copy(b[i:], replace)
return b
}
// ReplaceSlice3 replaces b[:j] with the contents of replace, calling Extend if needed.
func ReplaceSlice3(b []byte, j int, replace []byte) []byte {
n := j
m := len(replace)
o := m - n
if o > 0 {
b = Extend(b, o)
}
copy(b[j+o:], b[j:])
if o < 0 {
b = Truncate(b, len(b)+o)
}
copy(b, replace)
return b
}
func Replace(b, find, replace []byte) []byte {
i := bytes.Index(b, find)
if i < 0 {
return b
}
n := len(find)
b = ReplaceSlice2(b, i, i+n, replace)
return b
}
func ReplaceAll(b, find, replace []byte) []byte {
n := len(find)
m := len(replace)
o := m - n
for i := bytes.Index(b, find); i < len(b); {
b = ReplaceSlice2(b, i, i+n, replace)
i += o
idx := bytes.Index(b[i:], find)
if idx < 0 {
break
}
i += idx
}
return b
}
func ReplaceFull(b, replace []byte) []byte { return ReplaceSlice2(b, 0, len(b), replace) }
func ReplacePrefix(b, find, replace []byte) []byte {
if !bytes.HasPrefix(b, find) {
return b
}
n := len(find)
b = ReplaceSlice2(b, 0, n, replace)
return b
}
func ReplaceSuffix(b, find, replace []byte) []byte {
if !bytes.HasSuffix(b, find) {
return b
}
n := len(b)
m := len(find)
b = ReplaceSlice2(b, n-m, n, replace)
return b
}