feature_reflect.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543
  1. package jsoniter
  2. import (
  3. "encoding"
  4. "encoding/json"
  5. "fmt"
  6. "reflect"
  7. "sync/atomic"
  8. "unsafe"
  9. )
  10. // Decoder is an internal type registered to cache as needed.
  11. // Don't confuse jsoniter.Decoder with json.Decoder.
  12. // For json.Decoder's adapter, refer to jsoniter.AdapterDecoder(todo link).
  13. //
  14. // Reflection on type to create decoders, which is then cached
  15. // Reflection on value is avoided as we can, as the reflect.Value itself will allocate, with following exceptions
  16. // 1. create instance of new value, for example *int will need a int to be allocated
  17. // 2. append to slice, if the existing cap is not enough, allocate will be done using Reflect.New
  18. // 3. assignment to map, both key and value will be reflect.Value
  19. // For a simple struct binding, it will be reflect.Value free and allocation free
  20. type Decoder interface {
  21. decode(ptr unsafe.Pointer, iter *Iterator)
  22. }
  23. // Encoder is an internal type registered to cache as needed.
  24. // Don't confuse jsoniter.Encoder with json.Encoder.
  25. // For json.Encoder's adapter, refer to jsoniter.AdapterEncoder(todo godoc link).
  26. type Encoder interface {
  27. isEmpty(ptr unsafe.Pointer) bool
  28. encode(ptr unsafe.Pointer, stream *Stream)
  29. encodeInterface(val interface{}, stream *Stream)
  30. }
  31. func writeToStream(val interface{}, stream *Stream, encoder Encoder) {
  32. e := (*emptyInterface)(unsafe.Pointer(&val))
  33. if reflect.TypeOf(val).Kind() == reflect.Ptr {
  34. encoder.encode(unsafe.Pointer(&e.word), stream)
  35. } else {
  36. encoder.encode(e.word, stream)
  37. }
  38. }
  39. type DecoderFunc func(ptr unsafe.Pointer, iter *Iterator)
  40. type EncoderFunc func(ptr unsafe.Pointer, stream *Stream)
  41. type ExtensionFunc func(typ reflect.Type, field *reflect.StructField) ([]string, EncoderFunc, DecoderFunc)
  42. type funcDecoder struct {
  43. fun DecoderFunc
  44. }
  45. func (decoder *funcDecoder) decode(ptr unsafe.Pointer, iter *Iterator) {
  46. decoder.fun(ptr, iter)
  47. }
  48. type funcEncoder struct {
  49. fun EncoderFunc
  50. }
  51. func (encoder *funcEncoder) encode(ptr unsafe.Pointer, stream *Stream) {
  52. encoder.fun(ptr, stream)
  53. }
  54. func (encoder *funcEncoder) encodeInterface(val interface{}, stream *Stream) {
  55. writeToStream(val, stream, encoder)
  56. }
  57. func (encoder *funcEncoder) isEmpty(ptr unsafe.Pointer) bool {
  58. return false
  59. }
  60. var DECODERS unsafe.Pointer
  61. var ENCODERS unsafe.Pointer
  62. var typeDecoders map[string]Decoder
  63. var fieldDecoders map[string]Decoder
  64. var typeEncoders map[string]Encoder
  65. var fieldEncoders map[string]Encoder
  66. var extensions []ExtensionFunc
  67. var jsonNumberType reflect.Type
  68. var jsonRawMessageType reflect.Type
  69. var anyType reflect.Type
  70. var marshalerType reflect.Type
  71. var unmarshalerType reflect.Type
  72. var textUnmarshalerType reflect.Type
  73. func init() {
  74. typeDecoders = map[string]Decoder{}
  75. fieldDecoders = map[string]Decoder{}
  76. typeEncoders = map[string]Encoder{}
  77. fieldEncoders = map[string]Encoder{}
  78. extensions = []ExtensionFunc{}
  79. atomic.StorePointer(&DECODERS, unsafe.Pointer(&map[string]Decoder{}))
  80. atomic.StorePointer(&ENCODERS, unsafe.Pointer(&map[string]Encoder{}))
  81. jsonNumberType = reflect.TypeOf((*json.Number)(nil)).Elem()
  82. jsonRawMessageType = reflect.TypeOf((*json.RawMessage)(nil)).Elem()
  83. anyType = reflect.TypeOf((*Any)(nil)).Elem()
  84. marshalerType = reflect.TypeOf((*json.Marshaler)(nil)).Elem()
  85. unmarshalerType = reflect.TypeOf((*json.Unmarshaler)(nil)).Elem()
  86. textUnmarshalerType = reflect.TypeOf((*encoding.TextUnmarshaler)(nil)).Elem()
  87. }
  88. func addDecoderToCache(cacheKey reflect.Type, decoder Decoder) {
  89. done := false
  90. for !done {
  91. ptr := atomic.LoadPointer(&DECODERS)
  92. cache := *(*map[reflect.Type]Decoder)(ptr)
  93. copied := map[reflect.Type]Decoder{}
  94. for k, v := range cache {
  95. copied[k] = v
  96. }
  97. copied[cacheKey] = decoder
  98. done = atomic.CompareAndSwapPointer(&DECODERS, ptr, unsafe.Pointer(&copied))
  99. }
  100. }
  101. func addEncoderToCache(cacheKey reflect.Type, encoder Encoder) {
  102. done := false
  103. for !done {
  104. ptr := atomic.LoadPointer(&ENCODERS)
  105. cache := *(*map[reflect.Type]Encoder)(ptr)
  106. copied := map[reflect.Type]Encoder{}
  107. for k, v := range cache {
  108. copied[k] = v
  109. }
  110. copied[cacheKey] = encoder
  111. done = atomic.CompareAndSwapPointer(&ENCODERS, ptr, unsafe.Pointer(&copied))
  112. }
  113. }
  114. func getDecoderFromCache(cacheKey reflect.Type) Decoder {
  115. ptr := atomic.LoadPointer(&DECODERS)
  116. cache := *(*map[reflect.Type]Decoder)(ptr)
  117. return cache[cacheKey]
  118. }
  119. func getEncoderFromCache(cacheKey reflect.Type) Encoder {
  120. ptr := atomic.LoadPointer(&ENCODERS)
  121. cache := *(*map[reflect.Type]Encoder)(ptr)
  122. return cache[cacheKey]
  123. }
  124. // RegisterTypeDecoder can register a type for json object
  125. func RegisterTypeDecoder(typ string, fun DecoderFunc) {
  126. typeDecoders[typ] = &funcDecoder{fun}
  127. }
  128. // RegisterFieldDecoder can register a type for json field
  129. func RegisterFieldDecoder(typ string, field string, fun DecoderFunc) {
  130. fieldDecoders[fmt.Sprintf("%s/%s", typ, field)] = &funcDecoder{fun}
  131. }
  132. func RegisterTypeEncoder(typ string, fun EncoderFunc) {
  133. typeEncoders[typ] = &funcEncoder{fun}
  134. }
  135. func RegisterFieldEncoder(typ string, field string, fun EncoderFunc) {
  136. fieldEncoders[fmt.Sprintf("%s/%s", typ, field)] = &funcEncoder{fun}
  137. }
  138. // RegisterExtension can register a custom extension
  139. func RegisterExtension(extension ExtensionFunc) {
  140. extensions = append(extensions, extension)
  141. }
  142. // CleanDecoders cleans decoders registered or cached
  143. func CleanDecoders() {
  144. typeDecoders = map[string]Decoder{}
  145. fieldDecoders = map[string]Decoder{}
  146. atomic.StorePointer(&DECODERS, unsafe.Pointer(&map[string]Decoder{}))
  147. }
  148. // CleanEncoders cleans encoders registered or cached
  149. func CleanEncoders() {
  150. typeEncoders = map[string]Encoder{}
  151. fieldEncoders = map[string]Encoder{}
  152. atomic.StorePointer(&ENCODERS, unsafe.Pointer(&map[string]Encoder{}))
  153. }
  154. type optionalDecoder struct {
  155. valueType reflect.Type
  156. valueDecoder Decoder
  157. }
  158. func (decoder *optionalDecoder) decode(ptr unsafe.Pointer, iter *Iterator) {
  159. if iter.ReadNil() {
  160. *((*unsafe.Pointer)(ptr)) = nil
  161. } else {
  162. if *((*unsafe.Pointer)(ptr)) == nil {
  163. // pointer to null, we have to allocate memory to hold the value
  164. value := reflect.New(decoder.valueType)
  165. decoder.valueDecoder.decode(unsafe.Pointer(value.Pointer()), iter)
  166. *((*uintptr)(ptr)) = value.Pointer()
  167. } else {
  168. // reuse existing instance
  169. decoder.valueDecoder.decode(*((*unsafe.Pointer)(ptr)), iter)
  170. }
  171. }
  172. }
  173. type optionalEncoder struct {
  174. valueEncoder Encoder
  175. }
  176. func (encoder *optionalEncoder) encode(ptr unsafe.Pointer, stream *Stream) {
  177. if *((*unsafe.Pointer)(ptr)) == nil {
  178. stream.WriteNil()
  179. } else {
  180. encoder.valueEncoder.encode(*((*unsafe.Pointer)(ptr)), stream)
  181. }
  182. }
  183. func (encoder *optionalEncoder) encodeInterface(val interface{}, stream *Stream) {
  184. writeToStream(val, stream, encoder)
  185. }
  186. func (encoder *optionalEncoder) isEmpty(ptr unsafe.Pointer) bool {
  187. if *((*unsafe.Pointer)(ptr)) == nil {
  188. return true
  189. } else {
  190. return encoder.valueEncoder.isEmpty(*((*unsafe.Pointer)(ptr)))
  191. }
  192. }
  193. type placeholderEncoder struct {
  194. valueEncoder Encoder
  195. }
  196. func (encoder *placeholderEncoder) encode(ptr unsafe.Pointer, stream *Stream) {
  197. encoder.valueEncoder.encode(ptr, stream)
  198. }
  199. func (encoder *placeholderEncoder) encodeInterface(val interface{}, stream *Stream) {
  200. writeToStream(val, stream, encoder)
  201. }
  202. func (encoder *placeholderEncoder) isEmpty(ptr unsafe.Pointer) bool {
  203. return encoder.valueEncoder.isEmpty(ptr)
  204. }
  205. type placeholderDecoder struct {
  206. valueDecoder Decoder
  207. }
  208. func (decoder *placeholderDecoder) decode(ptr unsafe.Pointer, iter *Iterator) {
  209. decoder.valueDecoder.decode(ptr, iter)
  210. }
  211. // emptyInterface is the header for an interface{} value.
  212. type emptyInterface struct {
  213. typ unsafe.Pointer
  214. word unsafe.Pointer
  215. }
  216. // emptyInterface is the header for an interface with method (not interface{})
  217. type nonEmptyInterface struct {
  218. // see ../runtime/iface.go:/Itab
  219. itab *struct {
  220. ityp unsafe.Pointer // static interface type
  221. typ unsafe.Pointer // dynamic concrete type
  222. link unsafe.Pointer
  223. bad int32
  224. unused int32
  225. fun [100000]unsafe.Pointer // method table
  226. }
  227. word unsafe.Pointer
  228. }
  229. // Read converts an Iterator instance into go interface, same as json.Unmarshal
  230. func (iter *Iterator) ReadVal(obj interface{}) {
  231. typ := reflect.TypeOf(obj)
  232. cacheKey := typ.Elem()
  233. cachedDecoder := getDecoderFromCache(cacheKey)
  234. if cachedDecoder == nil {
  235. decoder, err := decoderOfType(cacheKey)
  236. if err != nil {
  237. iter.Error = err
  238. return
  239. }
  240. cachedDecoder = decoder
  241. addDecoderToCache(cacheKey, decoder)
  242. }
  243. e := (*emptyInterface)(unsafe.Pointer(&obj))
  244. cachedDecoder.decode(e.word, iter)
  245. }
  246. func (stream *Stream) WriteVal(val interface{}) {
  247. if nil == val {
  248. stream.WriteNil()
  249. return
  250. }
  251. typ := reflect.TypeOf(val)
  252. cacheKey := typ
  253. cachedEncoder := getEncoderFromCache(cacheKey)
  254. if cachedEncoder == nil {
  255. encoder, err := encoderOfType(cacheKey)
  256. if err != nil {
  257. stream.Error = err
  258. return
  259. }
  260. cachedEncoder = encoder
  261. addEncoderToCache(cacheKey, encoder)
  262. }
  263. cachedEncoder.encodeInterface(val, stream)
  264. }
  265. type prefix string
  266. func (p prefix) addToDecoder(decoder Decoder, err error) (Decoder, error) {
  267. if err != nil {
  268. return nil, fmt.Errorf("%s: %s", p, err.Error())
  269. }
  270. return decoder, err
  271. }
  272. func (p prefix) addToEncoder(encoder Encoder, err error) (Encoder, error) {
  273. if err != nil {
  274. return nil, fmt.Errorf("%s: %s", p, err.Error())
  275. }
  276. return encoder, err
  277. }
  278. func decoderOfType(typ reflect.Type) (Decoder, error) {
  279. typeName := typ.String()
  280. typeDecoder := typeDecoders[typeName]
  281. if typeDecoder != nil {
  282. return typeDecoder, nil
  283. }
  284. if typ.Kind() == reflect.Ptr {
  285. typeDecoder := typeDecoders[typ.Elem().String()]
  286. if typeDecoder != nil {
  287. return &optionalDecoder{typ.Elem(), typeDecoder}, nil
  288. }
  289. }
  290. cacheKey := typ
  291. cachedDecoder := getDecoderFromCache(cacheKey)
  292. if cachedDecoder != nil {
  293. return cachedDecoder, nil
  294. }
  295. placeholder := &placeholderDecoder{}
  296. addDecoderToCache(cacheKey, placeholder)
  297. newDecoder, err := createDecoderOfType(typ)
  298. placeholder.valueDecoder = newDecoder
  299. addDecoderToCache(cacheKey, newDecoder)
  300. return newDecoder, err
  301. }
  302. func createDecoderOfType(typ reflect.Type) (Decoder, error) {
  303. if typ.String() == "[]uint8" {
  304. return &base64Codec{}, nil
  305. }
  306. if typ.AssignableTo(jsonRawMessageType) {
  307. return &jsonRawMessageCodec{}, nil
  308. }
  309. if typ.AssignableTo(jsonNumberType) {
  310. return &jsonNumberCodec{}, nil
  311. }
  312. if typ.ConvertibleTo(unmarshalerType) {
  313. templateInterface := reflect.New(typ).Elem().Interface()
  314. return &optionalDecoder{typ, &unmarshalerDecoder{extractInterface(templateInterface)}}, nil
  315. }
  316. if typ.ConvertibleTo(anyType) {
  317. return &anyCodec{}, nil
  318. }
  319. switch typ.Kind() {
  320. case reflect.String:
  321. return &stringCodec{}, nil
  322. case reflect.Int:
  323. return &intCodec{}, nil
  324. case reflect.Int8:
  325. return &int8Codec{}, nil
  326. case reflect.Int16:
  327. return &int16Codec{}, nil
  328. case reflect.Int32:
  329. return &int32Codec{}, nil
  330. case reflect.Int64:
  331. return &int64Codec{}, nil
  332. case reflect.Uint:
  333. return &uintCodec{}, nil
  334. case reflect.Uint8:
  335. return &uint8Codec{}, nil
  336. case reflect.Uint16:
  337. return &uint16Codec{}, nil
  338. case reflect.Uint32:
  339. return &uint32Codec{}, nil
  340. case reflect.Uint64:
  341. return &uint64Codec{}, nil
  342. case reflect.Float32:
  343. return &float32Codec{}, nil
  344. case reflect.Float64:
  345. return &float64Codec{}, nil
  346. case reflect.Bool:
  347. return &boolCodec{}, nil
  348. case reflect.Interface:
  349. if typ.NumMethod() == 0 {
  350. return &emptyInterfaceCodec{}, nil
  351. } else {
  352. return &nonEmptyInterfaceCodec{}, nil
  353. }
  354. case reflect.Struct:
  355. return prefix(fmt.Sprintf("[%s]", typ.String())).addToDecoder(decoderOfStruct(typ))
  356. case reflect.Slice:
  357. return prefix("[slice]").addToDecoder(decoderOfSlice(typ))
  358. case reflect.Map:
  359. return prefix("[map]").addToDecoder(decoderOfMap(typ))
  360. case reflect.Ptr:
  361. return prefix("[optional]").addToDecoder(decoderOfOptional(typ))
  362. default:
  363. return nil, fmt.Errorf("unsupported type: %v", typ)
  364. }
  365. }
  366. func encoderOfType(typ reflect.Type) (Encoder, error) {
  367. typeName := typ.String()
  368. typeEncoder := typeEncoders[typeName]
  369. if typeEncoder != nil {
  370. return typeEncoder, nil
  371. }
  372. if typ.Kind() == reflect.Ptr {
  373. typeEncoder := typeEncoders[typ.Elem().String()]
  374. if typeEncoder != nil {
  375. return &optionalEncoder{typeEncoder}, nil
  376. }
  377. }
  378. cacheKey := typ
  379. cachedEncoder := getEncoderFromCache(cacheKey)
  380. if cachedEncoder != nil {
  381. return cachedEncoder, nil
  382. }
  383. placeholder := &placeholderEncoder{}
  384. addEncoderToCache(cacheKey, placeholder)
  385. newEncoder, err := createEncoderOfType(typ)
  386. placeholder.valueEncoder = newEncoder
  387. addEncoderToCache(cacheKey, newEncoder)
  388. return newEncoder, err
  389. }
  390. func createEncoderOfType(typ reflect.Type) (Encoder, error) {
  391. if typ.String() == "[]uint8" {
  392. return &base64Codec{}, nil
  393. }
  394. if typ.AssignableTo(jsonRawMessageType) {
  395. return &jsonRawMessageCodec{}, nil
  396. }
  397. if typ.AssignableTo(jsonNumberType) {
  398. return &jsonNumberCodec{}, nil
  399. }
  400. if typ.ConvertibleTo(marshalerType) {
  401. templateInterface := reflect.New(typ).Elem().Interface()
  402. return &marshalerEncoder{extractInterface(templateInterface)}, nil
  403. }
  404. if typ.ConvertibleTo(anyType) {
  405. return &anyCodec{}, nil
  406. }
  407. kind := typ.Kind()
  408. switch kind {
  409. case reflect.String:
  410. return &stringCodec{}, nil
  411. case reflect.Int:
  412. return &intCodec{}, nil
  413. case reflect.Int8:
  414. return &int8Codec{}, nil
  415. case reflect.Int16:
  416. return &int16Codec{}, nil
  417. case reflect.Int32:
  418. return &int32Codec{}, nil
  419. case reflect.Int64:
  420. return &int64Codec{}, nil
  421. case reflect.Uint:
  422. return &uintCodec{}, nil
  423. case reflect.Uint8:
  424. return &uint8Codec{}, nil
  425. case reflect.Uint16:
  426. return &uint16Codec{}, nil
  427. case reflect.Uint32:
  428. return &uint32Codec{}, nil
  429. case reflect.Uint64:
  430. return &uint64Codec{}, nil
  431. case reflect.Float32:
  432. return &float32Codec{}, nil
  433. case reflect.Float64:
  434. return &float64Codec{}, nil
  435. case reflect.Bool:
  436. return &boolCodec{}, nil
  437. case reflect.Interface:
  438. if typ.NumMethod() == 0 {
  439. return &emptyInterfaceCodec{}, nil
  440. } else {
  441. return &nonEmptyInterfaceCodec{}, nil
  442. }
  443. case reflect.Struct:
  444. return prefix(fmt.Sprintf("[%s]", typ.String())).addToEncoder(encoderOfStruct(typ))
  445. case reflect.Slice:
  446. return prefix("[slice]").addToEncoder(encoderOfSlice(typ))
  447. case reflect.Map:
  448. return prefix("[map]").addToEncoder(encoderOfMap(typ))
  449. case reflect.Ptr:
  450. return prefix("[optional]").addToEncoder(encoderOfOptional(typ))
  451. default:
  452. return nil, fmt.Errorf("unsupported type: %v", typ)
  453. }
  454. }
  455. func decoderOfOptional(typ reflect.Type) (Decoder, error) {
  456. elemType := typ.Elem()
  457. decoder, err := decoderOfType(elemType)
  458. if err != nil {
  459. return nil, err
  460. }
  461. return &optionalDecoder{elemType, decoder}, nil
  462. }
  463. func encoderOfOptional(typ reflect.Type) (Encoder, error) {
  464. elemType := typ.Elem()
  465. decoder, err := encoderOfType(elemType)
  466. if err != nil {
  467. return nil, err
  468. }
  469. return &optionalEncoder{decoder}, nil
  470. }
  471. func decoderOfMap(typ reflect.Type) (Decoder, error) {
  472. decoder, err := decoderOfType(typ.Elem())
  473. if err != nil {
  474. return nil, err
  475. }
  476. mapInterface := reflect.New(typ).Interface()
  477. return &mapDecoder{typ, typ.Key(), typ.Elem(), decoder, extractInterface(mapInterface)}, nil
  478. }
  479. func extractInterface(val interface{}) emptyInterface {
  480. return *((*emptyInterface)(unsafe.Pointer(&val)))
  481. }
  482. func encoderOfMap(typ reflect.Type) (Encoder, error) {
  483. elemType := typ.Elem()
  484. encoder, err := encoderOfType(elemType)
  485. if err != nil {
  486. return nil, err
  487. }
  488. mapInterface := reflect.New(typ).Elem().Interface()
  489. return &mapEncoder{typ, elemType, encoder, *((*emptyInterface)(unsafe.Pointer(&mapInterface)))}, nil
  490. }