feature_config.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. package jsoniter
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "io"
  6. "reflect"
  7. "unsafe"
  8. )
  9. // Config customize how the API should behave.
  10. // The API is created from Config by Froze.
  11. type Config struct {
  12. IndentionStep int
  13. MarshalFloatWith6Digits bool
  14. EscapeHTML bool
  15. SortMapKeys bool
  16. UseNumber bool
  17. TagKey string
  18. OnlyTaggedField bool
  19. ValidateJsonRawMessage bool
  20. ObjectFieldMustBeSimpleString bool
  21. }
  22. // API the public interface of this package.
  23. // Primary Marshal and Unmarshal.
  24. type API interface {
  25. IteratorPool
  26. StreamPool
  27. MarshalToString(v interface{}) (string, error)
  28. Marshal(v interface{}) ([]byte, error)
  29. MarshalIndent(v interface{}, prefix, indent string) ([]byte, error)
  30. UnmarshalFromString(str string, v interface{}) error
  31. Unmarshal(data []byte, v interface{}) error
  32. Get(data []byte, path ...interface{}) Any
  33. NewEncoder(writer io.Writer) *Encoder
  34. NewDecoder(reader io.Reader) *Decoder
  35. Valid(data []byte) bool
  36. RegisterExtension(extension Extension)
  37. }
  38. // ConfigDefault the default API
  39. var ConfigDefault = Config{
  40. EscapeHTML: true,
  41. }.Froze()
  42. // ConfigCompatibleWithStandardLibrary tries to be 100% compatible with standard library behavior
  43. var ConfigCompatibleWithStandardLibrary = Config{
  44. EscapeHTML: true,
  45. SortMapKeys: true,
  46. ValidateJsonRawMessage: true,
  47. }.Froze()
  48. // ConfigFastest marshals float with only 6 digits precision
  49. var ConfigFastest = Config{
  50. EscapeHTML: false,
  51. MarshalFloatWith6Digits: true, // will lose precession
  52. ObjectFieldMustBeSimpleString: true, // do not unescape object field
  53. }.Froze()
  54. // Froze forge API from config
  55. func (cfg Config) Froze() API {
  56. api := getFrozenConfigFromCache(cfg)
  57. if api != nil {
  58. return api
  59. }
  60. api = &frozenConfig{
  61. sortMapKeys: cfg.SortMapKeys,
  62. indentionStep: cfg.IndentionStep,
  63. objectFieldMustBeSimpleString: cfg.ObjectFieldMustBeSimpleString,
  64. onlyTaggedField: cfg.OnlyTaggedField,
  65. streamPool: make(chan *Stream, 16),
  66. iteratorPool: make(chan *Iterator, 16),
  67. }
  68. api.initCache()
  69. if cfg.MarshalFloatWith6Digits {
  70. api.marshalFloatWith6Digits()
  71. }
  72. if cfg.EscapeHTML {
  73. api.escapeHTML()
  74. }
  75. if cfg.UseNumber {
  76. api.useNumber()
  77. }
  78. if cfg.ValidateJsonRawMessage {
  79. api.validateJsonRawMessage()
  80. }
  81. api.configBeforeFrozen = cfg
  82. addFrozenConfigToCache(cfg, api)
  83. return api
  84. }
  85. func (cfg *frozenConfig) validateJsonRawMessage() {
  86. encoder := &funcEncoder{func(ptr unsafe.Pointer, stream *Stream) {
  87. rawMessage := *(*json.RawMessage)(ptr)
  88. iter := cfg.BorrowIterator([]byte(rawMessage))
  89. iter.Read()
  90. if iter.Error != nil {
  91. stream.WriteRaw("null")
  92. } else {
  93. cfg.ReturnIterator(iter)
  94. stream.WriteRaw(string(rawMessage))
  95. }
  96. }, func(ptr unsafe.Pointer) bool {
  97. return false
  98. }}
  99. cfg.addEncoderToCache(reflect.TypeOf((*json.RawMessage)(nil)).Elem(), encoder)
  100. cfg.addEncoderToCache(reflect.TypeOf((*RawMessage)(nil)).Elem(), encoder)
  101. }
  102. func (cfg *frozenConfig) useNumber() {
  103. cfg.addDecoderToCache(reflect.TypeOf((*interface{})(nil)).Elem(), &funcDecoder{func(ptr unsafe.Pointer, iter *Iterator) {
  104. if iter.WhatIsNext() == NumberValue {
  105. *((*interface{})(ptr)) = json.Number(iter.readNumberAsString())
  106. } else {
  107. *((*interface{})(ptr)) = iter.Read()
  108. }
  109. }})
  110. }
  111. func (cfg *frozenConfig) getTagKey() string {
  112. tagKey := cfg.configBeforeFrozen.TagKey
  113. if tagKey == "" {
  114. return "json"
  115. }
  116. return tagKey
  117. }
  118. func (cfg *frozenConfig) RegisterExtension(extension Extension) {
  119. cfg.extensions = append(cfg.extensions, extension)
  120. }
  121. type lossyFloat32Encoder struct {
  122. }
  123. func (encoder *lossyFloat32Encoder) Encode(ptr unsafe.Pointer, stream *Stream) {
  124. stream.WriteFloat32Lossy(*((*float32)(ptr)))
  125. }
  126. func (encoder *lossyFloat32Encoder) EncodeInterface(val interface{}, stream *Stream) {
  127. WriteToStream(val, stream, encoder)
  128. }
  129. func (encoder *lossyFloat32Encoder) IsEmpty(ptr unsafe.Pointer) bool {
  130. return *((*float32)(ptr)) == 0
  131. }
  132. type lossyFloat64Encoder struct {
  133. }
  134. func (encoder *lossyFloat64Encoder) Encode(ptr unsafe.Pointer, stream *Stream) {
  135. stream.WriteFloat64Lossy(*((*float64)(ptr)))
  136. }
  137. func (encoder *lossyFloat64Encoder) EncodeInterface(val interface{}, stream *Stream) {
  138. WriteToStream(val, stream, encoder)
  139. }
  140. func (encoder *lossyFloat64Encoder) IsEmpty(ptr unsafe.Pointer) bool {
  141. return *((*float64)(ptr)) == 0
  142. }
  143. // EnableLossyFloatMarshalling keeps 10**(-6) precision
  144. // for float variables for better performance.
  145. func (cfg *frozenConfig) marshalFloatWith6Digits() {
  146. // for better performance
  147. cfg.addEncoderToCache(reflect.TypeOf((*float32)(nil)).Elem(), &lossyFloat32Encoder{})
  148. cfg.addEncoderToCache(reflect.TypeOf((*float64)(nil)).Elem(), &lossyFloat64Encoder{})
  149. }
  150. type htmlEscapedStringEncoder struct {
  151. }
  152. func (encoder *htmlEscapedStringEncoder) Encode(ptr unsafe.Pointer, stream *Stream) {
  153. str := *((*string)(ptr))
  154. stream.WriteStringWithHTMLEscaped(str)
  155. }
  156. func (encoder *htmlEscapedStringEncoder) EncodeInterface(val interface{}, stream *Stream) {
  157. WriteToStream(val, stream, encoder)
  158. }
  159. func (encoder *htmlEscapedStringEncoder) IsEmpty(ptr unsafe.Pointer) bool {
  160. return *((*string)(ptr)) == ""
  161. }
  162. func (cfg *frozenConfig) escapeHTML() {
  163. cfg.addEncoderToCache(reflect.TypeOf((*string)(nil)).Elem(), &htmlEscapedStringEncoder{})
  164. }
  165. func (cfg *frozenConfig) cleanDecoders() {
  166. typeDecoders = map[string]ValDecoder{}
  167. fieldDecoders = map[string]ValDecoder{}
  168. *cfg = *(cfg.configBeforeFrozen.Froze().(*frozenConfig))
  169. }
  170. func (cfg *frozenConfig) cleanEncoders() {
  171. typeEncoders = map[string]ValEncoder{}
  172. fieldEncoders = map[string]ValEncoder{}
  173. *cfg = *(cfg.configBeforeFrozen.Froze().(*frozenConfig))
  174. }
  175. func (cfg *frozenConfig) MarshalToString(v interface{}) (string, error) {
  176. stream := cfg.BorrowStream(nil)
  177. defer cfg.ReturnStream(stream)
  178. stream.WriteVal(v)
  179. if stream.Error != nil {
  180. return "", stream.Error
  181. }
  182. return string(stream.Buffer()), nil
  183. }
  184. func (cfg *frozenConfig) Marshal(v interface{}) ([]byte, error) {
  185. stream := cfg.BorrowStream(nil)
  186. defer cfg.ReturnStream(stream)
  187. stream.WriteVal(v)
  188. if stream.Error != nil {
  189. return nil, stream.Error
  190. }
  191. result := stream.Buffer()
  192. copied := make([]byte, len(result))
  193. copy(copied, result)
  194. return copied, nil
  195. }
  196. func (cfg *frozenConfig) MarshalIndent(v interface{}, prefix, indent string) ([]byte, error) {
  197. if prefix != "" {
  198. panic("prefix is not supported")
  199. }
  200. for _, r := range indent {
  201. if r != ' ' {
  202. panic("indent can only be space")
  203. }
  204. }
  205. newCfg := cfg.configBeforeFrozen
  206. newCfg.IndentionStep = len(indent)
  207. return newCfg.Froze().Marshal(v)
  208. }
  209. func (cfg *frozenConfig) UnmarshalFromString(str string, v interface{}) error {
  210. data := []byte(str)
  211. data = data[:lastNotSpacePos(data)]
  212. iter := cfg.BorrowIterator(data)
  213. defer cfg.ReturnIterator(iter)
  214. iter.ReadVal(v)
  215. if iter.head == iter.tail {
  216. iter.loadMore()
  217. }
  218. if iter.Error == io.EOF {
  219. return nil
  220. }
  221. if iter.Error == nil {
  222. iter.ReportError("UnmarshalFromString", "there are bytes left after unmarshal")
  223. }
  224. return iter.Error
  225. }
  226. func (cfg *frozenConfig) Get(data []byte, path ...interface{}) Any {
  227. iter := cfg.BorrowIterator(data)
  228. defer cfg.ReturnIterator(iter)
  229. return locatePath(iter, path)
  230. }
  231. func (cfg *frozenConfig) Unmarshal(data []byte, v interface{}) error {
  232. data = data[:lastNotSpacePos(data)]
  233. iter := cfg.BorrowIterator(data)
  234. defer cfg.ReturnIterator(iter)
  235. typ := reflect.TypeOf(v)
  236. if typ.Kind() != reflect.Ptr {
  237. // return non-pointer error
  238. return errors.New("the second param must be ptr type")
  239. }
  240. iter.ReadVal(v)
  241. if iter.head == iter.tail {
  242. iter.loadMore()
  243. }
  244. if iter.Error == io.EOF {
  245. return nil
  246. }
  247. if iter.Error == nil {
  248. iter.ReportError("Unmarshal", "there are bytes left after unmarshal")
  249. }
  250. return iter.Error
  251. }
  252. func (cfg *frozenConfig) NewEncoder(writer io.Writer) *Encoder {
  253. stream := NewStream(cfg, writer, 512)
  254. return &Encoder{stream}
  255. }
  256. func (cfg *frozenConfig) NewDecoder(reader io.Reader) *Decoder {
  257. iter := Parse(cfg, reader, 512)
  258. return &Decoder{iter}
  259. }
  260. func (cfg *frozenConfig) Valid(data []byte) bool {
  261. iter := cfg.BorrowIterator(data)
  262. defer cfg.ReturnIterator(iter)
  263. iter.Skip()
  264. return iter.Error == nil
  265. }