Merge pull request #253 from IncSW/fix-251

fix error when unmarshal empty array
This commit is contained in:
Masaaki Goshima 2021-06-18 01:09:13 +09:00 committed by GitHub
commit 2565e4721a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 45 additions and 2 deletions

View File

@ -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)
}

View File

@ -46,8 +46,16 @@ func (d *arrayDecoder) DecodeStream(s *Stream, depth int64, p unsafe.Pointer) er
return nil return nil
case '[': case '[':
idx := 0 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++ s.cursor++
return nil
}
for {
if idx < d.alen { if idx < d.alen {
if err := d.valueDecoder.DecodeStream(s, depth, unsafe.Pointer(uintptr(p)+uintptr(idx)*d.size)); err != nil { if err := d.valueDecoder.DecodeStream(s, depth, unsafe.Pointer(uintptr(p)+uintptr(idx)*d.size)); err != nil {
return err return err
@ -67,9 +75,11 @@ func (d *arrayDecoder) DecodeStream(s *Stream, depth int64, p unsafe.Pointer) er
s.cursor++ s.cursor++
return nil return nil
case ',': case ',':
s.cursor++
continue continue
case nul: case nul:
if s.read() { if s.read() {
s.cursor++
continue continue
} }
goto ERROR goto ERROR
@ -111,8 +121,17 @@ func (d *arrayDecoder) Decode(ctx *RuntimeContext, cursor, depth int64, p unsafe
return cursor, nil return cursor, nil
case '[': case '[':
idx := 0 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++ cursor++
return cursor, nil
}
for {
if idx < d.alen { if idx < d.alen {
c, err := d.valueDecoder.Decode(ctx, cursor, depth, unsafe.Pointer(uintptr(p)+uintptr(idx)*d.size)) c, err := d.valueDecoder.Decode(ctx, cursor, depth, unsafe.Pointer(uintptr(p)+uintptr(idx)*d.size))
if err != nil { if err != nil {
@ -137,6 +156,7 @@ func (d *arrayDecoder) Decode(ctx *RuntimeContext, cursor, depth int64, p unsafe
cursor++ cursor++
return cursor, nil return cursor, nil
case ',': case ',':
cursor++
continue continue
default: default:
return 0, errors.ErrInvalidCharacter(buf[cursor], "array", cursor) return 0, errors.ErrInvalidCharacter(buf[cursor], "array", cursor)