mirror of
https://github.com/protocolbuffers/protobuf-go.git
synced 2025-03-31 10:20:48 +00:00
Previous calls to indexNeedEscape with a type conversion from []byte to string incurs allocation. Make 2 different calls instead, one for string and one for bytes. Type converting string to []byte does not incur extra allocation, however, the benchmark results still show it to be slower by ~3% for textpb and 6+% for jsonpb, hence decided to go with 2 separate calls instead. Results over current head: name old time/op new time/op delta TextEncode-4 18.1ms ± 2% 18.3ms ± 2% ~ (p=0.065 n=10+9) TextDecode-4 233ms ± 3% 102ms ± 1% -56.34% (p=0.000 n=9+10) JSONEncode-4 10.4ms ± 2% 10.5ms ± 0% +0.56% (p=0.019 n=9+9) JSONDecode-4 870ms ± 2% 354ms ± 4% -59.33% (p=0.000 n=9+10) name old alloc/op new alloc/op delta TextEncode-4 28.9MB ± 0% 28.9MB ± 0% +0.00% (p=0.000 n=10+9) TextDecode-4 1.16GB ± 0% 0.03GB ± 0% -97.44% (p=0.000 n=9+10) JSONEncode-4 3.94MB ± 0% 3.94MB ± 0% +0.00% (p=0.000 n=10+10) JSONDecode-4 3.35GB ± 0% 0.01GB ± 0% -99.83% (p=0.000 n=10+10) name old allocs/op new allocs/op delta TextEncode-4 73.5k ± 0% 73.5k ± 0% ~ (all equal) TextDecode-4 278k ± 0% 255k ± 0% -8.26% (p=0.000 n=9+10) JSONEncode-4 63.8k ± 0% 63.8k ± 0% ~ (all equal) JSONDecode-4 247k ± 0% 210k ± 0% -14.92% (p=0.000 n=10+10) Change-Id: Ibc64e9a7827ec1fffa213eb79f60497950203700 Reviewed-on: https://go-review.googlesource.com/c/protobuf/+/172239 Reviewed-by: Joe Tsai <thebrokentoaster@gmail.com>
245 lines
7.1 KiB
Go
245 lines
7.1 KiB
Go
// Copyright 2018 The Go Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style
|
|
// license that can be found in the LICENSE file.
|
|
|
|
package text
|
|
|
|
import (
|
|
"bytes"
|
|
"io"
|
|
"math"
|
|
"math/bits"
|
|
"strconv"
|
|
"strings"
|
|
"unicode"
|
|
"unicode/utf16"
|
|
"unicode/utf8"
|
|
|
|
"github.com/golang/protobuf/v2/internal/errors"
|
|
)
|
|
|
|
func (p *encoder) marshalString(v Value) error {
|
|
var err error
|
|
p.out, err = appendString(p.out, v, p.outputASCII)
|
|
return err
|
|
}
|
|
func appendString(out []byte, v Value, outputASCII bool) ([]byte, error) {
|
|
if v.Type() != String {
|
|
return nil, errors.New("invalid type %v, expected string", v.Type())
|
|
}
|
|
if len(v.raw) > 0 {
|
|
return append(out, v.raw...), nil
|
|
}
|
|
in := v.String()
|
|
|
|
out = append(out, '"')
|
|
i := indexNeedEscapeInString(in)
|
|
in, out = in[i:], append(out, in[:i]...)
|
|
for len(in) > 0 {
|
|
switch r, n := utf8.DecodeRuneInString(in); {
|
|
case r == utf8.RuneError && n == 1:
|
|
// We do not report invalid UTF-8 because strings in the text format
|
|
// are used to represent both the proto string and bytes type.
|
|
r = rune(in[0])
|
|
fallthrough
|
|
case r < ' ' || r == '"' || r == '\\':
|
|
out = append(out, '\\')
|
|
switch r {
|
|
case '"', '\\':
|
|
out = append(out, byte(r))
|
|
case '\n':
|
|
out = append(out, 'n')
|
|
case '\r':
|
|
out = append(out, 'r')
|
|
case '\t':
|
|
out = append(out, 't')
|
|
default:
|
|
out = append(out, 'x')
|
|
out = append(out, "00"[1+(bits.Len32(uint32(r))-1)/4:]...)
|
|
out = strconv.AppendUint(out, uint64(r), 16)
|
|
}
|
|
in = in[n:]
|
|
case outputASCII && r >= utf8.RuneSelf:
|
|
out = append(out, '\\')
|
|
if r <= math.MaxUint16 {
|
|
out = append(out, 'u')
|
|
out = append(out, "0000"[1+(bits.Len32(uint32(r))-1)/4:]...)
|
|
out = strconv.AppendUint(out, uint64(r), 16)
|
|
} else {
|
|
out = append(out, 'U')
|
|
out = append(out, "00000000"[1+(bits.Len32(uint32(r))-1)/4:]...)
|
|
out = strconv.AppendUint(out, uint64(r), 16)
|
|
}
|
|
in = in[n:]
|
|
default:
|
|
i := indexNeedEscapeInString(in[n:])
|
|
in, out = in[n+i:], append(out, in[:n+i]...)
|
|
}
|
|
}
|
|
out = append(out, '"')
|
|
return out, nil
|
|
}
|
|
|
|
func (p *decoder) unmarshalString() (Value, error) {
|
|
v, n, err := consumeString(p.in)
|
|
p.consume(n)
|
|
return v, err
|
|
}
|
|
func consumeString(in []byte) (Value, int, error) {
|
|
var nerr errors.NonFatal
|
|
in0 := in
|
|
if len(in) == 0 {
|
|
return Value{}, 0, io.ErrUnexpectedEOF
|
|
}
|
|
quote := in[0]
|
|
if in[0] != '"' && in[0] != '\'' {
|
|
return Value{}, 0, newSyntaxError("invalid character %q at start of string", in[0])
|
|
}
|
|
in = in[1:]
|
|
i := indexNeedEscapeInBytes(in)
|
|
in, out := in[i:], in[:i:i] // set cap to prevent mutations
|
|
for len(in) > 0 {
|
|
switch r, n := utf8.DecodeRune(in); {
|
|
case r == utf8.RuneError && n == 1:
|
|
nerr.AppendInvalidUTF8("")
|
|
in, out = in[1:], append(out, in[0]) // preserve invalid byte
|
|
case r == 0 || r == '\n':
|
|
return Value{}, 0, newSyntaxError("invalid character %q in string", r)
|
|
case r == rune(quote):
|
|
in = in[1:]
|
|
n := len(in0) - len(in)
|
|
v := rawValueOf(string(out), in0[:n:n])
|
|
return v, n, nerr.E
|
|
case r == '\\':
|
|
if len(in) < 2 {
|
|
return Value{}, 0, io.ErrUnexpectedEOF
|
|
}
|
|
switch r := in[1]; r {
|
|
case '"', '\'', '\\', '?':
|
|
in, out = in[2:], append(out, r)
|
|
case 'a':
|
|
in, out = in[2:], append(out, '\a')
|
|
case 'b':
|
|
in, out = in[2:], append(out, '\b')
|
|
case 'n':
|
|
in, out = in[2:], append(out, '\n')
|
|
case 'r':
|
|
in, out = in[2:], append(out, '\r')
|
|
case 't':
|
|
in, out = in[2:], append(out, '\t')
|
|
case 'v':
|
|
in, out = in[2:], append(out, '\v')
|
|
case 'f':
|
|
in, out = in[2:], append(out, '\f')
|
|
case '0', '1', '2', '3', '4', '5', '6', '7':
|
|
// One, two, or three octal characters.
|
|
n := len(in[1:]) - len(bytes.TrimLeft(in[1:], "01234567"))
|
|
if n > 3 {
|
|
n = 3
|
|
}
|
|
v, err := strconv.ParseUint(string(in[1:1+n]), 8, 8)
|
|
if err != nil {
|
|
return Value{}, 0, newSyntaxError("invalid octal escape code %q in string", in[:1+n])
|
|
}
|
|
in, out = in[1+n:], append(out, byte(v))
|
|
case 'x':
|
|
// One or two hexadecimal characters.
|
|
n := len(in[2:]) - len(bytes.TrimLeft(in[2:], "0123456789abcdefABCDEF"))
|
|
if n > 2 {
|
|
n = 2
|
|
}
|
|
v, err := strconv.ParseUint(string(in[2:2+n]), 16, 8)
|
|
if err != nil {
|
|
return Value{}, 0, newSyntaxError("invalid hex escape code %q in string", in[:2+n])
|
|
}
|
|
in, out = in[2+n:], append(out, byte(v))
|
|
case 'u', 'U':
|
|
// Four or eight hexadecimal characters
|
|
n := 6
|
|
if r == 'U' {
|
|
n = 10
|
|
}
|
|
if len(in) < n {
|
|
return Value{}, 0, io.ErrUnexpectedEOF
|
|
}
|
|
v, err := strconv.ParseUint(string(in[2:n]), 16, 32)
|
|
if utf8.MaxRune < v || err != nil {
|
|
return Value{}, 0, newSyntaxError("invalid Unicode escape code %q in string", in[:n])
|
|
}
|
|
in = in[n:]
|
|
|
|
r := rune(v)
|
|
if utf16.IsSurrogate(r) {
|
|
if len(in) < 6 {
|
|
return Value{}, 0, io.ErrUnexpectedEOF
|
|
}
|
|
v, err := strconv.ParseUint(string(in[2:6]), 16, 16)
|
|
r = utf16.DecodeRune(r, rune(v))
|
|
if in[0] != '\\' || in[1] != 'u' || r == unicode.ReplacementChar || err != nil {
|
|
return Value{}, 0, newSyntaxError("invalid Unicode escape code %q in string", in[:6])
|
|
}
|
|
in = in[6:]
|
|
}
|
|
out = append(out, string(r)...)
|
|
default:
|
|
return Value{}, 0, newSyntaxError("invalid escape code %q in string", in[:2])
|
|
}
|
|
default:
|
|
i := indexNeedEscapeInBytes(in[n:])
|
|
in, out = in[n+i:], append(out, in[:n+i]...)
|
|
}
|
|
}
|
|
return Value{}, 0, io.ErrUnexpectedEOF
|
|
}
|
|
|
|
// unmarshalStrings unmarshals multiple strings.
|
|
// This differs from unmarshalString since the text format allows
|
|
// multiple back-to-back string literals where they are semantically treated
|
|
// as a single large string with all values concatenated.
|
|
//
|
|
// E.g., `"foo" "bar" "baz"` => ValueOf("foobarbaz")
|
|
func (p *decoder) unmarshalStrings() (Value, error) {
|
|
// Note that the ending quote is sufficient to unambiguously mark the end
|
|
// of a string. Thus, the text grammar does not require intervening
|
|
// whitespace or control characters in-between strings.
|
|
// Thus, the following is valid:
|
|
// `"foo"'bar'"baz"` => ValueOf("foobarbaz")
|
|
b := p.in
|
|
var ss []string
|
|
for len(p.in) > 0 && (p.in[0] == '"' || p.in[0] == '\'') {
|
|
v, err := p.unmarshalString()
|
|
if !p.nerr.Merge(err) {
|
|
return Value{}, err
|
|
}
|
|
ss = append(ss, v.String())
|
|
}
|
|
b = b[:len(b)-len(p.in)]
|
|
return rawValueOf(strings.Join(ss, ""), b[:len(b):len(b)]), nil
|
|
}
|
|
|
|
// indexNeedEscapeInString returns the index of the character that needs
|
|
// escaping. If no characters need escaping, this returns the input length.
|
|
func indexNeedEscapeInString(s string) int {
|
|
for i := 0; i < len(s); i++ {
|
|
if c := s[i]; c < ' ' || c == '"' || c == '\'' || c == '\\' || c >= utf8.RuneSelf {
|
|
return i
|
|
}
|
|
}
|
|
return len(s)
|
|
}
|
|
|
|
// indexNeedEscapeInBytes returns the index of the character that needs
|
|
// escaping. If no characters need escaping, this returns the input length.
|
|
// TODO: Remove this duplicate function when https://golang.org/issue/31506 gets
|
|
// resolved.
|
|
func indexNeedEscapeInBytes(b []byte) int {
|
|
for i := 0; i < len(b); {
|
|
c, size := utf8.DecodeRune(b[i:])
|
|
if c < ' ' || c == '"' || c == '\'' || c == '\\' || c >= utf8.RuneSelf {
|
|
return i
|
|
}
|
|
i += size
|
|
}
|
|
return len(b)
|
|
}
|