reflect_map.go 8.9 KB

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