feature_reflect_extension.go 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  1. package jsoniter
  2. import (
  3. "fmt"
  4. "reflect"
  5. "strings"
  6. "unicode"
  7. "unsafe"
  8. )
  9. var typeDecoders = map[string]ValDecoder{}
  10. var fieldDecoders = map[string]ValDecoder{}
  11. var typeEncoders = map[string]ValEncoder{}
  12. var fieldEncoders = map[string]ValEncoder{}
  13. var extensions = []Extension{}
  14. type StructDescriptor struct {
  15. onePtrEmbedded bool
  16. onePtrOptimization bool
  17. Type reflect.Type
  18. Fields []*Binding
  19. }
  20. func (structDescriptor *StructDescriptor) GetField(fieldName string) *Binding {
  21. for _, binding := range structDescriptor.Fields {
  22. if binding.Field.Name == fieldName {
  23. return binding
  24. }
  25. }
  26. return nil
  27. }
  28. type Binding struct {
  29. Field *reflect.StructField
  30. FromNames []string
  31. ToNames []string
  32. Encoder ValEncoder
  33. Decoder ValDecoder
  34. }
  35. type Extension interface {
  36. UpdateStructDescriptor(structDescriptor *StructDescriptor)
  37. CreateDecoder(typ reflect.Type) ValDecoder
  38. CreateEncoder(typ reflect.Type) ValEncoder
  39. DecorateDecoder(typ reflect.Type, decoder ValDecoder) ValDecoder
  40. DecorateEncoder(typ reflect.Type, encoder ValEncoder) ValEncoder
  41. }
  42. type DummyExtension struct {
  43. }
  44. func (extension *DummyExtension) UpdateStructDescriptor(structDescriptor *StructDescriptor) {
  45. }
  46. func (extension *DummyExtension) CreateDecoder(typ reflect.Type) ValDecoder {
  47. return nil
  48. }
  49. func (extension *DummyExtension) CreateEncoder(typ reflect.Type) ValEncoder {
  50. return nil
  51. }
  52. func (extension *DummyExtension) DecorateDecoder(typ reflect.Type, decoder ValDecoder) ValDecoder {
  53. return decoder
  54. }
  55. func (extension *DummyExtension) DecorateEncoder(typ reflect.Type, encoder ValEncoder) ValEncoder {
  56. return encoder
  57. }
  58. type funcDecoder struct {
  59. fun DecoderFunc
  60. }
  61. func (decoder *funcDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) {
  62. decoder.fun(ptr, iter)
  63. }
  64. type funcEncoder struct {
  65. fun EncoderFunc
  66. isEmptyFunc func(ptr unsafe.Pointer) bool
  67. }
  68. func (encoder *funcEncoder) Encode(ptr unsafe.Pointer, stream *Stream) {
  69. encoder.fun(ptr, stream)
  70. }
  71. func (encoder *funcEncoder) EncodeInterface(val interface{}, stream *Stream) {
  72. WriteToStream(val, stream, encoder)
  73. }
  74. func (encoder *funcEncoder) IsEmpty(ptr unsafe.Pointer) bool {
  75. if encoder.isEmptyFunc == nil {
  76. return false
  77. }
  78. return encoder.isEmptyFunc(ptr)
  79. }
  80. func RegisterTypeDecoderFunc(typ string, fun DecoderFunc) {
  81. typeDecoders[typ] = &funcDecoder{fun}
  82. }
  83. func RegisterTypeDecoder(typ string, decoder ValDecoder) {
  84. typeDecoders[typ] = decoder
  85. }
  86. func RegisterFieldDecoderFunc(typ string, field string, fun DecoderFunc) {
  87. RegisterFieldDecoder(typ, field, &funcDecoder{fun})
  88. }
  89. func RegisterFieldDecoder(typ string, field string, decoder ValDecoder) {
  90. fieldDecoders[fmt.Sprintf("%s/%s", typ, field)] = decoder
  91. }
  92. func RegisterTypeEncoderFunc(typ string, fun EncoderFunc, isEmptyFunc func(unsafe.Pointer) bool) {
  93. typeEncoders[typ] = &funcEncoder{fun, isEmptyFunc}
  94. }
  95. func RegisterTypeEncoder(typ string, encoder ValEncoder) {
  96. typeEncoders[typ] = encoder
  97. }
  98. func RegisterFieldEncoderFunc(typ string, field string, fun EncoderFunc, isEmptyFunc func(unsafe.Pointer) bool) {
  99. RegisterFieldEncoder(typ, field, &funcEncoder{fun, isEmptyFunc})
  100. }
  101. func RegisterFieldEncoder(typ string, field string, encoder ValEncoder) {
  102. fieldEncoders[fmt.Sprintf("%s/%s", typ, field)] = encoder
  103. }
  104. func RegisterExtension(extension Extension) {
  105. extensions = append(extensions, extension)
  106. }
  107. func getTypeDecoderFromExtension(typ reflect.Type) ValDecoder {
  108. decoder := _getTypeDecoderFromExtension(typ)
  109. if decoder != nil {
  110. for _, extension := range extensions {
  111. decoder = extension.DecorateDecoder(typ, decoder)
  112. }
  113. }
  114. return decoder
  115. }
  116. func _getTypeDecoderFromExtension(typ reflect.Type) ValDecoder {
  117. for _, extension := range extensions {
  118. decoder := extension.CreateDecoder(typ)
  119. if decoder != nil {
  120. return decoder
  121. }
  122. }
  123. typeName := typ.String()
  124. decoder := typeDecoders[typeName]
  125. if decoder != nil {
  126. return decoder
  127. }
  128. if typ.Kind() == reflect.Ptr {
  129. decoder := typeDecoders[typ.Elem().String()]
  130. if decoder != nil {
  131. return &optionalDecoder{typ.Elem(), decoder}
  132. }
  133. }
  134. return nil
  135. }
  136. func getTypeEncoderFromExtension(typ reflect.Type) ValEncoder {
  137. encoder := _getTypeEncoderFromExtension(typ)
  138. if encoder != nil {
  139. for _, extension := range extensions {
  140. encoder = extension.DecorateEncoder(typ, encoder)
  141. }
  142. }
  143. return encoder
  144. }
  145. func _getTypeEncoderFromExtension(typ reflect.Type) ValEncoder {
  146. for _, extension := range extensions {
  147. encoder := extension.CreateEncoder(typ)
  148. if encoder != nil {
  149. return encoder
  150. }
  151. }
  152. typeName := typ.String()
  153. encoder := typeEncoders[typeName]
  154. if encoder != nil {
  155. return encoder
  156. }
  157. if typ.Kind() == reflect.Ptr {
  158. encoder := typeEncoders[typ.Elem().String()]
  159. if encoder != nil {
  160. return &optionalEncoder{encoder}
  161. }
  162. }
  163. return nil
  164. }
  165. func describeStruct(cfg *frozenConfig, typ reflect.Type) (*StructDescriptor, error) {
  166. headAnonymousBindings := []*Binding{}
  167. tailAnonymousBindings := []*Binding{}
  168. bindings := []*Binding{}
  169. for i := 0; i < typ.NumField(); i++ {
  170. field := typ.Field(i)
  171. if field.Anonymous {
  172. if field.Type.Kind() == reflect.Struct {
  173. structDescriptor, err := describeStruct(cfg, field.Type)
  174. if err != nil {
  175. return nil, err
  176. }
  177. for _, binding := range structDescriptor.Fields {
  178. binding.Encoder = &structFieldEncoder{&field, binding.Encoder, false}
  179. binding.Decoder = &structFieldDecoder{&field, binding.Decoder}
  180. if field.Offset == 0 {
  181. headAnonymousBindings = append(headAnonymousBindings, binding)
  182. } else {
  183. tailAnonymousBindings = append(tailAnonymousBindings, binding)
  184. }
  185. }
  186. continue
  187. } else if field.Type.Kind() == reflect.Ptr && field.Type.Elem().Kind() == reflect.Struct {
  188. structDescriptor, err := describeStruct(cfg, field.Type.Elem())
  189. if err != nil {
  190. return nil, err
  191. }
  192. for _, binding := range structDescriptor.Fields {
  193. cloneField := field
  194. cloneField.Name = binding.Field.Name
  195. binding.Encoder = &optionalEncoder{binding.Encoder}
  196. binding.Encoder = &structFieldEncoder{&cloneField, binding.Encoder, false}
  197. binding.Decoder = &deferenceDecoder{field.Type.Elem(), binding.Decoder}
  198. binding.Decoder = &structFieldDecoder{&cloneField, binding.Decoder}
  199. if field.Offset == 0 {
  200. headAnonymousBindings = append(headAnonymousBindings, binding)
  201. } else {
  202. tailAnonymousBindings = append(tailAnonymousBindings, binding)
  203. }
  204. }
  205. continue
  206. }
  207. }
  208. tagParts := strings.Split(field.Tag.Get("json"), ",")
  209. fieldNames := calcFieldNames(field.Name, tagParts[0], string(field.Tag))
  210. fieldCacheKey := fmt.Sprintf("%s/%s", typ.String(), field.Name)
  211. decoder := fieldDecoders[fieldCacheKey]
  212. if decoder == nil {
  213. var err error
  214. decoder, err = decoderOfType(cfg, field.Type)
  215. if err != nil {
  216. return nil, err
  217. }
  218. }
  219. encoder := fieldEncoders[fieldCacheKey]
  220. if encoder == nil {
  221. var err error
  222. encoder, err = encoderOfType(cfg, field.Type)
  223. if err != nil {
  224. return nil, err
  225. }
  226. // map is stored as pointer in the struct
  227. if field.Type.Kind() == reflect.Map {
  228. encoder = &optionalEncoder{encoder}
  229. }
  230. }
  231. binding := &Binding{
  232. Field: &field,
  233. FromNames: fieldNames,
  234. ToNames: fieldNames,
  235. Decoder: decoder,
  236. Encoder: encoder,
  237. }
  238. bindings = append(bindings, binding)
  239. }
  240. return createStructDescriptor(cfg, typ, bindings, headAnonymousBindings, tailAnonymousBindings), nil
  241. }
  242. func createStructDescriptor(cfg *frozenConfig, typ reflect.Type, bindings []*Binding, headAnonymousBindings []*Binding, tailAnonymousBindings []*Binding) *StructDescriptor {
  243. onePtrEmbedded := false
  244. onePtrOptimization := false
  245. if typ.NumField() == 1 {
  246. firstField := typ.Field(0)
  247. switch firstField.Type.Kind() {
  248. case reflect.Ptr:
  249. if firstField.Anonymous && firstField.Type.Elem().Kind() == reflect.Struct {
  250. onePtrEmbedded = true
  251. }
  252. fallthrough
  253. case reflect.Map:
  254. fallthrough
  255. case reflect.Slice:
  256. onePtrOptimization = true
  257. }
  258. }
  259. structDescriptor := &StructDescriptor{
  260. onePtrEmbedded: onePtrEmbedded,
  261. onePtrOptimization: onePtrOptimization,
  262. Type: typ,
  263. Fields: bindings,
  264. }
  265. for _, extension := range extensions {
  266. extension.UpdateStructDescriptor(structDescriptor)
  267. }
  268. processTags(structDescriptor, cfg)
  269. // insert anonymous bindings to the head
  270. structDescriptor.Fields = append(headAnonymousBindings, structDescriptor.Fields...)
  271. structDescriptor.Fields = append(structDescriptor.Fields, tailAnonymousBindings...)
  272. return structDescriptor
  273. }
  274. func processTags(structDescriptor *StructDescriptor, cfg *frozenConfig) {
  275. for _, binding := range structDescriptor.Fields {
  276. shouldOmitEmpty := false
  277. tagParts := strings.Split(binding.Field.Tag.Get("json"), ",")
  278. for _, tagPart := range tagParts[1:] {
  279. if tagPart == "omitempty" {
  280. shouldOmitEmpty = true
  281. } else if tagPart == "string" {
  282. if binding.Field.Type.Kind() == reflect.String {
  283. binding.Decoder = &stringModeStringDecoder{binding.Decoder, cfg}
  284. binding.Encoder = &stringModeStringEncoder{binding.Encoder, cfg}
  285. } else {
  286. binding.Decoder = &stringModeNumberDecoder{binding.Decoder}
  287. binding.Encoder = &stringModeNumberEncoder{binding.Encoder}
  288. }
  289. }
  290. }
  291. binding.Decoder = &structFieldDecoder{binding.Field, binding.Decoder}
  292. binding.Encoder = &structFieldEncoder{binding.Field, binding.Encoder, shouldOmitEmpty}
  293. }
  294. }
  295. func calcFieldNames(originalFieldName string, tagProvidedFieldName string, wholeTag string) []string {
  296. // ignore?
  297. if wholeTag == "-" {
  298. return []string{}
  299. }
  300. // rename?
  301. var fieldNames []string
  302. if tagProvidedFieldName == "" {
  303. fieldNames = []string{originalFieldName}
  304. } else {
  305. fieldNames = []string{tagProvidedFieldName}
  306. }
  307. // private?
  308. isNotExported := unicode.IsLower(rune(originalFieldName[0]))
  309. if isNotExported {
  310. fieldNames = []string{}
  311. }
  312. return fieldNames
  313. }