Skip to content

Commit 0039f4a

Browse files
authored
Merge pull request #371 from nikhita/byte-base64-encode
Don't marshal empty byte or uint8 slice as null
2 parents 08047c1 + fb5614a commit 0039f4a

File tree

2 files changed

+29
-6
lines changed

2 files changed

+29
-6
lines changed

misc_tests/jsoniter_array_test.go

+21
Original file line numberDiff line numberDiff line change
@@ -158,6 +158,27 @@ func Test_encode_byte_array(t *testing.T) {
158158
should.Equal(`"AQID"`, string(bytes))
159159
}
160160

161+
func Test_encode_empty_byte_array(t *testing.T) {
162+
should := require.New(t)
163+
bytes, err := json.Marshal([]byte{})
164+
should.Nil(err)
165+
should.Equal(`""`, string(bytes))
166+
bytes, err = jsoniter.Marshal([]byte{})
167+
should.Nil(err)
168+
should.Equal(`""`, string(bytes))
169+
}
170+
171+
func Test_encode_nil_byte_array(t *testing.T) {
172+
should := require.New(t)
173+
var nilSlice []byte
174+
bytes, err := json.Marshal(nilSlice)
175+
should.Nil(err)
176+
should.Equal(`null`, string(bytes))
177+
bytes, err = jsoniter.Marshal(nilSlice)
178+
should.Nil(err)
179+
should.Equal(`null`, string(bytes))
180+
}
181+
161182
func Test_decode_byte_array_from_base64(t *testing.T) {
162183
should := require.New(t)
163184
data := []byte{}

reflect_native.go

+8-6
Original file line numberDiff line numberDiff line change
@@ -432,17 +432,19 @@ func (codec *base64Codec) Decode(ptr unsafe.Pointer, iter *Iterator) {
432432
}
433433

434434
func (codec *base64Codec) Encode(ptr unsafe.Pointer, stream *Stream) {
435-
src := *((*[]byte)(ptr))
436-
if len(src) == 0 {
435+
if codec.sliceType.UnsafeIsNil(ptr) {
437436
stream.WriteNil()
438437
return
439438
}
439+
src := *((*[]byte)(ptr))
440440
encoding := base64.StdEncoding
441441
stream.writeByte('"')
442-
size := encoding.EncodedLen(len(src))
443-
buf := make([]byte, size)
444-
encoding.Encode(buf, src)
445-
stream.buf = append(stream.buf, buf...)
442+
if len(src) != 0 {
443+
size := encoding.EncodedLen(len(src))
444+
buf := make([]byte, size)
445+
encoding.Encode(buf, src)
446+
stream.buf = append(stream.buf, buf...)
447+
}
446448
stream.writeByte('"')
447449
}
448450

0 commit comments

Comments
 (0)