api.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. /*
  2. * Copyright 2021 ByteDance Inc.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package sonic
  17. import (
  18. `io`
  19. `github.com/bytedance/sonic/ast`
  20. `github.com/bytedance/sonic/internal/rt`
  21. )
  22. // Config is a combination of sonic/encoder.Options and sonic/decoder.Options
  23. type Config struct {
  24. // EscapeHTML indicates encoder to escape all HTML characters
  25. // after serializing into JSON (see https://pkg.go.dev/encoding/json#HTMLEscape).
  26. // WARNING: This hurts performance A LOT, USE WITH CARE.
  27. EscapeHTML bool
  28. // SortMapKeys indicates encoder that the keys of a map needs to be sorted
  29. // before serializing into JSON.
  30. // WARNING: This hurts performance A LOT, USE WITH CARE.
  31. SortMapKeys bool
  32. // CompactMarshaler indicates encoder that the output JSON from json.Marshaler
  33. // is always compact and needs no validation
  34. CompactMarshaler bool
  35. // NoQuoteTextMarshaler indicates encoder that the output text from encoding.TextMarshaler
  36. // is always escaped string and needs no quoting
  37. NoQuoteTextMarshaler bool
  38. // NoNullSliceOrMap indicates encoder that all empty Array or Object are encoded as '[]' or '{}',
  39. // instead of 'null'
  40. NoNullSliceOrMap bool
  41. // UseInt64 indicates decoder to unmarshal an integer into an interface{} as an
  42. // int64 instead of as a float64.
  43. UseInt64 bool
  44. // UseNumber indicates decoder to unmarshal a number into an interface{} as a
  45. // json.Number instead of as a float64.
  46. UseNumber bool
  47. // UseUnicodeErrors indicates decoder to return an error when encounter invalid
  48. // UTF-8 escape sequences.
  49. UseUnicodeErrors bool
  50. // DisallowUnknownFields indicates decoder to return an error when the destination
  51. // is a struct and the input contains object keys which do not match any
  52. // non-ignored, exported fields in the destination.
  53. DisallowUnknownFields bool
  54. // CopyString indicates decoder to decode string values by copying instead of referring.
  55. CopyString bool
  56. // ValidateString indicates decoder and encoder to valid string values: decoder will return errors
  57. // when unescaped control chars(\u0000-\u001f) in the string value of JSON.
  58. ValidateString bool
  59. // NoValidateJSONMarshaler indicates that the encoder should not validate the output string
  60. // after encoding the JSONMarshaler to JSON.
  61. NoValidateJSONMarshaler bool
  62. // NoEncoderNewline indicates that the encoder should not add a newline after every message
  63. NoEncoderNewline bool
  64. }
  65. var (
  66. // ConfigDefault is the default config of APIs, aiming at efficiency and safety.
  67. ConfigDefault = Config{}.Froze()
  68. // ConfigStd is the standard config of APIs, aiming at being compatible with encoding/json.
  69. ConfigStd = Config{
  70. EscapeHTML : true,
  71. SortMapKeys: true,
  72. CompactMarshaler: true,
  73. CopyString : true,
  74. ValidateString : true,
  75. }.Froze()
  76. // ConfigFastest is the fastest config of APIs, aiming at speed.
  77. ConfigFastest = Config{
  78. NoQuoteTextMarshaler: true,
  79. NoValidateJSONMarshaler: true,
  80. }.Froze()
  81. )
  82. // API is a binding of specific config.
  83. // This interface is inspired by github.com/json-iterator/go,
  84. // and has same behaviors under equavilent config.
  85. type API interface {
  86. // MarshalToString returns the JSON encoding string of v
  87. MarshalToString(v interface{}) (string, error)
  88. // Marshal returns the JSON encoding bytes of v.
  89. Marshal(v interface{}) ([]byte, error)
  90. // MarshalIndent returns the JSON encoding bytes with indent and prefix.
  91. MarshalIndent(v interface{}, prefix, indent string) ([]byte, error)
  92. // UnmarshalFromString parses the JSON-encoded bytes and stores the result in the value pointed to by v.
  93. UnmarshalFromString(str string, v interface{}) error
  94. // Unmarshal parses the JSON-encoded string and stores the result in the value pointed to by v.
  95. Unmarshal(data []byte, v interface{}) error
  96. // NewEncoder create a Encoder holding writer
  97. NewEncoder(writer io.Writer) Encoder
  98. // NewDecoder create a Decoder holding reader
  99. NewDecoder(reader io.Reader) Decoder
  100. // Valid validates the JSON-encoded bytes and reports if it is valid
  101. Valid(data []byte) bool
  102. }
  103. // Encoder encodes JSON into io.Writer
  104. type Encoder interface {
  105. // Encode writes the JSON encoding of v to the stream, followed by a newline character.
  106. Encode(val interface{}) error
  107. // SetEscapeHTML specifies whether problematic HTML characters
  108. // should be escaped inside JSON quoted strings.
  109. // The default behavior NOT ESCAPE
  110. SetEscapeHTML(on bool)
  111. // SetIndent instructs the encoder to format each subsequent encoded value
  112. // as if indented by the package-level function Indent(dst, src, prefix, indent).
  113. // Calling SetIndent("", "") disables indentation
  114. SetIndent(prefix, indent string)
  115. }
  116. // Decoder decodes JSON from io.Read
  117. type Decoder interface {
  118. // Decode reads the next JSON-encoded value from its input and stores it in the value pointed to by v.
  119. Decode(val interface{}) error
  120. // Buffered returns a reader of the data remaining in the Decoder's buffer.
  121. // The reader is valid until the next call to Decode.
  122. Buffered() io.Reader
  123. // DisallowUnknownFields causes the Decoder to return an error when the destination is a struct
  124. // and the input contains object keys which do not match any non-ignored, exported fields in the destination.
  125. DisallowUnknownFields()
  126. // More reports whether there is another element in the current array or object being parsed.
  127. More() bool
  128. // UseNumber causes the Decoder to unmarshal a number into an interface{} as a Number instead of as a float64.
  129. UseNumber()
  130. }
  131. // Marshal returns the JSON encoding bytes of v.
  132. func Marshal(val interface{}) ([]byte, error) {
  133. return ConfigDefault.Marshal(val)
  134. }
  135. // MarshalString returns the JSON encoding string of v.
  136. func MarshalString(val interface{}) (string, error) {
  137. return ConfigDefault.MarshalToString(val)
  138. }
  139. // Unmarshal parses the JSON-encoded data and stores the result in the value pointed to by v.
  140. // NOTICE: This API copies given buffer by default,
  141. // if you want to pass JSON more efficiently, use UnmarshalString instead.
  142. func Unmarshal(buf []byte, val interface{}) error {
  143. return ConfigDefault.Unmarshal(buf, val)
  144. }
  145. // UnmarshalString is like Unmarshal, except buf is a string.
  146. func UnmarshalString(buf string, val interface{}) error {
  147. return ConfigDefault.UnmarshalFromString(buf, val)
  148. }
  149. // Get searches and locates the given path from src json,
  150. // and returns a ast.Node representing the partially json.
  151. //
  152. // Each path arg must be integer or string:
  153. // - Integer is target index(>=0), means searching current node as array.
  154. // - String is target key, means searching current node as object.
  155. //
  156. //
  157. // Notice: It expects the src json is **Well-formed** and **Immutable** when calling,
  158. // otherwise it may return unexpected result.
  159. // Considering memory safety, the returned JSON is **Copied** from the input
  160. func Get(src []byte, path ...interface{}) (ast.Node, error) {
  161. return GetCopyFromString(rt.Mem2Str(src), path...)
  162. }
  163. // GetFromString is same with Get except src is string.
  164. //
  165. // WARNING: The returned JSON is **Referenced** from the input.
  166. // Caching or long-time holding the returned node may cause OOM.
  167. // If your src is big, consider use GetFromStringCopy().
  168. func GetFromString(src string, path ...interface{}) (ast.Node, error) {
  169. return ast.NewSearcher(src).GetByPath(path...)
  170. }
  171. // GetCopyFromString is same with Get except src is string
  172. func GetCopyFromString(src string, path ...interface{}) (ast.Node, error) {
  173. return ast.NewSearcher(src).GetByPathCopy(path...)
  174. }
  175. // Valid reports whether data is a valid JSON encoding.
  176. func Valid(data []byte) bool {
  177. return ConfigDefault.Valid(data)
  178. }
  179. // Valid reports whether data is a valid JSON encoding.
  180. func ValidString(data string) bool {
  181. return ConfigDefault.Valid(rt.Str2Mem(data))
  182. }