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 9.4 kB

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