Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix error when unmarshal empty array #253

Merged
merged 3 commits into from Jun 17, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
23 changes: 23 additions & 0 deletions decode_test.go
Expand Up @@ -3666,3 +3666,26 @@ func TestDecodeContextOption(t *testing.T) {
}
})
}

func TestIssue251(t *testing.T) {
array := [3]int{1, 2, 3}
err := stdjson.Unmarshal([]byte("[ ]"), &array)
if err != nil {
t.Fatal(err)
}
t.Log(array)

array = [3]int{1, 2, 3}
err = json.Unmarshal([]byte("[ ]"), &array)
if err != nil {
t.Fatal(err)
}
t.Log(array)

array = [3]int{1, 2, 3}
err = json.NewDecoder(strings.NewReader(`[ ]`)).Decode(&array)
if err != nil {
t.Fatal(err)
}
t.Log(array)
}
24 changes: 22 additions & 2 deletions internal/decoder/array.go
Expand Up @@ -46,8 +46,16 @@ func (d *arrayDecoder) DecodeStream(s *Stream, depth int64, p unsafe.Pointer) er
return nil
case '[':
idx := 0
for {
s.cursor++
if s.skipWhiteSpace() == ']' {
for idx < d.alen {
*(*unsafe.Pointer)(unsafe.Pointer(uintptr(p) + uintptr(idx)*d.size)) = d.zeroValue
idx++
}
s.cursor++
return nil
}
for {
if idx < d.alen {
if err := d.valueDecoder.DecodeStream(s, depth, unsafe.Pointer(uintptr(p)+uintptr(idx)*d.size)); err != nil {
return err
Expand All @@ -67,9 +75,11 @@ func (d *arrayDecoder) DecodeStream(s *Stream, depth int64, p unsafe.Pointer) er
s.cursor++
return nil
case ',':
s.cursor++
continue
case nul:
if s.read() {
s.cursor++
continue
}
goto ERROR
Expand Down Expand Up @@ -111,8 +121,17 @@ func (d *arrayDecoder) Decode(ctx *RuntimeContext, cursor, depth int64, p unsafe
return cursor, nil
case '[':
idx := 0
for {
cursor++
cursor = skipWhiteSpace(buf, cursor)
if buf[cursor] == ']' {
for idx < d.alen {
*(*unsafe.Pointer)(unsafe.Pointer(uintptr(p) + uintptr(idx)*d.size)) = d.zeroValue
idx++
}
cursor++
return cursor, nil
}
for {
if idx < d.alen {
c, err := d.valueDecoder.Decode(ctx, cursor, depth, unsafe.Pointer(uintptr(p)+uintptr(idx)*d.size))
if err != nil {
Expand All @@ -137,6 +156,7 @@ func (d *arrayDecoder) Decode(ctx *RuntimeContext, cursor, depth int64, p unsafe
cursor++
return cursor, nil
case ',':
cursor++
continue
default:
return 0, errors.ErrInvalidCharacter(buf[cursor], "array", cursor)
Expand Down