string.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. // Copyright 2018 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package text
  5. import (
  6. "bytes"
  7. "io"
  8. "math"
  9. "math/bits"
  10. "strconv"
  11. "strings"
  12. "unicode"
  13. "unicode/utf16"
  14. "unicode/utf8"
  15. "google.golang.org/protobuf/internal/errors"
  16. "google.golang.org/protobuf/internal/strs"
  17. )
  18. func (p *encoder) marshalString(v Value) error {
  19. var err error
  20. p.out, err = appendString(p.out, v, p.outputASCII)
  21. return err
  22. }
  23. func appendString(out []byte, v Value, outputASCII bool) ([]byte, error) {
  24. if v.Type() != String {
  25. return nil, errors.New("invalid type %v, expected string", v.Type())
  26. }
  27. if len(v.raw) > 0 {
  28. return append(out, v.raw...), nil
  29. }
  30. in := v.String()
  31. out = append(out, '"')
  32. i := indexNeedEscapeInString(in)
  33. in, out = in[i:], append(out, in[:i]...)
  34. for len(in) > 0 {
  35. switch r, n := utf8.DecodeRuneInString(in); {
  36. case r == utf8.RuneError && n == 1:
  37. // We do not report invalid UTF-8 because strings in the text format
  38. // are used to represent both the proto string and bytes type.
  39. r = rune(in[0])
  40. fallthrough
  41. case r < ' ' || r == '"' || r == '\\':
  42. out = append(out, '\\')
  43. switch r {
  44. case '"', '\\':
  45. out = append(out, byte(r))
  46. case '\n':
  47. out = append(out, 'n')
  48. case '\r':
  49. out = append(out, 'r')
  50. case '\t':
  51. out = append(out, 't')
  52. default:
  53. out = append(out, 'x')
  54. out = append(out, "00"[1+(bits.Len32(uint32(r))-1)/4:]...)
  55. out = strconv.AppendUint(out, uint64(r), 16)
  56. }
  57. in = in[n:]
  58. case outputASCII && r >= utf8.RuneSelf:
  59. out = append(out, '\\')
  60. if r <= math.MaxUint16 {
  61. out = append(out, 'u')
  62. out = append(out, "0000"[1+(bits.Len32(uint32(r))-1)/4:]...)
  63. out = strconv.AppendUint(out, uint64(r), 16)
  64. } else {
  65. out = append(out, 'U')
  66. out = append(out, "00000000"[1+(bits.Len32(uint32(r))-1)/4:]...)
  67. out = strconv.AppendUint(out, uint64(r), 16)
  68. }
  69. in = in[n:]
  70. default:
  71. i := indexNeedEscapeInString(in[n:])
  72. in, out = in[n+i:], append(out, in[:n+i]...)
  73. }
  74. }
  75. out = append(out, '"')
  76. return out, nil
  77. }
  78. func (p *decoder) unmarshalString() (Value, error) {
  79. v, n, err := consumeString(p.in)
  80. p.consume(n)
  81. return v, err
  82. }
  83. func consumeString(in []byte) (Value, int, error) {
  84. in0 := in
  85. if len(in) == 0 {
  86. return Value{}, 0, io.ErrUnexpectedEOF
  87. }
  88. quote := in[0]
  89. if in[0] != '"' && in[0] != '\'' {
  90. return Value{}, 0, newSyntaxError("invalid character %q at start of string", in[0])
  91. }
  92. in = in[1:]
  93. i := indexNeedEscapeInBytes(in)
  94. in, out := in[i:], in[:i:i] // set cap to prevent mutations
  95. for len(in) > 0 {
  96. switch r, n := utf8.DecodeRune(in); {
  97. case r == utf8.RuneError && n == 1:
  98. return Value{}, 0, newSyntaxError("invalid UTF-8 detected")
  99. case r == 0 || r == '\n':
  100. return Value{}, 0, newSyntaxError("invalid character %q in string", r)
  101. case r == rune(quote):
  102. in = in[1:]
  103. n := len(in0) - len(in)
  104. v := rawValueOf(string(out), in0[:n:n])
  105. return v, n, nil
  106. case r == '\\':
  107. if len(in) < 2 {
  108. return Value{}, 0, io.ErrUnexpectedEOF
  109. }
  110. switch r := in[1]; r {
  111. case '"', '\'', '\\', '?':
  112. in, out = in[2:], append(out, r)
  113. case 'a':
  114. in, out = in[2:], append(out, '\a')
  115. case 'b':
  116. in, out = in[2:], append(out, '\b')
  117. case 'n':
  118. in, out = in[2:], append(out, '\n')
  119. case 'r':
  120. in, out = in[2:], append(out, '\r')
  121. case 't':
  122. in, out = in[2:], append(out, '\t')
  123. case 'v':
  124. in, out = in[2:], append(out, '\v')
  125. case 'f':
  126. in, out = in[2:], append(out, '\f')
  127. case '0', '1', '2', '3', '4', '5', '6', '7':
  128. // One, two, or three octal characters.
  129. n := len(in[1:]) - len(bytes.TrimLeft(in[1:], "01234567"))
  130. if n > 3 {
  131. n = 3
  132. }
  133. v, err := strconv.ParseUint(string(in[1:1+n]), 8, 8)
  134. if err != nil {
  135. return Value{}, 0, newSyntaxError("invalid octal escape code %q in string", in[:1+n])
  136. }
  137. in, out = in[1+n:], append(out, byte(v))
  138. case 'x':
  139. // One or two hexadecimal characters.
  140. n := len(in[2:]) - len(bytes.TrimLeft(in[2:], "0123456789abcdefABCDEF"))
  141. if n > 2 {
  142. n = 2
  143. }
  144. v, err := strconv.ParseUint(string(in[2:2+n]), 16, 8)
  145. if err != nil {
  146. return Value{}, 0, newSyntaxError("invalid hex escape code %q in string", in[:2+n])
  147. }
  148. in, out = in[2+n:], append(out, byte(v))
  149. case 'u', 'U':
  150. // Four or eight hexadecimal characters
  151. n := 6
  152. if r == 'U' {
  153. n = 10
  154. }
  155. if len(in) < n {
  156. return Value{}, 0, io.ErrUnexpectedEOF
  157. }
  158. v, err := strconv.ParseUint(string(in[2:n]), 16, 32)
  159. if utf8.MaxRune < v || err != nil {
  160. return Value{}, 0, newSyntaxError("invalid Unicode escape code %q in string", in[:n])
  161. }
  162. in = in[n:]
  163. r := rune(v)
  164. if utf16.IsSurrogate(r) {
  165. if len(in) < 6 {
  166. return Value{}, 0, io.ErrUnexpectedEOF
  167. }
  168. v, err := strconv.ParseUint(string(in[2:6]), 16, 16)
  169. r = utf16.DecodeRune(r, rune(v))
  170. if in[0] != '\\' || in[1] != 'u' || r == unicode.ReplacementChar || err != nil {
  171. return Value{}, 0, newSyntaxError("invalid Unicode escape code %q in string", in[:6])
  172. }
  173. in = in[6:]
  174. }
  175. out = append(out, string(r)...)
  176. default:
  177. return Value{}, 0, newSyntaxError("invalid escape code %q in string", in[:2])
  178. }
  179. default:
  180. i := indexNeedEscapeInBytes(in[n:])
  181. in, out = in[n+i:], append(out, in[:n+i]...)
  182. }
  183. }
  184. return Value{}, 0, io.ErrUnexpectedEOF
  185. }
  186. // unmarshalStrings unmarshals multiple strings.
  187. // This differs from unmarshalString since the text format allows
  188. // multiple back-to-back string literals where they are semantically treated
  189. // as a single large string with all values concatenated.
  190. //
  191. // E.g., `"foo" "bar" "baz"` => ValueOf("foobarbaz")
  192. func (p *decoder) unmarshalStrings() (Value, error) {
  193. // Note that the ending quote is sufficient to unambiguously mark the end
  194. // of a string. Thus, the text grammar does not require intervening
  195. // whitespace or control characters in-between strings.
  196. // Thus, the following is valid:
  197. // `"foo"'bar'"baz"` => ValueOf("foobarbaz")
  198. b := p.in
  199. var ss []string
  200. for len(p.in) > 0 && (p.in[0] == '"' || p.in[0] == '\'') {
  201. v, err := p.unmarshalString()
  202. if err != nil {
  203. return Value{}, err
  204. }
  205. ss = append(ss, v.String())
  206. }
  207. b = b[:len(b)-len(p.in)]
  208. return rawValueOf(strings.Join(ss, ""), b[:len(b):len(b)]), nil
  209. }
  210. // indexNeedEscapeInString returns the index of the character that needs
  211. // escaping. If no characters need escaping, this returns the input length.
  212. func indexNeedEscapeInString(s string) int {
  213. for i := 0; i < len(s); i++ {
  214. if c := s[i]; c < ' ' || c == '"' || c == '\'' || c == '\\' || c >= utf8.RuneSelf {
  215. return i
  216. }
  217. }
  218. return len(s)
  219. }
  220. func indexNeedEscapeInBytes(b []byte) int { return indexNeedEscapeInString(strs.UnsafeString(b)) }