Fix decoding of null value to []byte by json.Unmarshal

This commit is contained in:
Masaaki Goshima 2021-05-02 15:26:36 +09:00
parent 6a1ae7c1ca
commit fb6151f556
2 changed files with 32 additions and 13 deletions

View File

@ -160,21 +160,11 @@ func (d *bytesDecoder) decodeBinary(buf []byte, cursor, depth int64, p unsafe.Po
} }
return nil, c, nil return nil, c, nil
case 'n': case 'n':
buflen := int64(len(buf)) if err := validateNull(buf, cursor); err != nil {
if cursor+3 >= buflen { return nil, 0, err
return nil, 0, errUnexpectedEndOfJSON("null", cursor)
}
if buf[cursor+1] != 'u' {
return nil, 0, errInvalidCharacter(buf[cursor+1], "null", cursor)
}
if buf[cursor+2] != 'l' {
return nil, 0, errInvalidCharacter(buf[cursor+2], "null", cursor)
}
if buf[cursor+3] != 'l' {
return nil, 0, errInvalidCharacter(buf[cursor+3], "null", cursor)
} }
cursor += 4 cursor += 4
return []byte{}, cursor, nil return nil, cursor, nil
default: default:
goto ERROR goto ERROR
} }

View File

@ -3388,3 +3388,32 @@ func TestDecodeUnknownInterface(t *testing.T) {
} }
}) })
} }
func TestDecodeByteSliceNull(t *testing.T) {
t.Run("unmarshal", func(t *testing.T) {
var v1 []byte
if err := stdjson.Unmarshal([]byte(`null`), &v1); err != nil {
t.Fatal(err)
}
var v2 []byte
if err := json.Unmarshal([]byte(`null`), &v2); err != nil {
t.Fatal(err)
}
if v1 == nil && v2 != nil || len(v1) != len(v2) {
t.Fatalf("failed to decode null to []byte. expected:%#v but got %#v", v1, v2)
}
})
t.Run("stream", func(t *testing.T) {
var v1 []byte
if err := stdjson.NewDecoder(strings.NewReader(`null`)).Decode(&v1); err != nil {
t.Fatal(err)
}
var v2 []byte
if err := json.NewDecoder(strings.NewReader(`null`)).Decode(&v2); err != nil {
t.Fatal(err)
}
if v1 == nil && v2 != nil || len(v1) != len(v2) {
t.Fatalf("failed to decode null to []byte. expected:%#v but got %#v", v1, v2)
}
})
}