time: properly quote strings containing quotes and backslashes

Fixes #45391

Change-Id: I43ea597f6a9596a621ae7b63eb05440d5b9e2d8f
Reviewed-on: https://go-review.googlesource.com/c/go/+/307192
Reviewed-by: Emmanuel Odeke <emmanuel@orijtech.com>
Reviewed-by: Ian Lance Taylor <iant@golang.org>
Run-TryBot: Emmanuel Odeke <emmanuel@orijtech.com>
TryBot-Result: Go Bot <gobot@golang.org>
This commit is contained in:
Ahmet Aktürk 2021-04-05 22:05:05 +03:00 committed by Ian Lance Taylor
parent 2e6f39beb0
commit 1271e9a9cc
3 changed files with 34 additions and 1 deletions

View file

@ -129,3 +129,5 @@ var StdChunkNames = map[int]string{
stdFracSecond9 | 8<<stdArgShift: ".99999999",
stdFracSecond9 | 9<<stdArgShift: ".999999999",
}
var Quote = quote

View file

@ -689,7 +689,16 @@ type ParseError struct {
}
func quote(s string) string {
return "\"" + s + "\""
buf := make([]byte, 0, len(s)+2) // +2 for surrounding quotes
buf = append(buf, '"')
for _, c := range s {
if c == '"' || c == '\\' {
buf = append(buf, '\\')
}
buf = append(buf, string(c)...)
}
buf = append(buf, '"')
return string(buf)
}
// Error returns the string representation of a ParseError.

View file

@ -563,6 +563,10 @@ var parseErrorTests = []ParseErrorTest{
// invalid or mismatched day-of-year
{"Jan _2 002 2006", "Feb 4 034 2006", "day-of-year does not match day"},
{"Jan _2 002 2006", "Feb 4 004 2006", "day-of-year does not match month"},
// issue 45391.
{`"2006-01-02T15:04:05Z07:00"`, "0", `parsing time "0" as "\"2006-01-02T15:04:05Z07:00\"": cannot parse "0" as "\""`},
{RFC3339, "\"", `parsing time "\"" as "2006-01-02T15:04:05Z07:00": cannot parse "\"" as "2006"`},
}
func TestParseErrors(t *testing.T) {
@ -782,3 +786,21 @@ func TestParseYday(t *testing.T) {
}
}
}
// Issue 45391.
func TestQuote(t *testing.T) {
tests := []struct {
s, want string
}{
{`"`, `"\""`},
{`abc"xyz"`, `"abc\"xyz\""`},
{"", `""`},
{"abc", `"abc"`},
}
for _, tt := range tests {
if q := Quote(tt.s); q != tt.want {
t.Errorf("Quote(%q) = %q, want %q", tt.s, q, tt.want)
}
}
}