summaryrefslogtreecommitdiff
path: root/encode.go
diff options
context:
space:
mode:
authorLuke Shumaker <lukeshu@datawire.io>2022-08-16 20:14:10 -0600
committerLuke Shumaker <lukeshu@datawire.io>2022-08-16 20:15:38 -0600
commit48d7aa22ba239e4413cb7bd86e1c7ce3f64832c3 (patch)
treeb7ce019adc1f82446feae6629b2dc361ddcbe058 /encode.go
parent9f75bb80b99f94c5c87582acb99e57c232caf01d (diff)
encode: Don't use generics for encodeString
Diffstat (limited to 'encode.go')
-rw-r--r--encode.go27
1 files changed, 19 insertions, 8 deletions
diff --git a/encode.go b/encode.go
index af7c57e..f6f8f0e 100644
--- a/encode.go
+++ b/encode.go
@@ -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})
}