Skip to content

Commit

Permalink
Make Hgetall support a wider variety of types, like pointers and inte…
Browse files Browse the repository at this point in the history
…rfaces.
  • Loading branch information
Michael Hoisie committed May 27, 2010
1 parent 8752d2b commit c6345e5
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 9 deletions.
35 changes: 26 additions & 9 deletions redis.go
Original file line number Diff line number Diff line change
Expand Up @@ -255,9 +255,16 @@ func (client *Client) Keys(pattern string) ([]string, os.Error) {
return nil, err
}

keys := bytes.Fields(res.([]byte))
ret := make([]string, len(keys))
for i, k := range keys {
var ok bool
var keydata [][]byte

if keydata, ok = res.([][]byte); ok {
// key data is already a double byte array
} else {
keydata = bytes.Fields(res.([]byte))
}
ret := make([]string, len(keydata))
for i, k := range keydata {
ret[i] = string(k)
}
return ret, nil
Expand Down Expand Up @@ -958,11 +965,12 @@ func valueToString(v reflect.Value) (string, os.Error) {
return "", os.NewError("Unsupported type")
}

func (client *Client) Hmset(key string, mapping interface{}) os.Error {
var args vector.StringVector
args.Push(key)

switch v := reflect.NewValue(mapping).(type) {
func containerToString(val reflect.Value, args *vector.StringVector) os.Error {
switch v := val.(type) {
case *reflect.PtrValue:
return containerToString(reflect.Indirect(v), args)
case *reflect.InterfaceValue:
return containerToString(v.Elem(), args)
case *reflect.MapValue:
if _, ok := v.Type().(*reflect.MapType).Key().(*reflect.StringType); !ok {
return os.NewError("Unsupported type - map key must be a string")
Expand All @@ -987,8 +995,17 @@ func (client *Client) Hmset(key string, mapping interface{}) os.Error {
args.Push(s)
}
}
return nil
}

_, err := client.sendCommand("HMSET", args)
func (client *Client) Hmset(key string, mapping interface{}) os.Error {
args := new(vector.StringVector)
args.Push(key)
err := containerToString(reflect.NewValue(mapping), args)
if err != nil {
return err
}
_, err = client.sendCommand("HMSET", *args)
if err != nil {
return err
}
Expand Down
11 changes: 11 additions & 0 deletions redis_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -249,6 +249,17 @@ func TestHash(t *testing.T) {
t.Fatal("verifyHash Hgetall failed")
}

//text extraneous fields
client.Hset("h3", "f", []byte("ffffff"))
var test5 tt
err = client.Hgetall("h3", &test5)
if err != nil {
t.Fatal("verifyHash Hgetall failed", err.String())
}
if !reflect.DeepEqual(test5, test3) {
t.Fatal("verifyHash Hgetall failed")
}

client.Del("h")
client.Del("h2")
client.Del("h3")
Expand Down

0 comments on commit c6345e5

Please sign in to comment.