From 94ccf711744877533fe0fa5117c1761085dbe36a Mon Sep 17 00:00:00 2001 From: Aleksey Boyko Date: Fri, 23 Mar 2018 18:55:23 +0300 Subject: [PATCH] [encoder] fix zero len array decoding - strings.Split with empty slice argument returns slice with 1 element which is empty string. without check len decoder crashes on empty numeric arrays - encoder test added - types test added --- encoder.go | 9 +++++++-- encoder_test.go | 2 ++ types_test.go | 1 + 3 files changed, 10 insertions(+), 2 deletions(-) diff --git a/encoder.go b/encoder.go index 01764fe..bc54f42 100644 --- a/encoder.go +++ b/encoder.go @@ -134,8 +134,13 @@ func (d *textDecoder) Decode(t string, value []byte) (driver.Value, error) { return unescape(unquote(v)), nil } if strings.HasPrefix(t, "Array") { - if len(v) > 0 && v[0] == '[' && v[len(value)-1] == ']' { - items := strings.Split(v[1:len(value)-1], ",") + if len(v) > 0 && v[0] == '[' && v[len(v)-1] == ']' { + var items []string + // check that array is not empty ([]) + if len(v) > 2 { + items = strings.Split(v[1:len(v)-1], ",") + } + subType := t[6 : len(t)-1] r := reflect.MakeSlice(reflect.SliceOf(columnType(subType)), len(items), len(items)) for i, item := range items { diff --git a/encoder_test.go b/encoder_test.go index d05d984..a92947d 100644 --- a/encoder_test.go +++ b/encoder_test.go @@ -34,6 +34,7 @@ func TestTextEncoder(t *testing.T) { {`\\'hello`, `'\\\\\'hello'`}, {[]byte(`\\'hello`), `\\'hello`}, {[]int32{1, 2}, "[1,2]"}, + {[]int32{}, "[]"}, {&d, "'2012-05-31 00:00:00'"}, } @@ -70,6 +71,7 @@ func TestTextDecoder(t *testing.T) { {"Enum8('one'=1)", "'one'", "one"}, {"Enum16('one'=1)", "'one'", "one"}, {"Array(UInt32)", "[1,2]", []uint32{1, 2}}, + {"Array(UInt32)", "[]", []uint32{}}, } dec := &textDecoder{location: time.UTC} diff --git a/types_test.go b/types_test.go index 9257e7a..e640f78 100644 --- a/types_test.go +++ b/types_test.go @@ -19,6 +19,7 @@ func TestArray(t *testing.T) { {[]uint16{1, 2}, []byte("[1,2]")}, {[]uint32{1, 2}, []byte("[1,2]")}, {[]uint64{1, 2}, []byte("[1,2]")}, + {[]uint64{}, []byte("[]")}, } for _, tc := range testCases {