feature_adapter.go 5.0 KB

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