reflect.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. package jsoniter
  2. import (
  3. "fmt"
  4. "github.com/modern-go/reflect2"
  5. "reflect"
  6. "unsafe"
  7. )
  8. // ValDecoder is an internal type registered to cache as needed.
  9. // Don't confuse jsoniter.ValDecoder with json.Decoder.
  10. // For json.Decoder's adapter, refer to jsoniter.AdapterDecoder(todo link).
  11. //
  12. // Reflection on type to create decoders, which is then cached
  13. // Reflection on value is avoided as we can, as the reflect.Value itself will allocate, with following exceptions
  14. // 1. create instance of new value, for example *int will need a int to be allocated
  15. // 2. append to slice, if the existing cap is not enough, allocate will be done using Reflect.New
  16. // 3. assignment to map, both key and value will be reflect.Value
  17. // For a simple struct binding, it will be reflect.Value free and allocation free
  18. type ValDecoder interface {
  19. Decode(ptr unsafe.Pointer, iter *Iterator)
  20. }
  21. // ValEncoder is an internal type registered to cache as needed.
  22. // Don't confuse jsoniter.ValEncoder with json.Encoder.
  23. // For json.Encoder's adapter, refer to jsoniter.AdapterEncoder(todo godoc link).
  24. type ValEncoder interface {
  25. IsEmpty(ptr unsafe.Pointer) bool
  26. Encode(ptr unsafe.Pointer, stream *Stream)
  27. }
  28. type checkIsEmpty interface {
  29. IsEmpty(ptr unsafe.Pointer) bool
  30. }
  31. type ctx struct {
  32. *frozenConfig
  33. prefix string
  34. encoders map[reflect2.Type]ValEncoder
  35. decoders map[reflect2.Type]ValDecoder
  36. }
  37. func (b *ctx) append(prefix string) *ctx {
  38. return &ctx{
  39. frozenConfig: b.frozenConfig,
  40. prefix: b.prefix + " " + prefix,
  41. encoders: b.encoders,
  42. decoders: b.decoders,
  43. }
  44. }
  45. // ReadVal copy the underlying JSON into go interface, same as json.Unmarshal
  46. func (iter *Iterator) ReadVal(obj interface{}) {
  47. cacheKey := reflect2.RTypeOf(obj)
  48. decoder := iter.cfg.getDecoderFromCache(cacheKey)
  49. if decoder == nil {
  50. typ := reflect2.TypeOf(obj)
  51. if typ.Kind() != reflect.Ptr {
  52. iter.ReportError("ReadVal", "can only unmarshal into pointer")
  53. return
  54. }
  55. decoder = iter.cfg.DecoderOf(typ)
  56. }
  57. ptr := reflect2.PtrOf(obj)
  58. if ptr == nil {
  59. iter.ReportError("ReadVal", "can not read into nil pointer")
  60. return
  61. }
  62. decoder.Decode(ptr, iter)
  63. }
  64. // WriteVal copy the go interface into underlying JSON, same as json.Marshal
  65. func (stream *Stream) WriteVal(val interface{}) {
  66. if nil == val {
  67. stream.WriteNil()
  68. return
  69. }
  70. cacheKey := reflect2.RTypeOf(val)
  71. encoder := stream.cfg.getEncoderFromCache(cacheKey)
  72. if encoder == nil {
  73. typ := reflect2.TypeOf(val)
  74. encoder = stream.cfg.EncoderOf(typ)
  75. }
  76. encoder.Encode(reflect2.PtrOf(val), stream)
  77. }
  78. func (cfg *frozenConfig) DecoderOf(typ reflect2.Type) ValDecoder {
  79. cacheKey := typ.RType()
  80. decoder := cfg.getDecoderFromCache(cacheKey)
  81. if decoder != nil {
  82. return decoder
  83. }
  84. ctx := &ctx{
  85. frozenConfig: cfg,
  86. prefix: "",
  87. decoders: map[reflect2.Type]ValDecoder{},
  88. encoders: map[reflect2.Type]ValEncoder{},
  89. }
  90. ptrType := typ.(*reflect2.UnsafePtrType)
  91. decoder = decoderOfType(ctx, ptrType.Elem())
  92. cfg.addDecoderToCache(cacheKey, decoder)
  93. return decoder
  94. }
  95. func decoderOfType(ctx *ctx, typ reflect2.Type) ValDecoder {
  96. decoder := getTypeDecoderFromExtension(ctx, typ)
  97. if decoder != nil {
  98. return decoder
  99. }
  100. decoder = createDecoderOfType(ctx, typ)
  101. for _, extension := range extensions {
  102. decoder = extension.DecorateDecoder(typ, decoder)
  103. }
  104. for _, extension := range ctx.extensions {
  105. decoder = extension.DecorateDecoder(typ, decoder)
  106. }
  107. return decoder
  108. }
  109. func createDecoderOfType(ctx *ctx, typ reflect2.Type) ValDecoder {
  110. decoder := ctx.decoders[typ]
  111. if decoder != nil {
  112. return decoder
  113. }
  114. placeholder := &placeholderDecoder{}
  115. ctx.decoders[typ] = placeholder
  116. decoder = _createDecoderOfType(ctx, typ)
  117. placeholder.decoder = decoder
  118. return decoder
  119. }
  120. func _createDecoderOfType(ctx *ctx, typ reflect2.Type) ValDecoder {
  121. decoder := createDecoderOfJsonRawMessage(ctx, typ)
  122. if decoder != nil {
  123. return decoder
  124. }
  125. decoder = createDecoderOfJsonNumber(ctx, typ)
  126. if decoder != nil {
  127. return decoder
  128. }
  129. decoder = createDecoderOfMarshaler(ctx, typ)
  130. if decoder != nil {
  131. return decoder
  132. }
  133. decoder = createDecoderOfAny(ctx, typ)
  134. if decoder != nil {
  135. return decoder
  136. }
  137. decoder = createDecoderOfNative(ctx, typ)
  138. if decoder != nil {
  139. return decoder
  140. }
  141. switch typ.Kind() {
  142. case reflect.Interface:
  143. ifaceType, isIFace := typ.(*reflect2.UnsafeIFaceType)
  144. if isIFace {
  145. return &ifaceDecoder{valType: ifaceType}
  146. }
  147. return &efaceDecoder{}
  148. case reflect.Struct:
  149. return decoderOfStruct(ctx, typ)
  150. case reflect.Array:
  151. return decoderOfArray(ctx, typ)
  152. case reflect.Slice:
  153. return decoderOfSlice(ctx, typ)
  154. case reflect.Map:
  155. return decoderOfMap(ctx, typ)
  156. case reflect.Ptr:
  157. return decoderOfOptional(ctx, typ)
  158. default:
  159. return &lazyErrorDecoder{err: fmt.Errorf("%s%s is unsupported type", ctx.prefix, typ.String())}
  160. }
  161. }
  162. func (cfg *frozenConfig) EncoderOf(typ reflect2.Type) ValEncoder {
  163. cacheKey := typ.RType()
  164. encoder := cfg.getEncoderFromCache(cacheKey)
  165. if encoder != nil {
  166. return encoder
  167. }
  168. ctx := &ctx{
  169. frozenConfig: cfg,
  170. prefix: "",
  171. decoders: map[reflect2.Type]ValDecoder{},
  172. encoders: map[reflect2.Type]ValEncoder{},
  173. }
  174. encoder = encoderOfType(ctx, typ)
  175. if typ.LikePtr() {
  176. encoder = &onePtrEncoder{encoder}
  177. }
  178. cfg.addEncoderToCache(cacheKey, encoder)
  179. return encoder
  180. }
  181. type onePtrEncoder struct {
  182. encoder ValEncoder
  183. }
  184. func (encoder *onePtrEncoder) IsEmpty(ptr unsafe.Pointer) bool {
  185. return encoder.encoder.IsEmpty(unsafe.Pointer(&ptr))
  186. }
  187. func (encoder *onePtrEncoder) Encode(ptr unsafe.Pointer, stream *Stream) {
  188. encoder.encoder.Encode(unsafe.Pointer(&ptr), stream)
  189. }
  190. func encoderOfType(ctx *ctx, typ reflect2.Type) ValEncoder {
  191. encoder := getTypeEncoderFromExtension(ctx, typ)
  192. if encoder != nil {
  193. return encoder
  194. }
  195. encoder = createEncoderOfType(ctx, typ)
  196. for _, extension := range extensions {
  197. encoder = extension.DecorateEncoder(typ, encoder)
  198. }
  199. for _, extension := range ctx.extensions {
  200. encoder = extension.DecorateEncoder(typ, encoder)
  201. }
  202. return encoder
  203. }
  204. func createEncoderOfType(ctx *ctx, typ reflect2.Type) ValEncoder {
  205. encoder := ctx.encoders[typ]
  206. if encoder != nil {
  207. return encoder
  208. }
  209. placeholder := &placeholderEncoder{}
  210. ctx.encoders[typ] = placeholder
  211. encoder = _createEncoderOfType(ctx, typ)
  212. placeholder.encoder = encoder
  213. return encoder
  214. }
  215. func _createEncoderOfType(ctx *ctx, typ reflect2.Type) ValEncoder {
  216. encoder := createEncoderOfJsonRawMessage(ctx, typ)
  217. if encoder != nil {
  218. return encoder
  219. }
  220. encoder = createEncoderOfJsonNumber(ctx, typ)
  221. if encoder != nil {
  222. return encoder
  223. }
  224. encoder = createEncoderOfMarshaler(ctx, typ)
  225. if encoder != nil {
  226. return encoder
  227. }
  228. encoder = createEncoderOfAny(ctx, typ)
  229. if encoder != nil {
  230. return encoder
  231. }
  232. encoder = createEncoderOfNative(ctx, typ)
  233. if encoder != nil {
  234. return encoder
  235. }
  236. kind := typ.Kind()
  237. switch kind {
  238. case reflect.Interface:
  239. return &dynamicEncoder{typ}
  240. case reflect.Struct:
  241. return encoderOfStruct(ctx, typ)
  242. case reflect.Array:
  243. return encoderOfArray(ctx, typ)
  244. case reflect.Slice:
  245. return encoderOfSlice(ctx, typ)
  246. case reflect.Map:
  247. return encoderOfMap(ctx, typ)
  248. case reflect.Ptr:
  249. return encoderOfOptional(ctx, typ)
  250. default:
  251. return &lazyErrorEncoder{err: fmt.Errorf("%s%s is unsupported type", ctx.prefix, typ.String())}
  252. }
  253. }
  254. type lazyErrorDecoder struct {
  255. err error
  256. }
  257. func (decoder *lazyErrorDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) {
  258. if iter.WhatIsNext() != NilValue {
  259. if iter.Error == nil {
  260. iter.Error = decoder.err
  261. }
  262. } else {
  263. iter.Skip()
  264. }
  265. }
  266. type lazyErrorEncoder struct {
  267. err error
  268. }
  269. func (encoder *lazyErrorEncoder) Encode(ptr unsafe.Pointer, stream *Stream) {
  270. if ptr == nil {
  271. stream.WriteNil()
  272. } else if stream.Error == nil {
  273. stream.Error = encoder.err
  274. }
  275. }
  276. func (encoder *lazyErrorEncoder) IsEmpty(ptr unsafe.Pointer) bool {
  277. return false
  278. }
  279. type placeholderDecoder struct {
  280. decoder ValDecoder
  281. }
  282. func (decoder *placeholderDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) {
  283. decoder.decoder.Decode(ptr, iter)
  284. }
  285. type placeholderEncoder struct {
  286. encoder ValEncoder
  287. }
  288. func (encoder *placeholderEncoder) Encode(ptr unsafe.Pointer, stream *Stream) {
  289. encoder.encoder.Encode(ptr, stream)
  290. }
  291. func (encoder *placeholderEncoder) IsEmpty(ptr unsafe.Pointer) bool {
  292. return encoder.encoder.IsEmpty(ptr)
  293. }