reflect.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  1. package jsoniter
  2. import (
  3. "fmt"
  4. "reflect"
  5. "unsafe"
  6. "github.com/modern-go/reflect2"
  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) caseSensitive() bool {
  38. if b.frozenConfig == nil {
  39. // default is case-insensitive
  40. return false
  41. }
  42. return b.frozenConfig.caseSensitive
  43. }
  44. func (b *ctx) append(prefix string) *ctx {
  45. return &ctx{
  46. frozenConfig: b.frozenConfig,
  47. prefix: b.prefix + " " + prefix,
  48. encoders: b.encoders,
  49. decoders: b.decoders,
  50. }
  51. }
  52. // ReadVal copy the underlying JSON into go interface, same as json.Unmarshal
  53. func (iter *Iterator) ReadVal(obj interface{}) {
  54. depth := iter.depth
  55. cacheKey := reflect2.RTypeOf(obj)
  56. decoder := iter.cfg.getDecoderFromCache(cacheKey)
  57. if decoder == nil {
  58. typ := reflect2.TypeOf(obj)
  59. if typ.Kind() != reflect.Ptr {
  60. iter.ReportError("ReadVal", "can only unmarshal into pointer")
  61. return
  62. }
  63. decoder = iter.cfg.DecoderOf(typ)
  64. }
  65. ptr := reflect2.PtrOf(obj)
  66. if ptr == nil {
  67. iter.ReportError("ReadVal", "can not read into nil pointer")
  68. return
  69. }
  70. decoder.Decode(ptr, iter)
  71. if iter.depth != depth {
  72. iter.ReportError("ReadVal", "unexpected mismatched nesting")
  73. return
  74. }
  75. }
  76. // WriteVal copy the go interface into underlying JSON, same as json.Marshal
  77. func (stream *Stream) WriteVal(val interface{}) {
  78. if nil == val {
  79. stream.WriteNil()
  80. return
  81. }
  82. cacheKey := reflect2.RTypeOf(val)
  83. encoder := stream.cfg.getEncoderFromCache(cacheKey)
  84. if encoder == nil {
  85. typ := reflect2.TypeOf(val)
  86. encoder = stream.cfg.EncoderOf(typ)
  87. }
  88. encoder.Encode(reflect2.PtrOf(val), stream)
  89. }
  90. func (cfg *frozenConfig) DecoderOf(typ reflect2.Type) ValDecoder {
  91. cacheKey := typ.RType()
  92. decoder := cfg.getDecoderFromCache(cacheKey)
  93. if decoder != nil {
  94. return decoder
  95. }
  96. ctx := &ctx{
  97. frozenConfig: cfg,
  98. prefix: "",
  99. decoders: map[reflect2.Type]ValDecoder{},
  100. encoders: map[reflect2.Type]ValEncoder{},
  101. }
  102. ptrType := typ.(*reflect2.UnsafePtrType)
  103. decoder = decoderOfType(ctx, ptrType.Elem())
  104. cfg.addDecoderToCache(cacheKey, decoder)
  105. return decoder
  106. }
  107. func decoderOfType(ctx *ctx, typ reflect2.Type) ValDecoder {
  108. decoder := getTypeDecoderFromExtension(ctx, typ)
  109. if decoder != nil {
  110. return decoder
  111. }
  112. decoder = createDecoderOfType(ctx, typ)
  113. for _, extension := range extensions {
  114. decoder = extension.DecorateDecoder(typ, decoder)
  115. }
  116. decoder = ctx.decoderExtension.DecorateDecoder(typ, decoder)
  117. for _, extension := range ctx.extraExtensions {
  118. decoder = extension.DecorateDecoder(typ, decoder)
  119. }
  120. return decoder
  121. }
  122. func createDecoderOfType(ctx *ctx, typ reflect2.Type) ValDecoder {
  123. decoder := ctx.decoders[typ]
  124. if decoder != nil {
  125. return decoder
  126. }
  127. placeholder := &placeholderDecoder{}
  128. ctx.decoders[typ] = placeholder
  129. decoder = _createDecoderOfType(ctx, typ)
  130. placeholder.decoder = decoder
  131. return decoder
  132. }
  133. func _createDecoderOfType(ctx *ctx, typ reflect2.Type) ValDecoder {
  134. decoder := createDecoderOfJsonRawMessage(ctx, typ)
  135. if decoder != nil {
  136. return decoder
  137. }
  138. decoder = createDecoderOfJsonNumber(ctx, typ)
  139. if decoder != nil {
  140. return decoder
  141. }
  142. decoder = createDecoderOfMarshaler(ctx, typ)
  143. if decoder != nil {
  144. return decoder
  145. }
  146. decoder = createDecoderOfAny(ctx, typ)
  147. if decoder != nil {
  148. return decoder
  149. }
  150. decoder = createDecoderOfNative(ctx, typ)
  151. if decoder != nil {
  152. return decoder
  153. }
  154. switch typ.Kind() {
  155. case reflect.Interface:
  156. ifaceType, isIFace := typ.(*reflect2.UnsafeIFaceType)
  157. if isIFace {
  158. return &ifaceDecoder{valType: ifaceType}
  159. }
  160. return &efaceDecoder{}
  161. case reflect.Struct:
  162. return decoderOfStruct(ctx, typ)
  163. case reflect.Array:
  164. return decoderOfArray(ctx, typ)
  165. case reflect.Slice:
  166. return decoderOfSlice(ctx, typ)
  167. case reflect.Map:
  168. return decoderOfMap(ctx, typ)
  169. case reflect.Ptr:
  170. return decoderOfOptional(ctx, typ)
  171. default:
  172. return &lazyErrorDecoder{err: fmt.Errorf("%s%s is unsupported type", ctx.prefix, typ.String())}
  173. }
  174. }
  175. func (cfg *frozenConfig) EncoderOf(typ reflect2.Type) ValEncoder {
  176. cacheKey := typ.RType()
  177. encoder := cfg.getEncoderFromCache(cacheKey)
  178. if encoder != nil {
  179. return encoder
  180. }
  181. ctx := &ctx{
  182. frozenConfig: cfg,
  183. prefix: "",
  184. decoders: map[reflect2.Type]ValDecoder{},
  185. encoders: map[reflect2.Type]ValEncoder{},
  186. }
  187. encoder = encoderOfType(ctx, typ)
  188. if typ.LikePtr() {
  189. encoder = &onePtrEncoder{encoder}
  190. }
  191. cfg.addEncoderToCache(cacheKey, encoder)
  192. return encoder
  193. }
  194. type onePtrEncoder struct {
  195. encoder ValEncoder
  196. }
  197. func (encoder *onePtrEncoder) IsEmpty(ptr unsafe.Pointer) bool {
  198. return encoder.encoder.IsEmpty(unsafe.Pointer(&ptr))
  199. }
  200. func (encoder *onePtrEncoder) Encode(ptr unsafe.Pointer, stream *Stream) {
  201. encoder.encoder.Encode(unsafe.Pointer(&ptr), stream)
  202. }
  203. func encoderOfType(ctx *ctx, typ reflect2.Type) ValEncoder {
  204. encoder := getTypeEncoderFromExtension(ctx, typ)
  205. if encoder != nil {
  206. return encoder
  207. }
  208. encoder = createEncoderOfType(ctx, typ)
  209. for _, extension := range extensions {
  210. encoder = extension.DecorateEncoder(typ, encoder)
  211. }
  212. encoder = ctx.encoderExtension.DecorateEncoder(typ, encoder)
  213. for _, extension := range ctx.extraExtensions {
  214. encoder = extension.DecorateEncoder(typ, encoder)
  215. }
  216. return encoder
  217. }
  218. func createEncoderOfType(ctx *ctx, typ reflect2.Type) ValEncoder {
  219. encoder := ctx.encoders[typ]
  220. if encoder != nil {
  221. return encoder
  222. }
  223. placeholder := &placeholderEncoder{}
  224. ctx.encoders[typ] = placeholder
  225. encoder = _createEncoderOfType(ctx, typ)
  226. placeholder.encoder = encoder
  227. return encoder
  228. }
  229. func _createEncoderOfType(ctx *ctx, typ reflect2.Type) ValEncoder {
  230. encoder := createEncoderOfJsonRawMessage(ctx, typ)
  231. if encoder != nil {
  232. return encoder
  233. }
  234. encoder = createEncoderOfJsonNumber(ctx, typ)
  235. if encoder != nil {
  236. return encoder
  237. }
  238. encoder = createEncoderOfMarshaler(ctx, typ)
  239. if encoder != nil {
  240. return encoder
  241. }
  242. encoder = createEncoderOfAny(ctx, typ)
  243. if encoder != nil {
  244. return encoder
  245. }
  246. encoder = createEncoderOfNative(ctx, typ)
  247. if encoder != nil {
  248. return encoder
  249. }
  250. kind := typ.Kind()
  251. switch kind {
  252. case reflect.Interface:
  253. return &dynamicEncoder{typ}
  254. case reflect.Struct:
  255. return encoderOfStruct(ctx, typ)
  256. case reflect.Array:
  257. return encoderOfArray(ctx, typ)
  258. case reflect.Slice:
  259. return encoderOfSlice(ctx, typ)
  260. case reflect.Map:
  261. return encoderOfMap(ctx, typ)
  262. case reflect.Ptr:
  263. return encoderOfOptional(ctx, typ)
  264. default:
  265. return &lazyErrorEncoder{err: fmt.Errorf("%s%s is unsupported type", ctx.prefix, typ.String())}
  266. }
  267. }
  268. type lazyErrorDecoder struct {
  269. err error
  270. }
  271. func (decoder *lazyErrorDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) {
  272. if iter.WhatIsNext() != NilValue {
  273. if iter.Error == nil {
  274. iter.Error = decoder.err
  275. }
  276. } else {
  277. iter.Skip()
  278. }
  279. }
  280. type lazyErrorEncoder struct {
  281. err error
  282. }
  283. func (encoder *lazyErrorEncoder) Encode(ptr unsafe.Pointer, stream *Stream) {
  284. if ptr == nil {
  285. stream.WriteNil()
  286. } else if stream.Error == nil {
  287. stream.Error = encoder.err
  288. }
  289. }
  290. func (encoder *lazyErrorEncoder) IsEmpty(ptr unsafe.Pointer) bool {
  291. return false
  292. }
  293. type placeholderDecoder struct {
  294. decoder ValDecoder
  295. }
  296. func (decoder *placeholderDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) {
  297. decoder.decoder.Decode(ptr, iter)
  298. }
  299. type placeholderEncoder struct {
  300. encoder ValEncoder
  301. }
  302. func (encoder *placeholderEncoder) Encode(ptr unsafe.Pointer, stream *Stream) {
  303. encoder.encoder.Encode(ptr, stream)
  304. }
  305. func (encoder *placeholderEncoder) IsEmpty(ptr unsafe.Pointer) bool {
  306. return encoder.encoder.IsEmpty(ptr)
  307. }