You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

union_handler.go 8.2 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. package json
  2. import (
  3. "fmt"
  4. "reflect"
  5. "unsafe"
  6. jsoniter "github.com/json-iterator/go"
  7. "github.com/modern-go/reflect2"
  8. "gitlink.org.cn/cloudream/common/pkgs/types"
  9. stypes "gitlink.org.cn/cloudream/common/utils/serder/types"
  10. ref2 "gitlink.org.cn/cloudream/common/utils/reflect2"
  11. )
  12. type anyTypeUnionExternallyTagged struct {
  13. Union *types.AnyTypeUnion
  14. TypeNameToType map[string]reflect.Type
  15. }
  16. func (u *anyTypeUnionExternallyTagged) Add(typ reflect.Type) error {
  17. err := u.Union.Add(typ)
  18. if err != nil {
  19. return nil
  20. }
  21. u.TypeNameToType[makeDerefFullTypeName(typ)] = typ
  22. return nil
  23. }
  24. type TypeUnionExternallyTagged[T any] struct {
  25. anyTypeUnionExternallyTagged
  26. TUnion *types.TypeUnion[T]
  27. }
  28. func (u *TypeUnionExternallyTagged[T]) AddT(nilValue T) error {
  29. u.Add(reflect.TypeOf(nilValue))
  30. return nil
  31. }
  32. type anyTypeUnionInternallyTagged struct {
  33. Union *types.AnyTypeUnion
  34. TagField string
  35. TagToType map[string]reflect.Type
  36. }
  37. func (u *anyTypeUnionInternallyTagged) Add(typ reflect.Type) error {
  38. err := u.Union.Add(typ)
  39. if err != nil {
  40. return nil
  41. }
  42. // 解引用直到得到结构体类型
  43. structType := typ
  44. for structType.Kind() == reflect.Pointer {
  45. structType = structType.Elem()
  46. }
  47. // 要求内嵌Metadata结构体,那么结构体中的字段名就会是Metadata,
  48. field, ok := structType.FieldByName(ref2.TypeNameOf[stypes.Metadata]())
  49. if !ok {
  50. u.TagToType[makeDerefFullTypeName(structType)] = typ
  51. return nil
  52. }
  53. // 为防同名,检查类型是不是也是Metadata
  54. if field.Type != ref2.TypeOf[stypes.Metadata]() {
  55. u.TagToType[makeDerefFullTypeName(structType)] = typ
  56. return nil
  57. }
  58. tag := field.Tag.Get("union")
  59. if tag == "" {
  60. u.TagToType[makeDerefFullTypeName(structType)] = typ
  61. return nil
  62. }
  63. u.TagToType[tag] = typ
  64. return nil
  65. }
  66. type TypeUnionInternallyTagged[T any] struct {
  67. anyTypeUnionInternallyTagged
  68. TUnion *types.TypeUnion[T]
  69. }
  70. func (u *TypeUnionInternallyTagged[T]) AddT(nilValue T) error {
  71. u.Add(reflect.TypeOf(nilValue))
  72. return nil
  73. }
  74. type UnionHandler struct {
  75. internallyTagged map[reflect.Type]*anyTypeUnionInternallyTagged
  76. externallyTagged map[reflect.Type]*anyTypeUnionExternallyTagged
  77. }
  78. func (h *UnionHandler) UpdateStructDescriptor(structDescriptor *jsoniter.StructDescriptor) {
  79. }
  80. func (h *UnionHandler) CreateMapKeyDecoder(typ reflect2.Type) jsoniter.ValDecoder {
  81. return nil
  82. }
  83. func (h *UnionHandler) CreateMapKeyEncoder(typ reflect2.Type) jsoniter.ValEncoder {
  84. return nil
  85. }
  86. func (h *UnionHandler) CreateDecoder(typ reflect2.Type) jsoniter.ValDecoder {
  87. typ1 := typ.Type1()
  88. if it, ok := h.internallyTagged[typ1]; ok {
  89. return &InternallyTaggedDecoder{
  90. union: it,
  91. }
  92. }
  93. if et, ok := h.externallyTagged[typ1]; ok {
  94. return &ExternallyTaggedDecoder{
  95. union: et,
  96. }
  97. }
  98. return nil
  99. }
  100. func (h *UnionHandler) CreateEncoder(typ reflect2.Type) jsoniter.ValEncoder {
  101. typ1 := typ.Type1()
  102. if it, ok := h.internallyTagged[typ1]; ok {
  103. return &InternallyTaggedEncoder{
  104. union: it,
  105. }
  106. }
  107. if et, ok := h.externallyTagged[typ1]; ok {
  108. return &ExternallyTaggedEncoder{
  109. union: et,
  110. }
  111. }
  112. return nil
  113. }
  114. func (h *UnionHandler) DecorateDecoder(typ reflect2.Type, decoder jsoniter.ValDecoder) jsoniter.ValDecoder {
  115. return decoder
  116. }
  117. func (h *UnionHandler) DecorateEncoder(typ reflect2.Type, encoder jsoniter.ValEncoder) jsoniter.ValEncoder {
  118. return encoder
  119. }
  120. // 以下Encoder/Decoder都是在传入类型/目标类型是TypeUnion的基类(UnionType)时使用
  121. type InternallyTaggedEncoder struct {
  122. union *anyTypeUnionInternallyTagged
  123. }
  124. func (e *InternallyTaggedEncoder) IsEmpty(ptr unsafe.Pointer) bool {
  125. return false
  126. }
  127. func (e *InternallyTaggedEncoder) Encode(ptr unsafe.Pointer, stream *jsoniter.Stream) {
  128. var val any
  129. if e.union.Union.UnionType.NumMethod() == 0 {
  130. // 无方法的interface底层都是eface结构体,所以可以直接转*any
  131. val = *(*any)(ptr)
  132. } else {
  133. // 有方法的interface底层都是iface结构体,可以将其转成eface,转换后不损失类型信息
  134. val = reflect2.IFaceToEFace(ptr)
  135. }
  136. // 可以考虑检查一下Type字段有没有赋值,没有赋值则将其赋值为union Tag指定的值
  137. stream.WriteVal(val)
  138. }
  139. type InternallyTaggedDecoder struct {
  140. union *anyTypeUnionInternallyTagged
  141. }
  142. func (e *InternallyTaggedDecoder) Decode(ptr unsafe.Pointer, iter *jsoniter.Iterator) {
  143. nextTokenKind := iter.WhatIsNext()
  144. if nextTokenKind == jsoniter.NilValue {
  145. iter.Skip()
  146. return
  147. }
  148. raw := iter.ReadAny()
  149. if raw.LastError() != nil {
  150. iter.ReportError("decode TaggedUnionType", "getting object raw:"+raw.LastError().Error())
  151. return
  152. }
  153. tagField := raw.Get(e.union.TagField)
  154. if tagField.LastError() != nil {
  155. iter.ReportError("decode TaggedUnionType", "getting type tag field:"+tagField.LastError().Error())
  156. return
  157. }
  158. typeTag := tagField.ToString()
  159. if typeTag == "" {
  160. iter.ReportError("decode TaggedUnionType", "type tag is empty")
  161. return
  162. }
  163. typ, ok := e.union.TagToType[typeTag]
  164. if !ok {
  165. iter.ReportError("decode TaggedUnionType", fmt.Sprintf("unknow type tag %s in union %s", typeTag, e.union.Union.UnionType.Name()))
  166. return
  167. }
  168. // 如果目标类型已经是个指针类型*T,那么在New的时候就需要使用T,
  169. // 否则New出来的是会是**T,这将导致后续的反序列化出问题
  170. if typ.Kind() == reflect.Pointer {
  171. val := reflect.New(typ.Elem())
  172. raw.ToVal(val.Interface())
  173. retVal := reflect.NewAt(e.union.Union.UnionType, ptr)
  174. retVal.Elem().Set(val)
  175. } else {
  176. val := reflect.New(typ)
  177. raw.ToVal(val.Interface())
  178. retVal := reflect.NewAt(e.union.Union.UnionType, ptr)
  179. retVal.Elem().Set(val.Elem())
  180. }
  181. }
  182. type ExternallyTaggedEncoder struct {
  183. union *anyTypeUnionExternallyTagged
  184. }
  185. func (e *ExternallyTaggedEncoder) IsEmpty(ptr unsafe.Pointer) bool {
  186. return false
  187. }
  188. func (e *ExternallyTaggedEncoder) Encode(ptr unsafe.Pointer, stream *jsoniter.Stream) {
  189. var val any
  190. if e.union.Union.UnionType.NumMethod() == 0 {
  191. // 无方法的interface底层都是eface结构体,所以可以直接转*any
  192. val = *(*any)(ptr)
  193. } else {
  194. // 有方法的interface底层都是iface结构体,可以将其转成eface,转换后不损失类型信息
  195. val = reflect2.IFaceToEFace(ptr)
  196. }
  197. if val == nil {
  198. stream.WriteNil()
  199. return
  200. }
  201. stream.WriteObjectStart()
  202. valType := ref2.TypeOfValue(val)
  203. if !e.union.Union.Include(valType) {
  204. stream.Error = fmt.Errorf("type %v is not in union %v", valType, e.union.Union.UnionType)
  205. return
  206. }
  207. stream.WriteObjectField(makeDerefFullTypeName(valType))
  208. stream.WriteVal(val)
  209. stream.WriteObjectEnd()
  210. }
  211. type ExternallyTaggedDecoder struct {
  212. union *anyTypeUnionExternallyTagged
  213. }
  214. func (e *ExternallyTaggedDecoder) Decode(ptr unsafe.Pointer, iter *jsoniter.Iterator) {
  215. nextTkType := iter.WhatIsNext()
  216. if nextTkType == jsoniter.NilValue {
  217. iter.Skip()
  218. return
  219. }
  220. if nextTkType != jsoniter.ObjectValue {
  221. iter.ReportError("decode UnionType", fmt.Sprintf("unknow next token type %v", nextTkType))
  222. return
  223. }
  224. typeStr := iter.ReadObject()
  225. if typeStr == "" {
  226. iter.ReportError("decode UnionType", "type string is empty")
  227. }
  228. typ, ok := e.union.TypeNameToType[typeStr]
  229. if !ok {
  230. iter.ReportError("decode UnionType", fmt.Sprintf("unknow type string %s in union %v", typeStr, e.union.Union.UnionType))
  231. return
  232. }
  233. // 如果目标类型已经是个指针类型*T,那么在New的时候就需要使用T,
  234. // 否则New出来的是会是**T,这将导致后续的反序列化出问题
  235. if typ.Kind() == reflect.Pointer {
  236. val := reflect.New(typ.Elem())
  237. iter.ReadVal(val.Interface())
  238. retVal := reflect.NewAt(e.union.Union.UnionType, ptr)
  239. retVal.Elem().Set(val)
  240. } else {
  241. val := reflect.New(typ)
  242. iter.ReadVal(val.Interface())
  243. retVal := reflect.NewAt(e.union.Union.UnionType, ptr)
  244. retVal.Elem().Set(val.Elem())
  245. }
  246. if iter.ReadObject() != "" {
  247. iter.ReportError("decode UnionType", "there should be only one fields in the json object")
  248. }
  249. }
  250. func makeDerefFullTypeName(typ reflect.Type) string {
  251. realType := typ
  252. for realType.Kind() == reflect.Pointer {
  253. realType = realType.Elem()
  254. }
  255. return fmt.Sprintf("%s.%s", realType.PkgPath(), realType.Name())
  256. }