Skip to content

Commit c0a824a

Browse files
vdoblerrobpike
authored andcommitted
strconv: fix CanBackquote for invalid UTF-8
Make CanBackquote(invalid UTF-8) return false. Also add two test which show that CanBackquote reports true for strings containing a BOM. Fixes golang#7572. LGTM=r R=golang-codereviews, bradfitz, r CC=golang-codereviews https://golang.org/cl/111780045
1 parent deae10e commit c0a824a

File tree

2 files changed

+14
-3
lines changed

2 files changed

+14
-3
lines changed

src/pkg/strconv/quote.go

+10-3
Original file line numberDiff line numberDiff line change
@@ -143,9 +143,16 @@ func AppendQuoteRuneToASCII(dst []byte, r rune) []byte {
143143
// unchanged as a single-line backquoted string without control
144144
// characters other than space and tab.
145145
func CanBackquote(s string) bool {
146-
for i := 0; i < len(s); i++ {
147-
c := s[i]
148-
if (c < ' ' && c != '\t') || c == '`' || c == '\u007F' {
146+
for len(s) > 0 {
147+
r, wid := utf8.DecodeRuneInString(s)
148+
s = s[wid:]
149+
if wid > 1 {
150+
continue // All multibyte runes are correctly encoded and assumed printable.
151+
}
152+
if r == utf8.RuneError {
153+
return false
154+
}
155+
if (r < ' ' && r != '\t') || r == '`' || r == '\u007F' {
149156
return false
150157
}
151158
}

src/pkg/strconv/quote_test.go

+4
Original file line numberDiff line numberDiff line change
@@ -146,6 +146,10 @@ var canbackquotetests = []canBackquoteTest{
146146
{`ABCDEFGHIJKLMNOPQRSTUVWXYZ`, true},
147147
{`abcdefghijklmnopqrstuvwxyz`, true},
148148
{`☺`, true},
149+
{"\x80", false},
150+
{"a\xe0\xa0z", false},
151+
{"\ufeffabc", true},
152+
{"a\ufeffz", true},
149153
}
150154

151155
func TestCanBackquote(t *testing.T) {

0 commit comments

Comments
 (0)