From fb5614a4caddab60ff95c09a50bddc173916c8b2 Mon Sep 17 00:00:00 2001 From: Nikhita Raghunath Date: Mon, 3 Jun 2019 01:31:28 +0530 Subject: [PATCH] Don't marshal empty byte or uint8 slice as null []byte or []uint8 are encoded as base-64 encoded string. Per this, non-nil empty slice should not get marshalled as null, rather as "". This restores compatibility with the standard library. --- misc_tests/jsoniter_array_test.go | 21 +++++++++++++++++++++ reflect_native.go | 14 ++++++++------ 2 files changed, 29 insertions(+), 6 deletions(-) diff --git a/misc_tests/jsoniter_array_test.go b/misc_tests/jsoniter_array_test.go index 56e3e12c..ef60420d 100644 --- a/misc_tests/jsoniter_array_test.go +++ b/misc_tests/jsoniter_array_test.go @@ -158,6 +158,27 @@ func Test_encode_byte_array(t *testing.T) { should.Equal(`"AQID"`, string(bytes)) } +func Test_encode_empty_byte_array(t *testing.T) { + should := require.New(t) + bytes, err := json.Marshal([]byte{}) + should.Nil(err) + should.Equal(`""`, string(bytes)) + bytes, err = jsoniter.Marshal([]byte{}) + should.Nil(err) + should.Equal(`""`, string(bytes)) +} + +func Test_encode_nil_byte_array(t *testing.T) { + should := require.New(t) + var nilSlice []byte + bytes, err := json.Marshal(nilSlice) + should.Nil(err) + should.Equal(`null`, string(bytes)) + bytes, err = jsoniter.Marshal(nilSlice) + should.Nil(err) + should.Equal(`null`, string(bytes)) +} + func Test_decode_byte_array_from_base64(t *testing.T) { should := require.New(t) data := []byte{} diff --git a/reflect_native.go b/reflect_native.go index 9042eb0c..f88722d1 100644 --- a/reflect_native.go +++ b/reflect_native.go @@ -432,17 +432,19 @@ func (codec *base64Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { } func (codec *base64Codec) Encode(ptr unsafe.Pointer, stream *Stream) { - src := *((*[]byte)(ptr)) - if len(src) == 0 { + if codec.sliceType.UnsafeIsNil(ptr) { stream.WriteNil() return } + src := *((*[]byte)(ptr)) encoding := base64.StdEncoding stream.writeByte('"') - size := encoding.EncodedLen(len(src)) - buf := make([]byte, size) - encoding.Encode(buf, src) - stream.buf = append(stream.buf, buf...) + if len(src) != 0 { + size := encoding.EncodedLen(len(src)) + buf := make([]byte, size) + encoding.Encode(buf, src) + stream.buf = append(stream.buf, buf...) + } stream.writeByte('"') }