另客网go项目公用的代码库

reflect.go 8.4KB

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