reflect_map.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. package jsoniter
  2. import (
  3. "fmt"
  4. "github.com/modern-go/reflect2"
  5. "io"
  6. "reflect"
  7. "sort"
  8. "unsafe"
  9. )
  10. func decoderOfMap(ctx *ctx, typ reflect2.Type) ValDecoder {
  11. mapType := typ.(*reflect2.UnsafeMapType)
  12. keyDecoder := decoderOfMapKey(ctx.append("[mapKey]"), mapType.Key())
  13. elemDecoder := decoderOfType(ctx.append("[mapElem]"), mapType.Elem())
  14. return &mapDecoder{
  15. mapType: mapType,
  16. keyType: mapType.Key(),
  17. elemType: mapType.Elem(),
  18. keyDecoder: keyDecoder,
  19. elemDecoder: elemDecoder,
  20. }
  21. }
  22. func encoderOfMap(ctx *ctx, typ reflect2.Type) ValEncoder {
  23. mapType := typ.(*reflect2.UnsafeMapType)
  24. if ctx.sortMapKeys {
  25. return &sortKeysMapEncoder{
  26. mapType: mapType,
  27. keyEncoder: encoderOfMapKey(ctx.append("[mapKey]"), mapType.Key()),
  28. elemEncoder: encoderOfType(ctx.append("[mapElem]"), mapType.Elem()),
  29. }
  30. }
  31. return &mapEncoder{
  32. mapType: mapType,
  33. keyEncoder: encoderOfMapKey(ctx.append("[mapKey]"), mapType.Key()),
  34. elemEncoder: encoderOfType(ctx.append("[mapElem]"), mapType.Elem()),
  35. }
  36. }
  37. func decoderOfMapKey(ctx *ctx, typ reflect2.Type) ValDecoder {
  38. for _, extension := range ctx.extensions {
  39. decoder := extension.CreateMapKeyDecoder(typ)
  40. if decoder != nil {
  41. return decoder
  42. }
  43. }
  44. switch typ.Kind() {
  45. case reflect.String:
  46. return decoderOfType(ctx, reflect2.DefaultTypeOfKind(reflect.String))
  47. case reflect.Bool,
  48. reflect.Uint8, reflect.Int8,
  49. reflect.Uint16, reflect.Int16,
  50. reflect.Uint32, reflect.Int32,
  51. reflect.Uint64, reflect.Int64,
  52. reflect.Uint, reflect.Int,
  53. reflect.Float32, reflect.Float64,
  54. reflect.Uintptr:
  55. typ = reflect2.DefaultTypeOfKind(typ.Kind())
  56. return &numericMapKeyDecoder{decoderOfType(ctx, typ)}
  57. default:
  58. ptrType := reflect2.PtrTo(typ)
  59. if ptrType.Implements(textMarshalerType) {
  60. return &referenceDecoder{
  61. &textUnmarshalerDecoder{
  62. valType: ptrType,
  63. },
  64. }
  65. }
  66. if typ.Implements(textMarshalerType) {
  67. return &textUnmarshalerDecoder{
  68. valType: typ,
  69. }
  70. }
  71. return &lazyErrorDecoder{err: fmt.Errorf("unsupported map key type: %v", typ)}
  72. }
  73. }
  74. func encoderOfMapKey(ctx *ctx, typ reflect2.Type) ValEncoder {
  75. for _, extension := range ctx.extensions {
  76. encoder := extension.CreateMapKeyEncoder(typ)
  77. if encoder != nil {
  78. return encoder
  79. }
  80. }
  81. switch typ.Kind() {
  82. case reflect.String:
  83. return encoderOfType(ctx, reflect2.DefaultTypeOfKind(reflect.String))
  84. case reflect.Bool,
  85. reflect.Uint8, reflect.Int8,
  86. reflect.Uint16, reflect.Int16,
  87. reflect.Uint32, reflect.Int32,
  88. reflect.Uint64, reflect.Int64,
  89. reflect.Uint, reflect.Int,
  90. reflect.Float32, reflect.Float64,
  91. reflect.Uintptr:
  92. typ = reflect2.DefaultTypeOfKind(typ.Kind())
  93. return &numericMapKeyEncoder{encoderOfType(ctx, typ)}
  94. default:
  95. if typ == textMarshalerType {
  96. return &directTextMarshalerEncoder{
  97. stringEncoder: ctx.EncoderOf(reflect2.TypeOf("")),
  98. }
  99. }
  100. if typ.Implements(textMarshalerType) {
  101. return &textMarshalerEncoder{
  102. valType: typ,
  103. stringEncoder: ctx.EncoderOf(reflect2.TypeOf("")),
  104. }
  105. }
  106. if typ.Kind() == reflect.Interface {
  107. return &dynamicMapKeyEncoder{ctx, typ}
  108. }
  109. return &lazyErrorEncoder{err: fmt.Errorf("unsupported map key type: %v", typ)}
  110. }
  111. }
  112. type mapDecoder struct {
  113. mapType *reflect2.UnsafeMapType
  114. keyType reflect2.Type
  115. elemType reflect2.Type
  116. keyDecoder ValDecoder
  117. elemDecoder ValDecoder
  118. }
  119. func (decoder *mapDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) {
  120. mapType := decoder.mapType
  121. c := iter.nextToken()
  122. if c == 'n' {
  123. iter.skipThreeBytes('u', 'l', 'l')
  124. *(*unsafe.Pointer)(ptr) = nil
  125. mapType.UnsafeSet(ptr, mapType.UnsafeNew())
  126. return
  127. }
  128. if mapType.UnsafeIsNil(ptr) {
  129. mapType.UnsafeSet(ptr, mapType.UnsafeMakeMap(0))
  130. }
  131. if c != '{' {
  132. iter.ReportError("ReadMapCB", `expect { or n, but found `+string([]byte{c}))
  133. return
  134. }
  135. c = iter.nextToken()
  136. if c == '}' {
  137. return
  138. }
  139. if c != '"' {
  140. iter.ReportError("ReadMapCB", `expect " after }, but found `+string([]byte{c}))
  141. return
  142. }
  143. iter.unreadByte()
  144. key := decoder.keyType.UnsafeNew()
  145. decoder.keyDecoder.Decode(key, iter)
  146. c = iter.nextToken()
  147. if c != ':' {
  148. iter.ReportError("ReadMapCB", "expect : after object field, but found "+string([]byte{c}))
  149. return
  150. }
  151. elem := decoder.elemType.UnsafeNew()
  152. decoder.elemDecoder.Decode(elem, iter)
  153. decoder.mapType.UnsafeSetIndex(ptr, key, elem)
  154. for c = iter.nextToken(); c == ','; c = iter.nextToken() {
  155. key := decoder.keyType.UnsafeNew()
  156. decoder.keyDecoder.Decode(key, iter)
  157. c = iter.nextToken()
  158. if c != ':' {
  159. iter.ReportError("ReadMapCB", "expect : after object field, but found "+string([]byte{c}))
  160. return
  161. }
  162. elem := decoder.elemType.UnsafeNew()
  163. decoder.elemDecoder.Decode(elem, iter)
  164. decoder.mapType.UnsafeSetIndex(ptr, key, elem)
  165. }
  166. if c != '}' {
  167. iter.ReportError("ReadMapCB", `expect }, but found `+string([]byte{c}))
  168. }
  169. }
  170. type numericMapKeyDecoder struct {
  171. decoder ValDecoder
  172. }
  173. func (decoder *numericMapKeyDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) {
  174. c := iter.nextToken()
  175. if c != '"' {
  176. iter.ReportError("ReadMapCB", `expect ", but found `+string([]byte{c}))
  177. return
  178. }
  179. decoder.decoder.Decode(ptr, iter)
  180. c = iter.nextToken()
  181. if c != '"' {
  182. iter.ReportError("ReadMapCB", `expect ", but found `+string([]byte{c}))
  183. return
  184. }
  185. }
  186. type numericMapKeyEncoder struct {
  187. encoder ValEncoder
  188. }
  189. func (encoder *numericMapKeyEncoder) Encode(ptr unsafe.Pointer, stream *Stream) {
  190. stream.writeByte('"')
  191. encoder.encoder.Encode(ptr, stream)
  192. stream.writeByte('"')
  193. }
  194. func (encoder *numericMapKeyEncoder) IsEmpty(ptr unsafe.Pointer) bool {
  195. return false
  196. }
  197. type dynamicMapKeyEncoder struct {
  198. ctx *ctx
  199. valType reflect2.Type
  200. }
  201. func (encoder *dynamicMapKeyEncoder) Encode(ptr unsafe.Pointer, stream *Stream) {
  202. obj := encoder.valType.UnsafeIndirect(ptr)
  203. encoderOfMapKey(encoder.ctx, reflect2.TypeOf(obj)).Encode(reflect2.PtrOf(obj), stream)
  204. }
  205. func (encoder *dynamicMapKeyEncoder) IsEmpty(ptr unsafe.Pointer) bool {
  206. obj := encoder.valType.UnsafeIndirect(ptr)
  207. return encoderOfMapKey(encoder.ctx, reflect2.TypeOf(obj)).IsEmpty(reflect2.PtrOf(obj))
  208. }
  209. type mapEncoder struct {
  210. mapType *reflect2.UnsafeMapType
  211. keyEncoder ValEncoder
  212. elemEncoder ValEncoder
  213. }
  214. func (encoder *mapEncoder) Encode(ptr unsafe.Pointer, stream *Stream) {
  215. stream.WriteObjectStart()
  216. iter := encoder.mapType.UnsafeIterate(ptr)
  217. for i := 0; iter.HasNext(); i++ {
  218. if i != 0 {
  219. stream.WriteMore()
  220. }
  221. key, elem := iter.UnsafeNext()
  222. encoder.keyEncoder.Encode(key, stream)
  223. if stream.indention > 0 {
  224. stream.writeTwoBytes(byte(':'), byte(' '))
  225. } else {
  226. stream.writeByte(':')
  227. }
  228. encoder.elemEncoder.Encode(elem, stream)
  229. }
  230. stream.WriteObjectEnd()
  231. }
  232. func (encoder *mapEncoder) IsEmpty(ptr unsafe.Pointer) bool {
  233. iter := encoder.mapType.UnsafeIterate(ptr)
  234. return !iter.HasNext()
  235. }
  236. type sortKeysMapEncoder struct {
  237. mapType *reflect2.UnsafeMapType
  238. keyEncoder ValEncoder
  239. elemEncoder ValEncoder
  240. }
  241. func (encoder *sortKeysMapEncoder) Encode(ptr unsafe.Pointer, stream *Stream) {
  242. if *(*unsafe.Pointer)(ptr) == nil {
  243. stream.WriteNil()
  244. return
  245. }
  246. stream.WriteObjectStart()
  247. mapIter := encoder.mapType.UnsafeIterate(ptr)
  248. subStream := stream.cfg.BorrowStream(nil)
  249. subIter := stream.cfg.BorrowIterator(nil)
  250. keyValues := encodedKeyValues{}
  251. for mapIter.HasNext() {
  252. subStream.buf = make([]byte, 0, 64)
  253. key, elem := mapIter.UnsafeNext()
  254. encoder.keyEncoder.Encode(key, subStream)
  255. if subStream.Error != nil && subStream.Error != io.EOF && stream.Error == nil {
  256. stream.Error = subStream.Error
  257. }
  258. encodedKey := subStream.Buffer()
  259. subIter.ResetBytes(encodedKey)
  260. decodedKey := subIter.ReadString()
  261. if stream.indention > 0 {
  262. subStream.writeTwoBytes(byte(':'), byte(' '))
  263. } else {
  264. subStream.writeByte(':')
  265. }
  266. encoder.elemEncoder.Encode(elem, subStream)
  267. keyValues = append(keyValues, encodedKV{
  268. key: decodedKey,
  269. keyValue: subStream.Buffer(),
  270. })
  271. }
  272. sort.Sort(keyValues)
  273. for i, keyValue := range keyValues {
  274. if i != 0 {
  275. stream.WriteMore()
  276. }
  277. stream.Write(keyValue.keyValue)
  278. }
  279. stream.WriteObjectEnd()
  280. stream.cfg.ReturnStream(subStream)
  281. stream.cfg.ReturnIterator(subIter)
  282. }
  283. func (encoder *sortKeysMapEncoder) IsEmpty(ptr unsafe.Pointer) bool {
  284. iter := encoder.mapType.UnsafeIterate(ptr)
  285. return !iter.HasNext()
  286. }
  287. type encodedKeyValues []encodedKV
  288. type encodedKV struct {
  289. key string
  290. keyValue []byte
  291. }
  292. func (sv encodedKeyValues) Len() int { return len(sv) }
  293. func (sv encodedKeyValues) Swap(i, j int) { sv[i], sv[j] = sv[j], sv[i] }
  294. func (sv encodedKeyValues) Less(i, j int) bool { return sv[i].key < sv[j].key }