From fb6151f556756808539857280c37c37f1953b2ec Mon Sep 17 00:00:00 2001 From: Masaaki Goshima Date: Sun, 2 May 2021 15:26:36 +0900 Subject: [PATCH] Fix decoding of null value to []byte by json.Unmarshal --- decode_bytes.go | 16 +++------------- decode_test.go | 29 +++++++++++++++++++++++++++++ 2 files changed, 32 insertions(+), 13 deletions(-) diff --git a/decode_bytes.go b/decode_bytes.go index 0babe82..b5e34a3 100644 --- a/decode_bytes.go +++ b/decode_bytes.go @@ -160,21 +160,11 @@ func (d *bytesDecoder) decodeBinary(buf []byte, cursor, depth int64, p unsafe.Po } return nil, c, nil case 'n': - buflen := int64(len(buf)) - if cursor+3 >= buflen { - 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) + if err := validateNull(buf, cursor); err != nil { + return nil, 0, err } cursor += 4 - return []byte{}, cursor, nil + return nil, cursor, nil default: goto ERROR } diff --git a/decode_test.go b/decode_test.go index c057add..cfc6df3 100644 --- a/decode_test.go +++ b/decode_test.go @@ -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) + } + }) +}