stream.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. package jsoniter
  2. import (
  3. "io"
  4. )
  5. var bytesNull []byte
  6. func init() {
  7. bytesNull = []byte("null")
  8. }
  9. type Stream struct {
  10. out io.Writer
  11. buf []byte
  12. n int
  13. Error error
  14. }
  15. func NewStream(out io.Writer, bufSize int) *Stream {
  16. return &Stream{out, make([]byte, bufSize), 0, nil}
  17. }
  18. // Available returns how many bytes are unused in the buffer.
  19. func (b *Stream) Available() int {
  20. return len(b.buf) - b.n
  21. }
  22. // Buffered returns the number of bytes that have been written into the current buffer.
  23. func (b *Stream) Buffered() int {
  24. return b.n
  25. }
  26. // Write writes the contents of p into the buffer.
  27. // It returns the number of bytes written.
  28. // If nn < len(p), it also returns an error explaining
  29. // why the write is short.
  30. func (b *Stream) Write(p []byte) (nn int, err error) {
  31. for len(p) > b.Available() && b.Error == nil {
  32. var n int
  33. if b.Buffered() == 0 {
  34. // Large write, empty buffer.
  35. // Write directly from p to avoid copy.
  36. n, b.Error = b.out.Write(p)
  37. } else {
  38. n = copy(b.buf[b.n:], p)
  39. b.n += n
  40. b.Flush()
  41. }
  42. nn += n
  43. p = p[n:]
  44. }
  45. if b.Error != nil {
  46. return nn, b.Error
  47. }
  48. n := copy(b.buf[b.n:], p)
  49. b.n += n
  50. nn += n
  51. return nn, nil
  52. }
  53. // WriteByte writes a single byte.
  54. func (b *Stream) writeByte(c byte) error {
  55. if b.Error != nil {
  56. return b.Error
  57. }
  58. if b.Available() <= 0 && b.Flush() != nil {
  59. return b.Error
  60. }
  61. b.buf[b.n] = c
  62. b.n++
  63. return nil
  64. }
  65. // Flush writes any buffered data to the underlying io.Writer.
  66. func (b *Stream) Flush() error {
  67. if b.Error != nil {
  68. return b.Error
  69. }
  70. if b.n == 0 {
  71. return nil
  72. }
  73. n, err := b.out.Write(b.buf[0:b.n])
  74. if n < b.n && err == nil {
  75. err = io.ErrShortWrite
  76. }
  77. if err != nil {
  78. if n > 0 && n < b.n {
  79. copy(b.buf[0:b.n - n], b.buf[n:b.n])
  80. }
  81. b.n -= n
  82. b.Error = err
  83. return err
  84. }
  85. b.n = 0
  86. return nil
  87. }
  88. func (b *Stream) WriteString(s string) {
  89. for len(s) > b.Available() && b.Error == nil {
  90. n := copy(b.buf[b.n:], s)
  91. b.n += n
  92. s = s[n:]
  93. b.Flush()
  94. }
  95. if b.Error != nil {
  96. return
  97. }
  98. n := copy(b.buf[b.n:], s)
  99. b.n += n
  100. }
  101. func (stream *Stream) WriteNull() {
  102. stream.Write(bytesNull)
  103. }
  104. func (stream *Stream) WriteVal(val interface{}) {
  105. }