]> Cypherpunks repositories - gostls13.git/commitdiff
time: properly quote strings containing quotes and backslashes
authorAhmet Aktürk <aakturk000@gmail.com>
Mon, 5 Apr 2021 19:05:05 +0000 (22:05 +0300)
committerIan Lance Taylor <iant@golang.org>
Tue, 6 Apr 2021 19:18:47 +0000 (19:18 +0000)
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>

src/time/export_test.go
src/time/format.go
src/time/format_test.go

index 0f2d21053a3489e6383d71c31ee1c115a978fc66..9baad60a92aaf3f7078936cc7009384295e388a5 100644 (file)
@@ -129,3 +129,5 @@ var StdChunkNames = map[int]string{
        stdFracSecond9 | 8<<stdArgShift: ".99999999",
        stdFracSecond9 | 9<<stdArgShift: ".999999999",
 }
+
+var Quote = quote
index 75860358722c98e03c5eb0da58dd6e83453933a9..9624752fb48de42c68f281d62df1dd8597030df3 100644 (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.
index 9e96d4a29568c527d83569fc44c1bdcc3d64a111..09d3f842e3b56deb77dcdcff0767ec1f1391c0d2 100644 (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)
+               }
+       }
+
+}