Ver código fonte

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.
Matt Good 8 anos atrás
pai
commit
ba3857729b
2 arquivos alterados com 13 adições e 0 exclusões
  1. 4 0
      feature_reflect_array.go
  2. 9 0
      jsoniter_fixed_array_test.go

+ 4 - 0
feature_reflect_array.go

@@ -27,6 +27,10 @@ type arrayEncoder struct {
 }
 
 func (encoder *arrayEncoder) Encode(ptr unsafe.Pointer, stream *Stream) {
+	if encoder.arrayType.Len() == 0 {
+		stream.WriteEmptyArray()
+		return
+	}
 	stream.WriteArrayStart()
 	elemPtr := unsafe.Pointer(ptr)
 	encoder.elemEncoder.Encode(elemPtr, stream)

+ 9 - 0
jsoniter_fixed_array_test.go

@@ -15,6 +15,15 @@ func Test_encode_fixed_array(t *testing.T) {
 	should.Equal("[0.1,1]", output)
 }
 
+func Test_encode_fixed_array_empty(t *testing.T) {
+	should := require.New(t)
+	type FixedArray [0]float64
+	fixed := FixedArray{}
+	output, err := MarshalToString(fixed)
+	should.Nil(err)
+	should.Equal("[]", output)
+}
+
 func Test_encode_fixed_array_of_map(t *testing.T) {
 	should := require.New(t)
 	type FixedArray [2]map[string]string