any.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. package jsoniter
  2. import (
  3. "errors"
  4. "fmt"
  5. "github.com/modern-go/reflect2"
  6. "io"
  7. "reflect"
  8. "strconv"
  9. "unsafe"
  10. )
  11. // Any generic object representation.
  12. // The lazy json implementation holds []byte and parse lazily.
  13. type Any interface {
  14. LastError() error
  15. ValueType() ValueType
  16. MustBeValid() Any
  17. ToBool() bool
  18. ToInt() int
  19. ToInt32() int32
  20. ToInt64() int64
  21. ToUint() uint
  22. ToUint32() uint32
  23. ToUint64() uint64
  24. ToFloat32() float32
  25. ToFloat64() float64
  26. ToString() string
  27. ToVal(val interface{})
  28. Get(path ...interface{}) Any
  29. Size() int
  30. Keys() []string
  31. GetInterface() interface{}
  32. WriteTo(stream *Stream)
  33. }
  34. type baseAny struct{}
  35. func (any *baseAny) Get(path ...interface{}) Any {
  36. return &invalidAny{baseAny{}, fmt.Errorf("GetIndex %v from simple value", path)}
  37. }
  38. func (any *baseAny) Size() int {
  39. return 0
  40. }
  41. func (any *baseAny) Keys() []string {
  42. return []string{}
  43. }
  44. func (any *baseAny) ToVal(obj interface{}) {
  45. panic("not implemented")
  46. }
  47. // WrapInt32 turn int32 into Any interface
  48. func WrapInt32(val int32) Any {
  49. return &int32Any{baseAny{}, val}
  50. }
  51. // WrapInt64 turn int64 into Any interface
  52. func WrapInt64(val int64) Any {
  53. return &int64Any{baseAny{}, val}
  54. }
  55. // WrapUint32 turn uint32 into Any interface
  56. func WrapUint32(val uint32) Any {
  57. return &uint32Any{baseAny{}, val}
  58. }
  59. // WrapUint64 turn uint64 into Any interface
  60. func WrapUint64(val uint64) Any {
  61. return &uint64Any{baseAny{}, val}
  62. }
  63. // WrapFloat64 turn float64 into Any interface
  64. func WrapFloat64(val float64) Any {
  65. return &floatAny{baseAny{}, val}
  66. }
  67. // WrapString turn string into Any interface
  68. func WrapString(val string) Any {
  69. return &stringAny{baseAny{}, val}
  70. }
  71. // Wrap turn a go object into Any interface
  72. func Wrap(val interface{}) Any {
  73. if val == nil {
  74. return &nilAny{}
  75. }
  76. asAny, isAny := val.(Any)
  77. if isAny {
  78. return asAny
  79. }
  80. typ := reflect2.TypeOf(val)
  81. switch typ.Kind() {
  82. case reflect.Slice:
  83. return wrapArray(val)
  84. case reflect.Struct:
  85. return wrapStruct(val)
  86. case reflect.Map:
  87. return wrapMap(val)
  88. case reflect.String:
  89. return WrapString(val.(string))
  90. case reflect.Int:
  91. if strconv.IntSize == 32 {
  92. return WrapInt32(int32(val.(int)))
  93. }
  94. return WrapInt64(int64(val.(int)))
  95. case reflect.Int8:
  96. return WrapInt32(int32(val.(int8)))
  97. case reflect.Int16:
  98. return WrapInt32(int32(val.(int16)))
  99. case reflect.Int32:
  100. return WrapInt32(val.(int32))
  101. case reflect.Int64:
  102. return WrapInt64(val.(int64))
  103. case reflect.Uint:
  104. if strconv.IntSize == 32 {
  105. return WrapUint32(uint32(val.(uint)))
  106. }
  107. return WrapUint64(uint64(val.(uint)))
  108. case reflect.Uintptr:
  109. if ptrSize == 32 {
  110. return WrapUint32(uint32(val.(uintptr)))
  111. }
  112. return WrapUint64(uint64(val.(uintptr)))
  113. case reflect.Uint8:
  114. return WrapUint32(uint32(val.(uint8)))
  115. case reflect.Uint16:
  116. return WrapUint32(uint32(val.(uint16)))
  117. case reflect.Uint32:
  118. return WrapUint32(uint32(val.(uint32)))
  119. case reflect.Uint64:
  120. return WrapUint64(val.(uint64))
  121. case reflect.Float32:
  122. return WrapFloat64(float64(val.(float32)))
  123. case reflect.Float64:
  124. return WrapFloat64(val.(float64))
  125. case reflect.Bool:
  126. if val.(bool) == true {
  127. return &trueAny{}
  128. }
  129. return &falseAny{}
  130. }
  131. return &invalidAny{baseAny{}, fmt.Errorf("unsupported type: %v", typ)}
  132. }
  133. // ReadAny read next JSON element as an Any object. It is a better json.RawMessage.
  134. func (iter *Iterator) ReadAny() Any {
  135. return iter.readAny()
  136. }
  137. func (iter *Iterator) readAny() Any {
  138. c := iter.nextToken()
  139. switch c {
  140. case '"':
  141. iter.unreadByte()
  142. return &stringAny{baseAny{}, iter.ReadString()}
  143. case 'n':
  144. iter.skipThreeBytes('u', 'l', 'l') // null
  145. return &nilAny{}
  146. case 't':
  147. iter.skipThreeBytes('r', 'u', 'e') // true
  148. return &trueAny{}
  149. case 'f':
  150. iter.skipFourBytes('a', 'l', 's', 'e') // false
  151. return &falseAny{}
  152. case '{':
  153. return iter.readObjectAny()
  154. case '[':
  155. return iter.readArrayAny()
  156. case '-':
  157. return iter.readNumberAny(false)
  158. case 0:
  159. return &invalidAny{baseAny{}, errors.New("input is empty")}
  160. default:
  161. return iter.readNumberAny(true)
  162. }
  163. }
  164. func (iter *Iterator) readNumberAny(positive bool) Any {
  165. iter.startCapture(iter.head - 1)
  166. iter.skipNumber()
  167. lazyBuf := iter.stopCapture()
  168. return &numberLazyAny{baseAny{}, iter.cfg, lazyBuf, nil}
  169. }
  170. func (iter *Iterator) readObjectAny() Any {
  171. iter.startCapture(iter.head - 1)
  172. iter.skipObject()
  173. lazyBuf := iter.stopCapture()
  174. return &objectLazyAny{baseAny{}, iter.cfg, lazyBuf, nil}
  175. }
  176. func (iter *Iterator) readArrayAny() Any {
  177. iter.startCapture(iter.head - 1)
  178. iter.skipArray()
  179. lazyBuf := iter.stopCapture()
  180. return &arrayLazyAny{baseAny{}, iter.cfg, lazyBuf, nil}
  181. }
  182. func locateObjectField(iter *Iterator, target string) []byte {
  183. var found []byte
  184. iter.ReadObjectCB(func(iter *Iterator, field string) bool {
  185. if field == target {
  186. found = iter.SkipAndReturnBytes()
  187. return false
  188. }
  189. iter.Skip()
  190. return true
  191. })
  192. return found
  193. }
  194. func locateArrayElement(iter *Iterator, target int) []byte {
  195. var found []byte
  196. n := 0
  197. iter.ReadArrayCB(func(iter *Iterator) bool {
  198. if n == target {
  199. found = iter.SkipAndReturnBytes()
  200. return false
  201. }
  202. iter.Skip()
  203. n++
  204. return true
  205. })
  206. return found
  207. }
  208. func locatePath(iter *Iterator, path []interface{}) Any {
  209. for i, pathKeyObj := range path {
  210. switch pathKey := pathKeyObj.(type) {
  211. case string:
  212. valueBytes := locateObjectField(iter, pathKey)
  213. if valueBytes == nil {
  214. return newInvalidAny(path[i:])
  215. }
  216. iter.ResetBytes(valueBytes)
  217. case int:
  218. valueBytes := locateArrayElement(iter, pathKey)
  219. if valueBytes == nil {
  220. return newInvalidAny(path[i:])
  221. }
  222. iter.ResetBytes(valueBytes)
  223. case int32:
  224. if '*' == pathKey {
  225. return iter.readAny().Get(path[i:]...)
  226. }
  227. return newInvalidAny(path[i:])
  228. default:
  229. return newInvalidAny(path[i:])
  230. }
  231. }
  232. if iter.Error != nil && iter.Error != io.EOF {
  233. return &invalidAny{baseAny{}, iter.Error}
  234. }
  235. return iter.readAny()
  236. }
  237. var anyType = reflect2.TypeOfPtr((*Any)(nil)).Elem()
  238. func createDecoderOfAny(ctx *ctx, typ reflect2.Type) ValDecoder {
  239. if typ == anyType {
  240. return &directAnyCodec{}
  241. }
  242. if typ.Implements(anyType) {
  243. return &anyCodec{
  244. valType: typ,
  245. }
  246. }
  247. return nil
  248. }
  249. func createEncoderOfAny(ctx *ctx, typ reflect2.Type) ValEncoder {
  250. if typ == anyType {
  251. return &directAnyCodec{}
  252. }
  253. if typ.Implements(anyType) {
  254. return &anyCodec{
  255. valType: typ,
  256. }
  257. }
  258. return nil
  259. }
  260. type anyCodec struct {
  261. valType reflect2.Type
  262. }
  263. func (codec *anyCodec) Decode(ptr unsafe.Pointer, iter *Iterator) {
  264. panic("not implemented")
  265. }
  266. func (codec *anyCodec) Encode(ptr unsafe.Pointer, stream *Stream) {
  267. obj := codec.valType.UnsafeIndirect(ptr)
  268. any := obj.(Any)
  269. any.WriteTo(stream)
  270. }
  271. func (codec *anyCodec) IsEmpty(ptr unsafe.Pointer) bool {
  272. obj := codec.valType.UnsafeIndirect(ptr)
  273. any := obj.(Any)
  274. return any.Size() == 0
  275. }
  276. type directAnyCodec struct {
  277. }
  278. func (codec *directAnyCodec) Decode(ptr unsafe.Pointer, iter *Iterator) {
  279. *(*Any)(ptr) = iter.readAny()
  280. }
  281. func (codec *directAnyCodec) Encode(ptr unsafe.Pointer, stream *Stream) {
  282. any := *(*Any)(ptr)
  283. any.WriteTo(stream)
  284. }
  285. func (codec *directAnyCodec) IsEmpty(ptr unsafe.Pointer) bool {
  286. any := *(*Any)(ptr)
  287. return any.Size() == 0
  288. }