fix(encode): fall back from the literal multiline form when unsafe
Assisted-by: GLM 5.3
This commit is contained in:
@@ -267,6 +267,38 @@ func TestEncoderUseLiteralMultilineThresholdZero(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestEncoderLiteralMultilineFallsBackWhenUnsafe(t *testing.T) {
|
||||
// The literal form carries the value verbatim, so content it cannot
|
||||
// represent must fall back to the escaped basic string instead of
|
||||
// producing output that does not re-parse.
|
||||
cases := []struct {
|
||||
name string
|
||||
in string
|
||||
}{
|
||||
{"embedded delimiter", "before ''' after\nsecond line"},
|
||||
{"control character", "a\x01b\nsecond"},
|
||||
{"delete character", "a\x7fb\nsecond"},
|
||||
{"lone carriage return", "first\rsecond\nthird"},
|
||||
}
|
||||
for _, c := range cases {
|
||||
out, err := NewEncoder().UseLiteralMultiline(5).Marshal(map[string]any{"s": c.in})
|
||||
if err != nil {
|
||||
t.Fatalf("%s: marshal: %v", c.name, err)
|
||||
}
|
||||
if !bytes.HasPrefix(out, []byte("s = \"")) {
|
||||
t.Errorf("%s: expected the basic quoted form, got:\n%s", c.name, out)
|
||||
}
|
||||
re, err := Parse(out)
|
||||
if err != nil {
|
||||
t.Errorf("%s: re-parse: %v\ndoc:\n%s", c.name, err, out)
|
||||
continue
|
||||
}
|
||||
if re["s"] != c.in {
|
||||
t.Errorf("%s: round-trip changed the value: %q", c.name, re["s"])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// marshalerFunc adapts a plain function value to the Marshaler interface.
|
||||
// Tests use it to express "this field produces this TOML value" without a
|
||||
// dedicated struct definition.
|
||||
|
||||
Reference in New Issue
Block a user