Skip to content

Commit 2565e47

Browse files
authored
Merge pull request #253 from IncSW/fix-251
fix error when unmarshal empty array
2 parents faa4de9 + 94cecc0 commit 2565e47

File tree

2 files changed

+45
-2
lines changed

2 files changed

+45
-2
lines changed

decode_test.go

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3666,3 +3666,26 @@ func TestDecodeContextOption(t *testing.T) {
36663666
}
36673667
})
36683668
}
3669+
3670+
func TestIssue251(t *testing.T) {
3671+
array := [3]int{1, 2, 3}
3672+
err := stdjson.Unmarshal([]byte("[ ]"), &array)
3673+
if err != nil {
3674+
t.Fatal(err)
3675+
}
3676+
t.Log(array)
3677+
3678+
array = [3]int{1, 2, 3}
3679+
err = json.Unmarshal([]byte("[ ]"), &array)
3680+
if err != nil {
3681+
t.Fatal(err)
3682+
}
3683+
t.Log(array)
3684+
3685+
array = [3]int{1, 2, 3}
3686+
err = json.NewDecoder(strings.NewReader(`[ ]`)).Decode(&array)
3687+
if err != nil {
3688+
t.Fatal(err)
3689+
}
3690+
t.Log(array)
3691+
}

internal/decoder/array.go

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -46,8 +46,16 @@ func (d *arrayDecoder) DecodeStream(s *Stream, depth int64, p unsafe.Pointer) er
4646
return nil
4747
case '[':
4848
idx := 0
49-
for {
49+
s.cursor++
50+
if s.skipWhiteSpace() == ']' {
51+
for idx < d.alen {
52+
*(*unsafe.Pointer)(unsafe.Pointer(uintptr(p) + uintptr(idx)*d.size)) = d.zeroValue
53+
idx++
54+
}
5055
s.cursor++
56+
return nil
57+
}
58+
for {
5159
if idx < d.alen {
5260
if err := d.valueDecoder.DecodeStream(s, depth, unsafe.Pointer(uintptr(p)+uintptr(idx)*d.size)); err != nil {
5361
return err
@@ -67,9 +75,11 @@ func (d *arrayDecoder) DecodeStream(s *Stream, depth int64, p unsafe.Pointer) er
6775
s.cursor++
6876
return nil
6977
case ',':
78+
s.cursor++
7079
continue
7180
case nul:
7281
if s.read() {
82+
s.cursor++
7383
continue
7484
}
7585
goto ERROR
@@ -111,8 +121,17 @@ func (d *arrayDecoder) Decode(ctx *RuntimeContext, cursor, depth int64, p unsafe
111121
return cursor, nil
112122
case '[':
113123
idx := 0
114-
for {
124+
cursor++
125+
cursor = skipWhiteSpace(buf, cursor)
126+
if buf[cursor] == ']' {
127+
for idx < d.alen {
128+
*(*unsafe.Pointer)(unsafe.Pointer(uintptr(p) + uintptr(idx)*d.size)) = d.zeroValue
129+
idx++
130+
}
115131
cursor++
132+
return cursor, nil
133+
}
134+
for {
116135
if idx < d.alen {
117136
c, err := d.valueDecoder.Decode(ctx, cursor, depth, unsafe.Pointer(uintptr(p)+uintptr(idx)*d.size))
118137
if err != nil {
@@ -137,6 +156,7 @@ func (d *arrayDecoder) Decode(ctx *RuntimeContext, cursor, depth int64, p unsafe
137156
cursor++
138157
return cursor, nil
139158
case ',':
159+
cursor++
140160
continue
141161
default:
142162
return 0, errors.ErrInvalidCharacter(buf[cursor], "array", cursor)

0 commit comments

Comments
 (0)