api.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  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. )
  21. // Config is a combination of sonic/encoder.Options and sonic/decoder.Options
  22. type Config struct {
  23. // EscapeHTML indicates encoder to escape all HTML characters
  24. // after serializing into JSON (see https://pkg.go.dev/encoding/json#HTMLEscape).
  25. // WARNING: This hurts performance A LOT, USE WITH CARE.
  26. EscapeHTML bool
  27. // SortMapKeys indicates encoder that the keys of a map needs to be sorted
  28. // before serializing into JSON.
  29. // WARNING: This hurts performance A LOT, USE WITH CARE.
  30. SortMapKeys bool
  31. // CompactMarshaler indicates encoder that the output JSON from json.Marshaler
  32. // is always compact and needs no validation
  33. CompactMarshaler bool
  34. // NoQuoteTextMarshaler indicates encoder that the output text from encoding.TextMarshaler
  35. // is always escaped string and needs no quoting
  36. NoQuoteTextMarshaler bool
  37. // NoNullSliceOrMap indicates encoder that all empty Array or Object are encoded as '[]' or '{}',
  38. // instead of 'null'
  39. NoNullSliceOrMap bool
  40. // UseInt64 indicates decoder to unmarshal an integer into an interface{} as an
  41. // int64 instead of as a float64.
  42. UseInt64 bool
  43. // UseNumber indicates decoder to unmarshal a number into an interface{} as a
  44. // json.Number instead of as a float64.
  45. UseNumber bool
  46. // UseUnicodeErrors indicates decoder to return an error when encounter invalid
  47. // UTF-8 escape sequences.
  48. UseUnicodeErrors bool
  49. // DisallowUnknownFields indicates decoder to return an error when the destination
  50. // is a struct and the input contains object keys which do not match any
  51. // non-ignored, exported fields in the destination.
  52. DisallowUnknownFields bool
  53. // CopyString indicates decoder to decode string values by copying instead of referring.
  54. CopyString bool
  55. // ValidateString indicates decoder and encoder to valid string values: decoder will return errors
  56. // when unescaped control chars(\u0000-\u001f) in the string value of JSON.
  57. ValidateString bool
  58. // NoValidateJSONMarshaler indicates that the encoder should not validate the output string
  59. // after encoding the JSONMarshaler to JSON.
  60. NoValidateJSONMarshaler bool
  61. }
  62. var (
  63. // ConfigDefault is the default config of APIs, aiming at efficiency and safty.
  64. ConfigDefault = Config{}.Froze()
  65. // ConfigStd is the standard config of APIs, aiming at being compatible with encoding/json.
  66. ConfigStd = Config{
  67. EscapeHTML : true,
  68. SortMapKeys: true,
  69. CompactMarshaler: true,
  70. CopyString : true,
  71. ValidateString : true,
  72. }.Froze()
  73. // ConfigFastest is the fastest config of APIs, aiming at speed.
  74. ConfigFastest = Config{
  75. NoQuoteTextMarshaler: true,
  76. NoValidateJSONMarshaler: true,
  77. }.Froze()
  78. )
  79. // API is a binding of specific config.
  80. // This interface is inspired by github.com/json-iterator/go,
  81. // and has same behaviors under equavilent config.
  82. type API interface {
  83. // MarshalToString returns the JSON encoding string of v
  84. MarshalToString(v interface{}) (string, error)
  85. // Marshal returns the JSON encoding bytes of v.
  86. Marshal(v interface{}) ([]byte, error)
  87. // MarshalIndent returns the JSON encoding bytes with indent and prefix.
  88. MarshalIndent(v interface{}, prefix, indent string) ([]byte, error)
  89. // UnmarshalFromString parses the JSON-encoded bytes and stores the result in the value pointed to by v.
  90. UnmarshalFromString(str string, v interface{}) error
  91. // Unmarshal parses the JSON-encoded string and stores the result in the value pointed to by v.
  92. Unmarshal(data []byte, v interface{}) error
  93. // NewEncoder create a Encoder holding writer
  94. NewEncoder(writer io.Writer) Encoder
  95. // NewDecoder create a Decoder holding reader
  96. NewDecoder(reader io.Reader) Decoder
  97. // Valid validates the JSON-encoded bytes and reportes if it is valid
  98. Valid(data []byte) bool
  99. }
  100. // Encoder encodes JSON into io.Writer
  101. type Encoder interface {
  102. // Encode writes the JSON encoding of v to the stream, followed by a newline character.
  103. Encode(val interface{}) error
  104. // SetEscapeHTML specifies whether problematic HTML characters
  105. // should be escaped inside JSON quoted strings.
  106. // The default behavior NOT ESCAPE
  107. SetEscapeHTML(on bool)
  108. // SetIndent instructs the encoder to format each subsequent encoded value
  109. // as if indented by the package-level function Indent(dst, src, prefix, indent).
  110. // Calling SetIndent("", "") disables indentation
  111. SetIndent(prefix, indent string)
  112. }
  113. // Decoder decodes JSON from io.Read
  114. type Decoder interface {
  115. // Decode reads the next JSON-encoded value from its input and stores it in the value pointed to by v.
  116. Decode(val interface{}) error
  117. // Buffered returns a reader of the data remaining in the Decoder's buffer.
  118. // The reader is valid until the next call to Decode.
  119. Buffered() io.Reader
  120. // DisallowUnknownFields causes the Decoder to return an error when the destination is a struct
  121. // and the input contains object keys which do not match any non-ignored, exported fields in the destination.
  122. DisallowUnknownFields()
  123. // More reports whether there is another element in the current array or object being parsed.
  124. More() bool
  125. // UseNumber causes the Decoder to unmarshal a number into an interface{} as a Number instead of as a float64.
  126. UseNumber()
  127. }
  128. // Marshal returns the JSON encoding bytes of v.
  129. func Marshal(val interface{}) ([]byte, error) {
  130. return ConfigDefault.Marshal(val)
  131. }
  132. // MarshalString returns the JSON encoding string of v.
  133. func MarshalString(val interface{}) (string, error) {
  134. return ConfigDefault.MarshalToString(val)
  135. }
  136. // Unmarshal parses the JSON-encoded data and stores the result in the value pointed to by v.
  137. // NOTICE: This API copies given buffer by default,
  138. // if you want to pass JSON more efficiently, use UnmarshalString instead.
  139. func Unmarshal(buf []byte, val interface{}) error {
  140. return ConfigDefault.Unmarshal(buf, val)
  141. }
  142. // UnmarshalString is like Unmarshal, except buf is a string.
  143. func UnmarshalString(buf string, val interface{}) error {
  144. return ConfigDefault.UnmarshalFromString(buf, val)
  145. }
  146. // Get searches the given path from json,
  147. // and returns its representing ast.Node.
  148. //
  149. // Each path arg must be integer or string:
  150. // - Integer is target index(>=0), means searching current node as array.
  151. // - String is target key, means searching current node as object.
  152. //
  153. //
  154. // Note, the api expects the json is well-formed at least,
  155. // otherwise it may return unexpected result.
  156. func Get(src []byte, path ...interface{}) (ast.Node, error) {
  157. return GetFromString(string(src), path...)
  158. }
  159. // GetFromString is same with Get except src is string,
  160. // which can reduce unnecessary memory copy.
  161. func GetFromString(src string, path ...interface{}) (ast.Node, error) {
  162. return ast.NewSearcher(src).GetByPath(path...)
  163. }
  164. // Valid reports whether data is a valid JSON encoding.
  165. func Valid(data []byte) bool {
  166. return ConfigDefault.Valid(data)
  167. }