feature_stream.go 6.8 KB

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