feature_stream.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  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. if stream.Available() >= minimal {
  178. return
  179. }
  180. }
  181. toGrow := len(stream.buf)
  182. if toGrow < minimal {
  183. toGrow = minimal
  184. }
  185. newBuf := make([]byte, len(stream.buf)+toGrow)
  186. copy(newBuf, stream.Buffer())
  187. stream.buf = newBuf
  188. }
  189. // WriteRaw write string out without quotes, just like []byte
  190. func (stream *Stream) WriteRaw(s string) {
  191. stream.ensure(len(s))
  192. if stream.Error != nil {
  193. return
  194. }
  195. n := copy(stream.buf[stream.n:], s)
  196. stream.n += n
  197. }
  198. // WriteNil write null to stream
  199. func (stream *Stream) WriteNil() {
  200. stream.writeFourBytes('n', 'u', 'l', 'l')
  201. }
  202. // WriteTrue write true to stream
  203. func (stream *Stream) WriteTrue() {
  204. stream.writeFourBytes('t', 'r', 'u', 'e')
  205. }
  206. // WriteFalse write false to stream
  207. func (stream *Stream) WriteFalse() {
  208. stream.writeFiveBytes('f', 'a', 'l', 's', 'e')
  209. }
  210. // WriteBool write true or false into stream
  211. func (stream *Stream) WriteBool(val bool) {
  212. if val {
  213. stream.WriteTrue()
  214. } else {
  215. stream.WriteFalse()
  216. }
  217. }
  218. // WriteObjectStart write { with possible indention
  219. func (stream *Stream) WriteObjectStart() {
  220. stream.indention += stream.cfg.indentionStep
  221. stream.writeByte('{')
  222. stream.writeIndention(0)
  223. }
  224. // WriteObjectField write "field": with possible indention
  225. func (stream *Stream) WriteObjectField(field string) {
  226. stream.WriteString(field)
  227. if stream.indention > 0 {
  228. stream.writeTwoBytes(':', ' ')
  229. } else {
  230. stream.writeByte(':')
  231. }
  232. }
  233. // WriteObjectEnd write } with possible indention
  234. func (stream *Stream) WriteObjectEnd() {
  235. stream.writeIndention(stream.cfg.indentionStep)
  236. stream.indention -= stream.cfg.indentionStep
  237. stream.writeByte('}')
  238. }
  239. // WriteEmptyObject write {}
  240. func (stream *Stream) WriteEmptyObject() {
  241. stream.writeByte('{')
  242. stream.writeByte('}')
  243. }
  244. // WriteMore write , with possible indention
  245. func (stream *Stream) WriteMore() {
  246. stream.writeByte(',')
  247. stream.writeIndention(0)
  248. }
  249. // WriteArrayStart write [ with possible indention
  250. func (stream *Stream) WriteArrayStart() {
  251. stream.indention += stream.cfg.indentionStep
  252. stream.writeByte('[')
  253. stream.writeIndention(0)
  254. }
  255. // WriteEmptyArray write []
  256. func (stream *Stream) WriteEmptyArray() {
  257. stream.writeTwoBytes('[', ']')
  258. }
  259. // WriteArrayEnd write ] with possible indention
  260. func (stream *Stream) WriteArrayEnd() {
  261. stream.writeIndention(stream.cfg.indentionStep)
  262. stream.indention -= stream.cfg.indentionStep
  263. stream.writeByte(']')
  264. }
  265. func (stream *Stream) writeIndention(delta int) {
  266. if stream.indention == 0 {
  267. return
  268. }
  269. stream.writeByte('\n')
  270. toWrite := stream.indention - delta
  271. stream.ensure(toWrite)
  272. for i := 0; i < toWrite && stream.n < len(stream.buf); i++ {
  273. stream.buf[stream.n] = ' '
  274. stream.n++
  275. }
  276. }