feature_adapter.go 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. package jsoniter
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "errors"
  6. "io"
  7. "reflect"
  8. "unsafe"
  9. )
  10. // Unmarshal adapts to json/encoding Unmarshal API
  11. //
  12. // Unmarshal parses the JSON-encoded data and stores the result in the value pointed to by v.
  13. // Refer to https://godoc.org/encoding/json#Unmarshal for more information
  14. func Unmarshal(data []byte, v interface{}) error {
  15. data = data[:lastNotSpacePos(data)]
  16. iter := ParseBytes(data)
  17. typ := reflect.TypeOf(v)
  18. if typ.Kind() != reflect.Ptr {
  19. // return non-pointer error
  20. return errors.New("the second param must be ptr type")
  21. }
  22. iter.ReadVal(v)
  23. if iter.head == iter.tail {
  24. iter.loadMore()
  25. }
  26. if iter.Error == io.EOF {
  27. return nil
  28. }
  29. if iter.Error == nil {
  30. iter.reportError("Unmarshal", "there are bytes left after unmarshal")
  31. }
  32. return iter.Error
  33. }
  34. func UnmarshalAny(data []byte) (Any, error) {
  35. data = data[:lastNotSpacePos(data)]
  36. iter := ParseBytes(data)
  37. any := iter.ReadAny()
  38. if iter.head == iter.tail {
  39. iter.loadMore()
  40. }
  41. if iter.Error == io.EOF {
  42. return any, nil
  43. }
  44. if iter.Error == nil {
  45. iter.reportError("UnmarshalAny", "there are bytes left after unmarshal")
  46. }
  47. return any, iter.Error
  48. }
  49. func lastNotSpacePos(data []byte) int {
  50. for i := len(data) - 1; i >= 0; i-- {
  51. if data[i] != ' ' && data[i] != '\t' && data[i] != '\r' && data[i] != '\n' {
  52. return i + 1
  53. }
  54. }
  55. return 0
  56. }
  57. func UnmarshalFromString(str string, v interface{}) error {
  58. data := []byte(str)
  59. data = data[:lastNotSpacePos(data)]
  60. iter := ParseBytes(data)
  61. iter.ReadVal(v)
  62. if iter.head == iter.tail {
  63. iter.loadMore()
  64. }
  65. if iter.Error == io.EOF {
  66. return nil
  67. }
  68. if iter.Error == nil {
  69. iter.reportError("UnmarshalFromString", "there are bytes left after unmarshal")
  70. }
  71. return iter.Error
  72. }
  73. func UnmarshalAnyFromString(str string) (Any, error) {
  74. data := []byte(str)
  75. data = data[:lastNotSpacePos(data)]
  76. iter := ParseBytes(data)
  77. any := iter.ReadAny()
  78. if iter.head == iter.tail {
  79. iter.loadMore()
  80. }
  81. if iter.Error == io.EOF {
  82. return any, nil
  83. }
  84. if iter.Error == nil {
  85. iter.reportError("UnmarshalAnyFromString", "there are bytes left after unmarshal")
  86. }
  87. return nil, iter.Error
  88. }
  89. // Marshal adapts to json/encoding Marshal API
  90. //
  91. // Marshal returns the JSON encoding of v, adapts to json/encoding Marshal API
  92. // Refer to https://godoc.org/encoding/json#Marshal for more information
  93. func Marshal(v interface{}) ([]byte, error) {
  94. stream := NewStream(nil, 256)
  95. stream.WriteVal(v)
  96. if stream.Error != nil {
  97. return nil, stream.Error
  98. }
  99. return stream.Buffer(), nil
  100. }
  101. func MarshalToString(v interface{}) (string, error) {
  102. buf, err := Marshal(v)
  103. if err != nil {
  104. return "", err
  105. }
  106. return string(buf), nil
  107. }
  108. // NewDecoder adapts to json/stream NewDecoder API.
  109. //
  110. // NewDecoder returns a new decoder that reads from r.
  111. //
  112. // Instead of a json/encoding Decoder, an AdaptedDecoder is returned
  113. // Refer to https://godoc.org/encoding/json#NewDecoder for more information
  114. func NewDecoder(reader io.Reader) *AdaptedDecoder {
  115. iter := Parse(reader, 512)
  116. return &AdaptedDecoder{iter}
  117. }
  118. // AdaptedDecoder reads and decodes JSON values from an input stream.
  119. // AdaptedDecoder provides identical APIs with json/stream Decoder (Token() and UseNumber() are in progress)
  120. type AdaptedDecoder struct {
  121. iter *Iterator
  122. }
  123. func (adapter *AdaptedDecoder) Decode(obj interface{}) error {
  124. adapter.iter.ReadVal(obj)
  125. err := adapter.iter.Error
  126. if err == io.EOF {
  127. return nil
  128. }
  129. return adapter.iter.Error
  130. }
  131. func (adapter *AdaptedDecoder) More() bool {
  132. return adapter.iter.head != adapter.iter.tail
  133. }
  134. func (adapter *AdaptedDecoder) Buffered() io.Reader {
  135. remaining := adapter.iter.buf[adapter.iter.head:adapter.iter.tail]
  136. return bytes.NewReader(remaining)
  137. }
  138. func (decoder *AdaptedDecoder) UseNumber() {
  139. RegisterTypeDecoder("interface {}", func(ptr unsafe.Pointer, iter *Iterator) {
  140. if iter.WhatIsNext() == Number {
  141. *((*interface{})(ptr)) = json.Number(iter.readNumberAsString())
  142. } else {
  143. *((*interface{})(ptr)) = iter.Read()
  144. }
  145. })
  146. }
  147. func NewEncoder(writer io.Writer) *AdaptedEncoder {
  148. stream := NewStream(writer, 512)
  149. return &AdaptedEncoder{stream}
  150. }
  151. type AdaptedEncoder struct {
  152. stream *Stream
  153. }
  154. func (adapter *AdaptedEncoder) Encode(val interface{}) error {
  155. adapter.stream.WriteVal(val)
  156. adapter.stream.Flush()
  157. return adapter.stream.Error
  158. }
  159. func (adapter *AdaptedEncoder) SetIndent(prefix, indent string) {
  160. adapter.stream.IndentionStep = len(indent)
  161. }