Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add Float64Map #605

Merged
merged 3 commits into from Mar 24, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
30 changes: 30 additions & 0 deletions redis/reply.go
Expand Up @@ -476,6 +476,36 @@ func Int64Map(result interface{}, err error) (map[string]int64, error) {
return m, nil
}

// Float64Map is a helper that converts an array of strings (alternating key, value)
// into a map[string]float64. The HGETALL commands return replies in this format.
// Requires an even number of values in result.
func Float64Map(result interface{}, err error) (map[string]float64, error) {
values, err := Values(result, err)
if err != nil {
return nil, err
}

if len(values)%2 != 0 {
return nil, fmt.Errorf("redigo: Float64Map expects even number of values result, got %d", len(values))
}

m := make(map[string]float64, len(values)/2)
for i := 0; i < len(values); i += 2 {
key, ok := values[i].([]byte)
if !ok {
return nil, fmt.Errorf("redigo: Float64Map key[%d] not a bulk string value, got %T", i, values[i])
}

value, err := Float64(values[i+1], nil)
if err != nil {
return nil, err
}

m[string(key)] = value
}
return m, nil
}

// Positions is a helper that converts an array of positions (lat, long)
// into a [][2]float64. The GEOPOS command returns replies in this format.
func Positions(result interface{}, err error) ([]*[2]float64, error) {
Expand Down
5 changes: 5 additions & 0 deletions redis/reply_test.go
Expand Up @@ -123,6 +123,11 @@ var replyTests = []struct {
ve(redis.Float64(nil, nil)),
ve(float64(0.0), redis.ErrNil),
},
{
"float64Map([[]byte, []byte])",
ve(redis.Float64Map([]interface{}{[]byte("key1"), []byte("1.234"), []byte("key2"), []byte("5.678")}, nil)),
ve(map[string]float64{"key1": 1.234, "key2": 5.678}, nil),
},
{
"uint64(1)",
ve(redis.Uint64(int64(1), nil)),
Expand Down