feature_config.go 9.3 KB

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