Skip to content

Commit

Permalink
feat: new method--HTypes(#136)
Browse files Browse the repository at this point in the history
  • Loading branch information
qishenonly committed Jul 6, 2023
1 parent 18cbeb4 commit 6a71211
Show file tree
Hide file tree
Showing 2 changed files with 69 additions and 0 deletions.
37 changes: 37 additions & 0 deletions structure/hash.go
Original file line number Diff line number Diff line change
Expand Up @@ -763,3 +763,40 @@ func (hs *HashStructure) HSetNX(key, field, value []byte) (bool, error) {
}

}

// HTypes returns if field is an existing hash key in the hash stored at key.
func (hs *HashStructure) HTypes(key, field []byte) (string, error) {
// Check the parameters
if len(key) == 0 || len(field) == 0 {
return "", _const.ErrKeyIsEmpty
}

// Find the hash metadata by the given key
hashMeta, err := hs.findHashMeta(key, Hash)
if err != nil {
return "", err
}

// If the counter is 0, return 0
if hashMeta.counter == 0 {
return "", nil
}

// Create a new HashField
hf := &HashField{
field: field,
key: key,
version: hashMeta.version,
}

// Encode the HashField
hfBuf := hf.encodeHashField()

// Get the field from the database
_, err = hs.db.Get(hfBuf)
if err != nil && err == _const.ErrKeyNotFound {
return "", _const.ErrKeyNotFound
} else {
return "hash", nil
}
}
32 changes: 32 additions & 0 deletions structure/hash_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -360,3 +360,35 @@ func TestHashStructure_HSetNX(t *testing.T) {
assert.False(t, ok6)

}

func TestHashStructure_HTypes(t *testing.T) {
hash := initHashDB()

ok1, err := hash.HSet(randkv.GetTestKey(1), []byte("field1"), []byte("1000"))
assert.Nil(t, err)
assert.True(t, ok1)

ok2, err := hash.HSet(randkv.GetTestKey(1), []byte("field2"), []byte("100"))
assert.Nil(t, err)
assert.True(t, ok2)

ok3, err := hash.HSet(randkv.GetTestKey(1), []byte("field3"), []byte("10"))
assert.Nil(t, err)
assert.True(t, ok3)

type1, err := hash.HTypes(randkv.GetTestKey(1), []byte("field1"))
assert.Nil(t, err)
assert.Equal(t, type1, "hash")

type2, err := hash.HTypes(randkv.GetTestKey(1), []byte("field2"))
assert.Nil(t, err)
assert.Equal(t, type2, "hash")

type3, err := hash.HTypes(randkv.GetTestKey(1), []byte("field3"))
assert.Nil(t, err)
assert.Equal(t, type3, "hash")

type4, err := hash.HTypes(randkv.GetTestKey(1), []byte("field4"))
assert.Equal(t, "", type4)
assert.Equal(t, err, _const.ErrKeyNotFound)
}

0 comments on commit 6a71211

Please sign in to comment.