Skip to content

Commit ba38577

Browse files
author
Matt Good
committed
Fix encoding 0-length arrays
The array encoder assumed that arrays had at least one value, so it would serialize them with a zero-value for the array, such as `[0]`. This adds a test to reproduce the issue, and updates the encoder to write an empty array if the length is 0.
1 parent c3ed5e8 commit ba38577

File tree

2 files changed

+13
-0
lines changed

2 files changed

+13
-0
lines changed

feature_reflect_array.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,10 @@ type arrayEncoder struct {
2727
}
2828

2929
func (encoder *arrayEncoder) Encode(ptr unsafe.Pointer, stream *Stream) {
30+
if encoder.arrayType.Len() == 0 {
31+
stream.WriteEmptyArray()
32+
return
33+
}
3034
stream.WriteArrayStart()
3135
elemPtr := unsafe.Pointer(ptr)
3236
encoder.elemEncoder.Encode(elemPtr, stream)

jsoniter_fixed_array_test.go

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,15 @@ func Test_encode_fixed_array(t *testing.T) {
1515
should.Equal("[0.1,1]", output)
1616
}
1717

18+
func Test_encode_fixed_array_empty(t *testing.T) {
19+
should := require.New(t)
20+
type FixedArray [0]float64
21+
fixed := FixedArray{}
22+
output, err := MarshalToString(fixed)
23+
should.Nil(err)
24+
should.Equal("[]", output)
25+
}
26+
1827
func Test_encode_fixed_array_of_map(t *testing.T) {
1928
should := require.New(t)
2029
type FixedArray [2]map[string]string

0 commit comments

Comments
 (0)