reflect_dynamic.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package jsoniter
  2. import (
  3. "github.com/modern-go/reflect2"
  4. "reflect"
  5. "unsafe"
  6. )
  7. type dynamicEncoder struct {
  8. valType reflect2.Type
  9. }
  10. func (encoder *dynamicEncoder) Encode(ptr unsafe.Pointer, stream *Stream) {
  11. obj := encoder.valType.UnsafeIndirect(ptr)
  12. stream.WriteVal(obj)
  13. }
  14. func (encoder *dynamicEncoder) IsEmpty(ptr unsafe.Pointer) bool {
  15. return encoder.valType.UnsafeIndirect(ptr) == nil
  16. }
  17. type efaceDecoder struct {
  18. }
  19. func (decoder *efaceDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) {
  20. pObj := (*interface{})(ptr)
  21. obj := *pObj
  22. if obj == nil {
  23. *pObj = iter.Read()
  24. return
  25. }
  26. typ := reflect2.TypeOf(obj)
  27. if typ.Kind() != reflect.Ptr {
  28. *pObj = iter.Read()
  29. return
  30. }
  31. ptrType := typ.(*reflect2.UnsafePtrType)
  32. ptrElemType := ptrType.Elem()
  33. if iter.WhatIsNext() == NilValue {
  34. if ptrElemType.Kind() != reflect.Ptr {
  35. iter.skipFourBytes('n', 'u', 'l', 'l')
  36. *pObj = nil
  37. return
  38. }
  39. }
  40. if reflect2.IsNil(obj) {
  41. obj := ptrElemType.New()
  42. iter.ReadVal(obj)
  43. *pObj = obj
  44. return
  45. }
  46. iter.ReadVal(obj)
  47. }
  48. type ifaceDecoder struct {
  49. valType *reflect2.UnsafeIFaceType
  50. }
  51. func (decoder *ifaceDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) {
  52. if iter.ReadNil() {
  53. decoder.valType.UnsafeSet(ptr, decoder.valType.UnsafeNew())
  54. return
  55. }
  56. obj := decoder.valType.UnsafeIndirect(ptr)
  57. if reflect2.IsNil(obj) {
  58. iter.ReportError("decode non empty interface", "can not unmarshal into nil")
  59. return
  60. }
  61. iter.ReadVal(obj)
  62. }