Skip to content

Commit

Permalink
feat: new method--HStrLen(#136)
Browse files Browse the repository at this point in the history
  • Loading branch information
qishenonly committed Jul 6, 2023
1 parent 5523207 commit 30b4908
Show file tree
Hide file tree
Showing 2 changed files with 70 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 @@ -616,3 +616,40 @@ func (hs *HashStructure) HDecrBy(key, field []byte, decrement int64) (int64, err

return val, nil
}

// HStrLen returns the string length of the value associated with field in the hash stored at key.
func (hs *HashStructure) HStrLen(key, field []byte) (int, error) {
// Check the parameters
if len(key) == 0 || len(field) == 0 {
return 0, _const.ErrKeyIsEmpty
}

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

// If the counter is 0, return 0
if hashMeta.counter == 0 {
return 0, 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
value, err := hs.db.Get(hfBuf)
if err != nil && err == _const.ErrKeyNotFound {
return 0, nil
}

return len(value), nil
}
33 changes: 33 additions & 0 deletions structure/hash_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -241,3 +241,36 @@ func TestHashStructure_HDecrBy(t *testing.T) {
assert.Equal(t, v4, int64(0))

}

func TestHashStructure_HStrLen(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)

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

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

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

l4, err := hash.HStrLen(randkv.GetTestKey(1), []byte("field4"))
assert.Nil(t, err)
assert.Equal(t, l4, 0)

}

0 comments on commit 30b4908

Please sign in to comment.