|
| 1 | +package jsoniter |
| 2 | + |
| 3 | +type Stream struct { |
| 4 | + buf []byte |
| 5 | + Error error |
| 6 | + indentCount int |
| 7 | + Prefix string |
| 8 | + Indent string |
| 9 | +} |
| 10 | + |
| 11 | +// NewStream create new stream instance. |
| 12 | +func NewStream() *Stream { |
| 13 | + return &Stream{ |
| 14 | + buf: make([]byte, 0, 16), |
| 15 | + Error: nil, |
| 16 | + indentCount: 0, |
| 17 | + } |
| 18 | +} |
| 19 | + |
| 20 | +// Buffer if writer is nil, use this method to take the result |
| 21 | +func (stream *Stream) Buffer() []byte { |
| 22 | + return stream.buf |
| 23 | +} |
| 24 | + |
| 25 | +// Write writes the contents of p into the buffer. |
| 26 | +// It returns the number of bytes written. |
| 27 | +// If nn < len(p), it also returns an error explaining |
| 28 | +// why the write is short. |
| 29 | +func (stream *Stream) Write(p []byte) (nn int, err error) { |
| 30 | + stream.buf = append(stream.buf, p...) |
| 31 | + return len(p), nil |
| 32 | +} |
| 33 | + |
| 34 | +// WriteByte writes a single byte. |
| 35 | +func (stream *Stream) writeByte(c byte) { |
| 36 | + stream.buf = append(stream.buf, c) |
| 37 | +} |
| 38 | + |
| 39 | +func (stream *Stream) writeTwoBytes(c1 byte, c2 byte) { |
| 40 | + stream.buf = append(stream.buf, c1, c2) |
| 41 | +} |
| 42 | + |
| 43 | +func (stream *Stream) writeThreeBytes(c1 byte, c2 byte, c3 byte) { |
| 44 | + stream.buf = append(stream.buf, c1, c2, c3) |
| 45 | +} |
| 46 | + |
| 47 | +func (stream *Stream) writeFourBytes(c1 byte, c2 byte, c3 byte, c4 byte) { |
| 48 | + stream.buf = append(stream.buf, c1, c2, c3, c4) |
| 49 | +} |
| 50 | + |
| 51 | +func (stream *Stream) writeFiveBytes(c1 byte, c2 byte, c3 byte, c4 byte, c5 byte) { |
| 52 | + stream.buf = append(stream.buf, c1, c2, c3, c4, c5) |
| 53 | +} |
| 54 | + |
| 55 | +// WriteRaw write string out without quotes, just like []byte |
| 56 | +func (stream *Stream) WriteRaw(s string) { |
| 57 | + stream.buf = append(stream.buf, s...) |
| 58 | +} |
| 59 | + |
| 60 | +// WriteNull write null to stream |
| 61 | +func (stream *Stream) WriteNull() { |
| 62 | + stream.writeFourBytes('n', 'u', 'l', 'l') |
| 63 | +} |
| 64 | + |
| 65 | +// WriteMore write , with possible indention |
| 66 | +func (stream *Stream) WriteMore() { |
| 67 | + stream.writeByte(',') |
| 68 | + stream.writeIndent() |
| 69 | +} |
| 70 | + |
| 71 | +func (stream *Stream) withIndent() bool { |
| 72 | + return len(stream.Prefix) > 0 || len(stream.Indent) > 0 |
| 73 | +} |
| 74 | + |
| 75 | +func (stream *Stream) writeIndent() { |
| 76 | + if stream.withIndent() { |
| 77 | + stream.writeByte('\n') |
| 78 | + } |
| 79 | + stream.buf = append(stream.buf, stream.Prefix...) |
| 80 | + for i := 0; i < stream.indentCount; i++ { |
| 81 | + stream.buf = append(stream.buf, stream.Indent...) |
| 82 | + } |
| 83 | +} |
0 commit comments