feature_config.go 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  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 := &frozenConfig{
  57. sortMapKeys: cfg.SortMapKeys,
  58. indentionStep: cfg.IndentionStep,
  59. objectFieldMustBeSimpleString: cfg.ObjectFieldMustBeSimpleString,
  60. onlyTaggedField: cfg.OnlyTaggedField,
  61. streamPool: make(chan *Stream, 16),
  62. iteratorPool: make(chan *Iterator, 16),
  63. }
  64. api.initCache()
  65. if cfg.MarshalFloatWith6Digits {
  66. api.marshalFloatWith6Digits()
  67. }
  68. if cfg.EscapeHTML {
  69. api.escapeHTML()
  70. }
  71. if cfg.UseNumber {
  72. api.useNumber()
  73. }
  74. if cfg.ValidateJsonRawMessage {
  75. api.validateJsonRawMessage()
  76. }
  77. api.configBeforeFrozen = cfg
  78. return api
  79. }
  80. func (cfg Config) frozeWithCacheReuse() *frozenConfig {
  81. api := getFrozenConfigFromCache(cfg)
  82. if api != nil {
  83. return api
  84. }
  85. api = cfg.Froze().(*frozenConfig)
  86. addFrozenConfigToCache(cfg, api)
  87. return api
  88. }
  89. func (cfg *frozenConfig) validateJsonRawMessage() {
  90. encoder := &funcEncoder{func(ptr unsafe.Pointer, stream *Stream) {
  91. rawMessage := *(*json.RawMessage)(ptr)
  92. iter := cfg.BorrowIterator([]byte(rawMessage))
  93. iter.Read()
  94. if iter.Error != nil {
  95. stream.WriteRaw("null")
  96. } else {
  97. cfg.ReturnIterator(iter)
  98. stream.WriteRaw(string(rawMessage))
  99. }
  100. }, func(ptr unsafe.Pointer) bool {
  101. return false
  102. }}
  103. cfg.addEncoderToCache(reflect.TypeOf((*json.RawMessage)(nil)).Elem(), encoder)
  104. cfg.addEncoderToCache(reflect.TypeOf((*RawMessage)(nil)).Elem(), encoder)
  105. }
  106. func (cfg *frozenConfig) useNumber() {
  107. cfg.addDecoderToCache(reflect.TypeOf((*interface{})(nil)).Elem(), &funcDecoder{func(ptr unsafe.Pointer, iter *Iterator) {
  108. if iter.WhatIsNext() == NumberValue {
  109. *((*interface{})(ptr)) = json.Number(iter.readNumberAsString())
  110. } else {
  111. *((*interface{})(ptr)) = iter.Read()
  112. }
  113. }})
  114. }
  115. func (cfg *frozenConfig) getTagKey() string {
  116. tagKey := cfg.configBeforeFrozen.TagKey
  117. if tagKey == "" {
  118. return "json"
  119. }
  120. return tagKey
  121. }
  122. func (cfg *frozenConfig) RegisterExtension(extension Extension) {
  123. cfg.extensions = append(cfg.extensions, extension)
  124. }
  125. type lossyFloat32Encoder struct {
  126. }
  127. func (encoder *lossyFloat32Encoder) Encode(ptr unsafe.Pointer, stream *Stream) {
  128. stream.WriteFloat32Lossy(*((*float32)(ptr)))
  129. }
  130. func (encoder *lossyFloat32Encoder) EncodeInterface(val interface{}, stream *Stream) {
  131. WriteToStream(val, stream, encoder)
  132. }
  133. func (encoder *lossyFloat32Encoder) IsEmpty(ptr unsafe.Pointer) bool {
  134. return *((*float32)(ptr)) == 0
  135. }
  136. type lossyFloat64Encoder struct {
  137. }
  138. func (encoder *lossyFloat64Encoder) Encode(ptr unsafe.Pointer, stream *Stream) {
  139. stream.WriteFloat64Lossy(*((*float64)(ptr)))
  140. }
  141. func (encoder *lossyFloat64Encoder) EncodeInterface(val interface{}, stream *Stream) {
  142. WriteToStream(val, stream, encoder)
  143. }
  144. func (encoder *lossyFloat64Encoder) IsEmpty(ptr unsafe.Pointer) bool {
  145. return *((*float64)(ptr)) == 0
  146. }
  147. // EnableLossyFloatMarshalling keeps 10**(-6) precision
  148. // for float variables for better performance.
  149. func (cfg *frozenConfig) marshalFloatWith6Digits() {
  150. // for better performance
  151. cfg.addEncoderToCache(reflect.TypeOf((*float32)(nil)).Elem(), &lossyFloat32Encoder{})
  152. cfg.addEncoderToCache(reflect.TypeOf((*float64)(nil)).Elem(), &lossyFloat64Encoder{})
  153. }
  154. type htmlEscapedStringEncoder struct {
  155. }
  156. func (encoder *htmlEscapedStringEncoder) Encode(ptr unsafe.Pointer, stream *Stream) {
  157. str := *((*string)(ptr))
  158. stream.WriteStringWithHTMLEscaped(str)
  159. }
  160. func (encoder *htmlEscapedStringEncoder) EncodeInterface(val interface{}, stream *Stream) {
  161. WriteToStream(val, stream, encoder)
  162. }
  163. func (encoder *htmlEscapedStringEncoder) IsEmpty(ptr unsafe.Pointer) bool {
  164. return *((*string)(ptr)) == ""
  165. }
  166. func (cfg *frozenConfig) escapeHTML() {
  167. cfg.addEncoderToCache(reflect.TypeOf((*string)(nil)).Elem(), &htmlEscapedStringEncoder{})
  168. }
  169. func (cfg *frozenConfig) cleanDecoders() {
  170. typeDecoders = map[string]ValDecoder{}
  171. fieldDecoders = map[string]ValDecoder{}
  172. *cfg = *(cfg.configBeforeFrozen.Froze().(*frozenConfig))
  173. }
  174. func (cfg *frozenConfig) cleanEncoders() {
  175. typeEncoders = map[string]ValEncoder{}
  176. fieldEncoders = map[string]ValEncoder{}
  177. *cfg = *(cfg.configBeforeFrozen.Froze().(*frozenConfig))
  178. }
  179. func (cfg *frozenConfig) MarshalToString(v interface{}) (string, error) {
  180. stream := cfg.BorrowStream(nil)
  181. defer cfg.ReturnStream(stream)
  182. stream.WriteVal(v)
  183. if stream.Error != nil {
  184. return "", stream.Error
  185. }
  186. return string(stream.Buffer()), nil
  187. }
  188. func (cfg *frozenConfig) Marshal(v interface{}) ([]byte, error) {
  189. stream := cfg.BorrowStream(nil)
  190. defer cfg.ReturnStream(stream)
  191. stream.WriteVal(v)
  192. if stream.Error != nil {
  193. return nil, stream.Error
  194. }
  195. result := stream.Buffer()
  196. copied := make([]byte, len(result))
  197. copy(copied, result)
  198. return copied, nil
  199. }
  200. func (cfg *frozenConfig) MarshalIndent(v interface{}, prefix, indent string) ([]byte, error) {
  201. if prefix != "" {
  202. panic("prefix is not supported")
  203. }
  204. for _, r := range indent {
  205. if r != ' ' {
  206. panic("indent can only be space")
  207. }
  208. }
  209. newCfg := cfg.configBeforeFrozen
  210. newCfg.IndentionStep = len(indent)
  211. return newCfg.frozeWithCacheReuse().Marshal(v)
  212. }
  213. func (cfg *frozenConfig) UnmarshalFromString(str string, v interface{}) error {
  214. data := []byte(str)
  215. data = data[:lastNotSpacePos(data)]
  216. iter := cfg.BorrowIterator(data)
  217. defer cfg.ReturnIterator(iter)
  218. iter.ReadVal(v)
  219. if iter.head == iter.tail {
  220. iter.loadMore()
  221. }
  222. if iter.Error == io.EOF {
  223. return nil
  224. }
  225. if iter.Error == nil {
  226. iter.ReportError("UnmarshalFromString", "there are bytes left after unmarshal")
  227. }
  228. return iter.Error
  229. }
  230. func (cfg *frozenConfig) Get(data []byte, path ...interface{}) Any {
  231. iter := cfg.BorrowIterator(data)
  232. defer cfg.ReturnIterator(iter)
  233. return locatePath(iter, path)
  234. }
  235. func (cfg *frozenConfig) Unmarshal(data []byte, v interface{}) error {
  236. data = data[:lastNotSpacePos(data)]
  237. iter := cfg.BorrowIterator(data)
  238. defer cfg.ReturnIterator(iter)
  239. typ := reflect.TypeOf(v)
  240. if typ.Kind() != reflect.Ptr {
  241. // return non-pointer error
  242. return errors.New("the second param must be ptr type")
  243. }
  244. iter.ReadVal(v)
  245. if iter.head == iter.tail {
  246. iter.loadMore()
  247. }
  248. if iter.Error == io.EOF {
  249. return nil
  250. }
  251. if iter.Error == nil {
  252. iter.ReportError("Unmarshal", "there are bytes left after unmarshal")
  253. }
  254. return iter.Error
  255. }
  256. func (cfg *frozenConfig) NewEncoder(writer io.Writer) *Encoder {
  257. stream := NewStream(cfg, writer, 512)
  258. return &Encoder{stream}
  259. }
  260. func (cfg *frozenConfig) NewDecoder(reader io.Reader) *Decoder {
  261. iter := Parse(cfg, reader, 512)
  262. return &Decoder{iter}
  263. }
  264. func (cfg *frozenConfig) Valid(data []byte) bool {
  265. iter := cfg.BorrowIterator(data)
  266. defer cfg.ReturnIterator(iter)
  267. iter.Skip()
  268. return iter.Error == nil
  269. }