feature_stream.go 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. package jsoniter
  2. import (
  3. "io"
  4. )
  5. // stream is a io.Writer like object, with JSON specific write functions.
  6. // Error is not returned as return value, but stored as Error member on this stream instance.
  7. type Stream struct {
  8. cfg *frozenConfig
  9. out io.Writer
  10. buf []byte
  11. n int
  12. Error error
  13. indention int
  14. Attachment interface{} // open for customized encoder
  15. floatBuf []byte
  16. }
  17. // NewStream create new stream instance.
  18. // cfg can be jsoniter.ConfigDefault.
  19. // out can be nil if write to internal buffer.
  20. // bufSize is the initial size for the internal buffer in bytes.
  21. func NewStream(cfg API, out io.Writer, bufSize int) *Stream {
  22. return &Stream{
  23. cfg: cfg.(*frozenConfig),
  24. out: out,
  25. buf: make([]byte, bufSize),
  26. n: 0,
  27. Error: nil,
  28. indention: 0,
  29. floatBuf: make([]byte, 0, 32),
  30. }
  31. }
  32. // Pool returns a pool can provide more stream with same configuration
  33. func (stream *Stream) Pool() StreamPool {
  34. return stream.cfg
  35. }
  36. // Reset reuse this stream instance by assign a new writer
  37. func (stream *Stream) Reset(out io.Writer) {
  38. stream.out = out
  39. stream.n = 0
  40. }
  41. // Available returns how many bytes are unused in the buffer.
  42. func (stream *Stream) Available() int {
  43. return len(stream.buf) - stream.n
  44. }
  45. // Buffered returns the number of bytes that have been written into the current buffer.
  46. func (stream *Stream) Buffered() int {
  47. return stream.n
  48. }
  49. // Buffer if writer is nil, use this method to take the result
  50. func (stream *Stream) Buffer() []byte {
  51. return stream.buf[:stream.n]
  52. }
  53. // Write writes the contents of p into the buffer.
  54. // It returns the number of bytes written.
  55. // If nn < len(p), it also returns an error explaining
  56. // why the write is short.
  57. func (stream *Stream) Write(p []byte) (nn int, err error) {
  58. for len(p) > stream.Available() && stream.Error == nil {
  59. if stream.out == nil {
  60. stream.growAtLeast(len(p))
  61. } else {
  62. var n int
  63. if stream.Buffered() == 0 {
  64. // Large write, empty buffer.
  65. // Write directly from p to avoid copy.
  66. n, stream.Error = stream.out.Write(p)
  67. } else {
  68. n = copy(stream.buf[stream.n:], p)
  69. stream.n += n
  70. stream.Flush()
  71. }
  72. nn += n
  73. p = p[n:]
  74. }
  75. }
  76. if stream.Error != nil {
  77. return nn, stream.Error
  78. }
  79. n := copy(stream.buf[stream.n:], p)
  80. stream.n += n
  81. nn += n
  82. return nn, nil
  83. }
  84. // WriteByte writes a single byte.
  85. func (stream *Stream) writeByte(c byte) {
  86. if stream.Error != nil {
  87. return
  88. }
  89. if stream.Available() < 1 {
  90. stream.growAtLeast(1)
  91. }
  92. stream.buf[stream.n] = c
  93. stream.n++
  94. }
  95. func (stream *Stream) writeTwoBytes(c1 byte, c2 byte) {
  96. if stream.Error != nil {
  97. return
  98. }
  99. if stream.Available() < 2 {
  100. stream.growAtLeast(2)
  101. }
  102. stream.buf[stream.n] = c1
  103. stream.buf[stream.n+1] = c2
  104. stream.n += 2
  105. }
  106. func (stream *Stream) writeThreeBytes(c1 byte, c2 byte, c3 byte) {
  107. if stream.Error != nil {
  108. return
  109. }
  110. if stream.Available() < 3 {
  111. stream.growAtLeast(3)
  112. }
  113. stream.buf[stream.n] = c1
  114. stream.buf[stream.n+1] = c2
  115. stream.buf[stream.n+2] = c3
  116. stream.n += 3
  117. }
  118. func (stream *Stream) writeFourBytes(c1 byte, c2 byte, c3 byte, c4 byte) {
  119. if stream.Error != nil {
  120. return
  121. }
  122. if stream.Available() < 4 {
  123. stream.growAtLeast(4)
  124. }
  125. stream.buf[stream.n] = c1
  126. stream.buf[stream.n+1] = c2
  127. stream.buf[stream.n+2] = c3
  128. stream.buf[stream.n+3] = c4
  129. stream.n += 4
  130. }
  131. func (stream *Stream) writeFiveBytes(c1 byte, c2 byte, c3 byte, c4 byte, c5 byte) {
  132. if stream.Error != nil {
  133. return
  134. }
  135. if stream.Available() < 5 {
  136. stream.growAtLeast(5)
  137. }
  138. stream.buf[stream.n] = c1
  139. stream.buf[stream.n+1] = c2
  140. stream.buf[stream.n+2] = c3
  141. stream.buf[stream.n+3] = c4
  142. stream.buf[stream.n+4] = c5
  143. stream.n += 5
  144. }
  145. // Flush writes any buffered data to the underlying io.Writer.
  146. func (stream *Stream) Flush() error {
  147. if stream.out == nil {
  148. return nil
  149. }
  150. if stream.Error != nil {
  151. return stream.Error
  152. }
  153. if stream.n == 0 {
  154. return nil
  155. }
  156. n, err := stream.out.Write(stream.buf[0:stream.n])
  157. if n < stream.n && err == nil {
  158. err = io.ErrShortWrite
  159. }
  160. if err != nil {
  161. if n > 0 && n < stream.n {
  162. copy(stream.buf[0:stream.n-n], stream.buf[n:stream.n])
  163. }
  164. stream.n -= n
  165. stream.Error = err
  166. return err
  167. }
  168. stream.n = 0
  169. return nil
  170. }
  171. func (stream *Stream) ensure(minimal int) {
  172. available := stream.Available()
  173. if available < minimal {
  174. stream.growAtLeast(minimal)
  175. }
  176. }
  177. func (stream *Stream) growAtLeast(minimal int) {
  178. if stream.out != nil {
  179. stream.Flush()
  180. if stream.Available() >= minimal {
  181. return
  182. }
  183. }
  184. toGrow := len(stream.buf)
  185. if toGrow < minimal {
  186. toGrow = minimal
  187. }
  188. newBuf := make([]byte, len(stream.buf)+toGrow)
  189. copy(newBuf, stream.Buffer())
  190. stream.buf = newBuf
  191. }
  192. // WriteRaw write string out without quotes, just like []byte
  193. func (stream *Stream) WriteRaw(s string) {
  194. stream.ensure(len(s))
  195. if stream.Error != nil {
  196. return
  197. }
  198. n := copy(stream.buf[stream.n:], s)
  199. stream.n += n
  200. }
  201. // WriteNil write null to stream
  202. func (stream *Stream) WriteNil() {
  203. stream.writeFourBytes('n', 'u', 'l', 'l')
  204. }
  205. // WriteTrue write true to stream
  206. func (stream *Stream) WriteTrue() {
  207. stream.writeFourBytes('t', 'r', 'u', 'e')
  208. }
  209. // WriteFalse write false to stream
  210. func (stream *Stream) WriteFalse() {
  211. stream.writeFiveBytes('f', 'a', 'l', 's', 'e')
  212. }
  213. // WriteBool write true or false into stream
  214. func (stream *Stream) WriteBool(val bool) {
  215. if val {
  216. stream.WriteTrue()
  217. } else {
  218. stream.WriteFalse()
  219. }
  220. }
  221. // WriteObjectStart write { with possible indention
  222. func (stream *Stream) WriteObjectStart() {
  223. stream.indention += stream.cfg.indentionStep
  224. stream.writeByte('{')
  225. stream.writeIndention(0)
  226. }
  227. // WriteObjectField write "field": with possible indention
  228. func (stream *Stream) WriteObjectField(field string) {
  229. stream.WriteString(field)
  230. if stream.indention > 0 {
  231. stream.writeTwoBytes(':', ' ')
  232. } else {
  233. stream.writeByte(':')
  234. }
  235. }
  236. // WriteObjectEnd write } with possible indention
  237. func (stream *Stream) WriteObjectEnd() {
  238. stream.writeIndention(stream.cfg.indentionStep)
  239. stream.indention -= stream.cfg.indentionStep
  240. stream.writeByte('}')
  241. }
  242. // WriteEmptyObject write {}
  243. func (stream *Stream) WriteEmptyObject() {
  244. stream.writeByte('{')
  245. stream.writeByte('}')
  246. }
  247. // WriteMore write , with possible indention
  248. func (stream *Stream) WriteMore() {
  249. stream.writeByte(',')
  250. stream.writeIndention(0)
  251. }
  252. // WriteArrayStart write [ with possible indention
  253. func (stream *Stream) WriteArrayStart() {
  254. stream.indention += stream.cfg.indentionStep
  255. stream.writeByte('[')
  256. stream.writeIndention(0)
  257. }
  258. // WriteEmptyArray write []
  259. func (stream *Stream) WriteEmptyArray() {
  260. stream.writeTwoBytes('[', ']')
  261. }
  262. // WriteArrayEnd write ] with possible indention
  263. func (stream *Stream) WriteArrayEnd() {
  264. stream.writeIndention(stream.cfg.indentionStep)
  265. stream.indention -= stream.cfg.indentionStep
  266. stream.writeByte(']')
  267. }
  268. func (stream *Stream) writeIndention(delta int) {
  269. if stream.indention == 0 {
  270. return
  271. }
  272. stream.writeByte('\n')
  273. toWrite := stream.indention - delta
  274. stream.ensure(toWrite)
  275. for i := 0; i < toWrite && stream.n < len(stream.buf); i++ {
  276. stream.buf[stream.n] = ' '
  277. stream.n++
  278. }
  279. }