feature_stream.go 6.6 KB

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