Skip to content

Commit

Permalink
Parsing string responses in AsIntSlice (#437)
Browse files Browse the repository at this point in the history
* refactor: shorten the AsFloatSlice

* feat: improve the AsIntSlice by parsing string responses
  • Loading branch information
rueian authored Jan 2, 2024
1 parent 6d8b04b commit 7dfdb23
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 9 deletions.
22 changes: 13 additions & 9 deletions message.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand All @@ -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
Expand Down
8 changes: 8 additions & 0 deletions message_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down

0 comments on commit 7dfdb23

Please sign in to comment.