Skip to content

Commit

Permalink
feat: method--HExists(#136 ID 6)
Browse files Browse the repository at this point in the history
  • Loading branch information
qishenonly committed Jul 5, 2023
1 parent f9c4cfc commit 40792c8
Show file tree
Hide file tree
Showing 2 changed files with 54 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 @@ -325,3 +325,40 @@ func (hs *HashStructure) HDel(key []byte, fields ...[]byte) (bool, error) {

return true, nil
}

// HExists determines whether a hash field exists or not.
func (hs *HashStructure) HExists(key, field []byte) (bool, error) {
// Check the parameters
if len(key) == 0 || len(field) == 0 {
return false, _const.ErrKeyIsEmpty
}

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

// If the counter is 0, return false
if hashMeta.counter == 0 {
return false, 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 false, nil
}

return true, nil
}
17 changes: 17 additions & 0 deletions structure/hash_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,3 +73,20 @@ func TestHashStructure_HDel(t *testing.T) {
assert.True(t, ok5)

}

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

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

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

ok3, err := hash.HExists(randkv.GetTestKey(1), []byte("field2"))
assert.Nil(t, err)
assert.False(t, ok3)

}

0 comments on commit 40792c8

Please sign in to comment.