summaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorAndrew Gerrand <adg@golang.org>2013-11-01 11:18:49 +1100
committerAndrew Gerrand <adg@golang.org>2013-11-01 11:18:49 +1100
commite7652861790315292e4c15452ad3c199fbd115a4 (patch)
treeb653948e17346b8147ee43309e710f6f4ef8816d /src
parent6e54ffe4d2df38abe645935b8a045a3194fb88b8 (diff)
downloadgo-e7652861790315292e4c15452ad3c199fbd115a4.tar.gz
[release-branch.go1.2] strings: fix Replacer bug with prefix matches
??? CL 16880043 / 0eb6508d3e88 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 issue 6659 R=golang-dev, r CC=golang-dev https://codereview.appspot.com/16880043 ??? R=golang-dev CC=golang-dev https://codereview.appspot.com/20570044
Diffstat (limited to 'src')
-rw-r--r--src/pkg/strings/replace.go5
-rw-r--r--src/pkg/strings/replace_test.go11
2 files changed, 14 insertions, 2 deletions
diff --git a/src/pkg/strings/replace.go b/src/pkg/strings/replace.go
index f63b1792c..54c9323e0 100644
--- a/src/pkg/strings/replace.go
+++ b/src/pkg/strings/replace.go
@@ -364,17 +364,18 @@ func makeSingleStringReplacer(pattern string, value string) *singleStringReplace
func (r *singleStringReplacer) Replace(s string) string {
var buf []byte
- i := 0
+ i, matched := 0, false
for {
match := r.finder.next(s[i:])
if match == -1 {
break
}
+ matched = true
buf = append(buf, s[i:i+match]...)
buf = append(buf, r.value...)
i += match + len(r.finder.pattern)
}
- if buf == nil {
+ if !matched {
return s
}
buf = append(buf, s[i:]...)
diff --git a/src/pkg/strings/replace_test.go b/src/pkg/strings/replace_test.go
index d33dea95b..82e4b6ef0 100644
--- a/src/pkg/strings/replace_test.go
+++ b/src/pkg/strings/replace_test.go
@@ -261,10 +261,21 @@ func TestReplacer(t *testing.T) {
testCases = append(testCases,
testCase{abcMatcher, "", ""},
testCase{abcMatcher, "ab", "ab"},
+ testCase{abcMatcher, "abc", "[match]"},
testCase{abcMatcher, "abcd", "[match]d"},
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.
nop := NewReplacer()