Skip to content
This repository has been archived by the owner on Sep 1, 2022. It is now read-only.

Commit

Permalink
[reply] Add ByteSlices conversion helper
Browse files Browse the repository at this point in the history
  • Loading branch information
tomlinford committed Oct 29, 2015
1 parent 7ec56c9 commit 6f4b077
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
30 changes: 30 additions & 0 deletions redis/reply.go
Original file line number Diff line number Diff line change
Expand Up @@ -273,6 +273,36 @@ func Strings(reply interface{}, err error) ([]string, error) {
return nil, fmt.Errorf("redigo: unexpected type for Strings, got type %T", reply)
}

// ByteSlices is a helper that converts an array command reply to a [][]byte.
// If err is not equal to nil, then ByteSlices returns nil, err. Nil array
// items are stay nil. ByteSlices returns an error if an array item is not a
// bulk string or nil.
func ByteSlices(reply interface{}, err error) ([][]byte, error) {
if err != nil {
return nil, err
}
switch reply := reply.(type) {
case []interface{}:
result := make([][]byte, len(reply))
for i := range reply {
if reply[i] == nil {
continue
}
p, ok := reply[i].([]byte)
if !ok {
return nil, fmt.Errorf("redigo: unexpected element type for ByteSlices, got type %T", reply[i])
}
result[i] = p
}
return result, nil
case nil:
return nil, ErrNil
case Error:
return nil, reply
}
return nil, fmt.Errorf("redigo: unexpected type for ByteSlices, got type %T", reply)
}

// Ints is a helper that converts an array command reply to a []int. If
// err is not equal to nil, then Ints returns nil, err.
func Ints(reply interface{}, err error) ([]int, error) {
Expand Down
10 changes: 10 additions & 0 deletions redis/reply_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,16 @@ var replyTests = []struct {
ve(redis.Strings(nil, nil)),
ve([]string(nil), redis.ErrNil),
},
{
"byteslices([v1, v2])",
ve(redis.ByteSlices([]interface{}{[]byte("v1"), []byte("v2")}, nil)),
ve([][]byte{[]byte("v1"), []byte("v2")}, nil),
},
{
"byteslices(nil)",
ve(redis.ByteSlices(nil, nil)),
ve([][]byte(nil), redis.ErrNil),
},
{
"values([v1, v2])",
ve(redis.Values([]interface{}{[]byte("v1"), []byte("v2")}, nil)),
Expand Down

0 comments on commit 6f4b077

Please sign in to comment.