From 7dfdb23605adf9adcbb3089f894b791e38d1b3d4 Mon Sep 17 00:00:00 2001 From: Rueian Date: Wed, 3 Jan 2024 00:25:20 +0800 Subject: [PATCH] Parsing string responses in AsIntSlice (#437) * refactor: shorten the AsFloatSlice * feat: improve the AsIntSlice by parsing string responses --- message.go | 22 +++++++++++++--------- message_test.go | 8 ++++++++ 2 files changed, 21 insertions(+), 9 deletions(-) diff --git a/message.go b/message.go index a59cb4dd..c19d5a27 100644 --- a/message.go +++ b/message.go @@ -697,9 +697,15 @@ func (m *RedisMessage) AsIntSlice() ([]int64, error) { if err != nil { return nil, err } - s := make([]int64, 0, len(values)) - for _, v := range values { - s = append(s, v.integer) + s := make([]int64, len(values)) + for i, v := range values { + if len(v.string) != 0 { + if s[i], err = strconv.ParseInt(v.string, 10, 64); err != nil { + return nil, err + } + } else { + s[i] = v.integer + } } return s, nil } @@ -711,16 +717,14 @@ func (m *RedisMessage) AsFloatSlice() ([]float64, error) { if err != nil { return nil, err } - s := make([]float64, 0, len(values)) - for _, v := range values { + s := make([]float64, len(values)) + for i, v := range values { if len(v.string) != 0 { - i, err := util.ToFloat64(v.string) - if err != nil { + if s[i], err = util.ToFloat64(v.string); err != nil { return nil, err } - s = append(s, i) } else { - s = append(s, float64(v.integer)) + s[i] = float64(v.integer) } } return s, nil diff --git a/message_test.go b/message_test.go index 8da653ba..e5d0e114 100644 --- a/message_test.go +++ b/message_test.go @@ -254,6 +254,14 @@ func TestRedisResult(t *testing.T) { if ret, _ := (RedisResult{val: RedisMessage{typ: '*', values: values}}).AsIntSlice(); !reflect.DeepEqual(ret, []int64{2}) { t.Fatal("AsIntSlice not get value as expected") } + values = []RedisMessage{{string: "3", typ: '+'}} + if ret, _ := (RedisResult{val: RedisMessage{typ: '*', values: values}}).AsIntSlice(); !reflect.DeepEqual(ret, []int64{3}) { + t.Fatal("AsIntSlice not get value as expected") + } + values = []RedisMessage{{string: "ab", typ: '+'}} + if _, err := (RedisResult{val: RedisMessage{typ: '*', values: values}}).AsIntSlice(); err == nil { + t.Fatal("AsIntSlice not failed as expected") + } }) t.Run("AsFloatSlice", func(t *testing.T) {