Commit 2d6a1399 authored by Brad Fitzpatrick's avatar Brad Fitzpatrick

strings: fix Replacer bug with prefix matches

singleStringReplacer had a bug where if a string was replaced
at the beginning and no output had yet been produced into the
temp buffer before matching ended, an invalid nil check (used
as a proxy for having matched anything) meant it always
returned its input.

Fixes #6659

R=golang-dev, r
CC=golang-dev
https://golang.org/cl/16880043
parent 17a03d86
...@@ -364,17 +364,18 @@ func makeSingleStringReplacer(pattern string, value string) *singleStringReplace ...@@ -364,17 +364,18 @@ func makeSingleStringReplacer(pattern string, value string) *singleStringReplace
func (r *singleStringReplacer) Replace(s string) string { func (r *singleStringReplacer) Replace(s string) string {
var buf []byte var buf []byte
i := 0 i, matched := 0, false
for { for {
match := r.finder.next(s[i:]) match := r.finder.next(s[i:])
if match == -1 { if match == -1 {
break break
} }
matched = true
buf = append(buf, s[i:i+match]...) buf = append(buf, s[i:i+match]...)
buf = append(buf, r.value...) buf = append(buf, r.value...)
i += match + len(r.finder.pattern) i += match + len(r.finder.pattern)
} }
if buf == nil { if !matched {
return s return s
} }
buf = append(buf, s[i:]...) buf = append(buf, s[i:]...)
......
...@@ -261,10 +261,21 @@ func TestReplacer(t *testing.T) { ...@@ -261,10 +261,21 @@ func TestReplacer(t *testing.T) {
testCases = append(testCases, testCases = append(testCases,
testCase{abcMatcher, "", ""}, testCase{abcMatcher, "", ""},
testCase{abcMatcher, "ab", "ab"}, testCase{abcMatcher, "ab", "ab"},
testCase{abcMatcher, "abc", "[match]"},
testCase{abcMatcher, "abcd", "[match]d"}, testCase{abcMatcher, "abcd", "[match]d"},
testCase{abcMatcher, "cabcabcdabca", "c[match][match]d[match]a"}, testCase{abcMatcher, "cabcabcdabca", "c[match][match]d[match]a"},
) )
// Issue 6659 cases (more single string replacer)
noHello := NewReplacer("Hello", "")
testCases = append(testCases,
testCase{noHello, "Hello", ""},
testCase{noHello, "Hellox", "x"},
testCase{noHello, "xHello", "x"},
testCase{noHello, "xHellox", "xx"},
)
// No-arg test cases. // No-arg test cases.
nop := NewReplacer() nop := NewReplacer()
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment