diff options
Diffstat (limited to 'encode.go')
-rw-r--r-- | encode.go | 27 |
1 files changed, 19 insertions, 8 deletions
@@ -15,6 +15,7 @@ import ( "sort" "strconv" "strings" + "unicode/utf8" "unsafe" ) @@ -145,7 +146,7 @@ func encode(w io.Writer, val reflect.Value, quote bool, cycleDepth uint, cycleSe SourceFunc: "MarshalText", }}) } - encodeString(w, text) + encodeStringFromBytes(w, text) default: switch val.Kind() { @@ -201,10 +202,10 @@ func encode(w io.Writer, val reflect.Value, quote bool, cycleDepth uint, cycleSe } else { if quote { var buf bytes.Buffer - encodeString(&buf, val.String()) - encodeString(w, buf.Bytes()) + encodeStringFromString(&buf, val.String()) + encodeStringFromBytes(w, buf.Bytes()) } else { - encodeString(w, val.String()) + encodeStringFromString(w, val.String()) } } case reflect.Interface: @@ -228,7 +229,7 @@ func encode(w io.Writer, val reflect.Value, quote bool, cycleDepth uint, cycleSe encodeWriteByte(w, ',') } empty = false - encodeString(w, field.Name) + encodeStringFromString(w, field.Name) encodeWriteByte(w, ':') encode(w, fVal, field.Quote, cycleDepth, cycleSeen) } @@ -270,7 +271,7 @@ func encode(w io.Writer, val reflect.Value, quote bool, cycleDepth uint, cycleSe } if !strings.HasPrefix(kStr, `"`) { k.Reset() - encodeString(&k, kStr) + encodeStringFromString(&k, kStr) kStr = k.String() } kvs[i].K = kStr @@ -369,10 +370,20 @@ func encode(w io.Writer, val reflect.Value, quote bool, cycleDepth uint, cycleSe } } -func encodeString[T interface{ []byte | string }](w io.Writer, str T) { +func encodeStringFromString(w io.Writer, str string) { + encodeWriteByte(w, '"') + for _, c := range str { + if _, err := writeStringChar(w, c, BackslashEscapeNone, nil); err != nil { + panic(encodeError{err}) + } + } + encodeWriteByte(w, '"') +} + +func encodeStringFromBytes(w io.Writer, str []byte) { encodeWriteByte(w, '"') for i := 0; i < len(str); { - c, size := decodeRune(str[i:]) + c, size := utf8.DecodeRune(str[i:]) if _, err := writeStringChar(w, c, BackslashEscapeNone, nil); err != nil { panic(encodeError{err}) } |