marshal: don't escape quotes unnecessarily (#991)
Only 3 consecutive quotation marks need to be quoted. We choose to quote all quotation marks in a sequence if there are 3 or more consecutive present. Fixes #990 --------- Co-authored-by: Thomas Pelletier <thomas@pelletier.dev>
This commit is contained in:
+15
-1
@@ -517,12 +517,26 @@ func (enc *Encoder) encodeQuotedString(multiline bool, b []byte, v string) []byt
|
|||||||
del = 0x7f
|
del = 0x7f
|
||||||
)
|
)
|
||||||
|
|
||||||
for _, r := range []byte(v) {
|
bv := []byte(v)
|
||||||
|
for i := 0; i < len(bv); i++ {
|
||||||
|
r := bv[i]
|
||||||
switch r {
|
switch r {
|
||||||
case '\\':
|
case '\\':
|
||||||
b = append(b, `\\`...)
|
b = append(b, `\\`...)
|
||||||
case '"':
|
case '"':
|
||||||
|
if multiline {
|
||||||
|
// Quotation marks do not need to be quoted in multiline strings unless
|
||||||
|
// it contains 3 consecutive. If 3+ quotes appear, quote all of them
|
||||||
|
// because it's visually better
|
||||||
|
if i+2 > len(bv) || bv[i+1] != '"' || bv[i+2] != '"' {
|
||||||
|
b = append(b, r)
|
||||||
|
} else {
|
||||||
|
b = append(b, `\"\"\"`...)
|
||||||
|
i += 2
|
||||||
|
}
|
||||||
|
} else {
|
||||||
b = append(b, `\"`...)
|
b = append(b, `\"`...)
|
||||||
|
}
|
||||||
case '\b':
|
case '\b':
|
||||||
b = append(b, `\b`...)
|
b = append(b, `\b`...)
|
||||||
case '\f':
|
case '\f':
|
||||||
|
|||||||
@@ -387,6 +387,54 @@ name = 'Alice'
|
|||||||
expected: `A = """
|
expected: `A = """
|
||||||
hello
|
hello
|
||||||
world"""
|
world"""
|
||||||
|
`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
desc: "multi-line quotation",
|
||||||
|
v: struct {
|
||||||
|
A string `toml:",multiline"`
|
||||||
|
}{
|
||||||
|
A: "hello\n\"world\"",
|
||||||
|
},
|
||||||
|
expected: `A = """
|
||||||
|
hello
|
||||||
|
"world""""
|
||||||
|
`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
desc: "multi-line triple quotation",
|
||||||
|
v: struct {
|
||||||
|
A string `toml:",multiline"`
|
||||||
|
}{
|
||||||
|
A: "hello\n\"\"\"world\"",
|
||||||
|
},
|
||||||
|
expected: `A = """
|
||||||
|
hello
|
||||||
|
\"\"\"world""""
|
||||||
|
`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
desc: "multi-line triple quotation",
|
||||||
|
v: struct {
|
||||||
|
A string `toml:",multiline"`
|
||||||
|
}{
|
||||||
|
A: "hello\n\"world\"\"\"",
|
||||||
|
},
|
||||||
|
expected: `A = """
|
||||||
|
hello
|
||||||
|
"world\"\"\""""
|
||||||
|
`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
desc: "multi-line sextuple quotation",
|
||||||
|
v: struct {
|
||||||
|
A string `toml:",multiline"`
|
||||||
|
}{
|
||||||
|
A: "hello\n\"\"\"\"\"\"world\"",
|
||||||
|
},
|
||||||
|
expected: `A = """
|
||||||
|
hello
|
||||||
|
\"\"\"\"\"\"world""""
|
||||||
`,
|
`,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|||||||
Reference in New Issue
Block a user