From e034897e69610b2f78a4d3a628fd3ca9688fca53 Mon Sep 17 00:00:00 2001 From: Tao Wen Date: Sat, 7 Jan 2017 22:16:20 +0800 Subject: [PATCH] write array --- jsoniter_array_test.go | 17 +++++++++++++++++ stream.go | 12 ++++++++++++ 2 files changed, 29 insertions(+) diff --git a/jsoniter_array_test.go b/jsoniter_array_test.go index 368b1b0..285994f 100644 --- a/jsoniter_array_test.go +++ b/jsoniter_array_test.go @@ -3,6 +3,8 @@ package jsoniter import ( "encoding/json" "testing" + "github.com/json-iterator/go/require" + "bytes" ) func Test_empty_array(t *testing.T) { @@ -117,6 +119,21 @@ func Test_whitespace_before_comma(t *testing.T) { } } +func Test_write_array(t *testing.T) { + should := require.New(t) + buf := &bytes.Buffer{} + stream := NewStream(buf, 4096) + stream.IndentionStep = 2 + stream.WriteArrayStart() + stream.WriteInt(1) + stream.WriteMore() + stream.WriteInt(2) + stream.WriteArrayEnd() + stream.Flush() + should.Nil(stream.Error) + should.Equal("[\n 1,\n 2\n]", buf.String()) +} + func Benchmark_jsoniter_array(b *testing.B) { b.ReportAllocs() input := []byte(`[1,2,3,4,5,6,7,8,9]`) diff --git a/stream.go b/stream.go index 32f288e..cb95255 100644 --- a/stream.go +++ b/stream.go @@ -160,6 +160,18 @@ func (stream *Stream) WriteMore() { stream.writeIndention(0) } +func (stream *Stream) WriteArrayStart() { + stream.indention += stream.IndentionStep + stream.writeByte('[') + stream.writeIndention(0) +} + +func (stream *Stream) WriteArrayEnd() { + stream.writeIndention(stream.IndentionStep) + stream.indention -= stream.IndentionStep + stream.writeByte(']') +} + func (stream *Stream) writeIndention(delta int) { if (stream.indention == 0) { return