Skip to content

Commit 459f0e3

Browse files
committed
fix #37: add SkipAndAppendBytes iterator method
1 parent 0039f4a commit 459f0e3

File tree

2 files changed

+22
-12
lines changed

2 files changed

+22
-12
lines changed

iter_skip.go

+13-12
Original file line numberDiff line numberDiff line change
@@ -37,17 +37,24 @@ func (iter *Iterator) SkipAndReturnBytes() []byte {
3737
return iter.stopCapture()
3838
}
3939

40-
type captureBuffer struct {
41-
startedAt int
42-
captured []byte
40+
// SkipAndAppendBytes skips next JSON element and appends its content to
41+
// buffer, returning the result.
42+
func (iter *Iterator) SkipAndAppendBytes(buf []byte) []byte {
43+
iter.startCaptureTo(buf, iter.head)
44+
iter.Skip()
45+
return iter.stopCapture()
4346
}
4447

45-
func (iter *Iterator) startCapture(captureStartedAt int) {
48+
func (iter *Iterator) startCaptureTo(buf []byte, captureStartedAt int) {
4649
if iter.captured != nil {
4750
panic("already in capture mode")
4851
}
4952
iter.captureStartedAt = captureStartedAt
50-
iter.captured = make([]byte, 0, 32)
53+
iter.captured = buf
54+
}
55+
56+
func (iter *Iterator) startCapture(captureStartedAt int) {
57+
iter.startCaptureTo(make([]byte, 0, 32), captureStartedAt)
5158
}
5259

5360
func (iter *Iterator) stopCapture() []byte {
@@ -58,13 +65,7 @@ func (iter *Iterator) stopCapture() []byte {
5865
remaining := iter.buf[iter.captureStartedAt:iter.head]
5966
iter.captureStartedAt = -1
6067
iter.captured = nil
61-
if len(captured) == 0 {
62-
copied := make([]byte, len(remaining))
63-
copy(copied, remaining)
64-
return copied
65-
}
66-
captured = append(captured, remaining...)
67-
return captured
68+
return append(captured, remaining...)
6869
}
6970

7071
// Skip skips a json object and positions to relatively the next json object

skip_tests/jsoniter_skip_test.go

+9
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,15 @@ func Test_skip_and_return_bytes_with_reader(t *testing.T) {
105105
should.Equal(`{"a" : [{"stream": "c"}], "d": 102 }`, string(skipped))
106106
}
107107

108+
func Test_append_skip_and_return_bytes_with_reader(t *testing.T) {
109+
should := require.New(t)
110+
iter := jsoniter.Parse(jsoniter.ConfigDefault, bytes.NewBufferString(`[ {"a" : [{"stream": "c"}], "d": 102 }, "stream"]`), 4)
111+
iter.ReadArray()
112+
buf := make([]byte, 0, 1024)
113+
buf = iter.SkipAndAppendBytes(buf)
114+
should.Equal(`{"a" : [{"stream": "c"}], "d": 102 }`, string(buf))
115+
}
116+
108117
func Test_skip_empty(t *testing.T) {
109118
should := require.New(t)
110119
should.NotNil(jsoniter.Get([]byte("")).LastError())

0 commit comments

Comments
 (0)