any.go 6.8 KB

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