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鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

Don't marshal empty byte or uint8 slice as null #371

Merged
merged 1 commit into from
Jun 3, 2019
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions misc_tests/jsoniter_array_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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{}
Expand Down
14 changes: 8 additions & 6 deletions reflect_native.go
Original file line number Diff line number Diff line change
Expand Up @@ -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('"')
}

Expand Down