From 40792c82e1722dca7d98911489bedefe688e30a5 Mon Sep 17 00:00:00 2001 From: qishenonly <1050026498@qq.com> Date: Wed, 5 Jul 2023 16:34:12 +0800 Subject: [PATCH] feat: method--HExists(#136 ID 6) --- structure/hash.go | 37 +++++++++++++++++++++++++++++++++++++ structure/hash_test.go | 17 +++++++++++++++++ 2 files changed, 54 insertions(+) diff --git a/structure/hash.go b/structure/hash.go index 2946a070..0e671a7a 100644 --- a/structure/hash.go +++ b/structure/hash.go @@ -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 +} diff --git a/structure/hash_test.go b/structure/hash_test.go index 3baff35b..fc7258ea 100644 --- a/structure/hash_test.go +++ b/structure/hash_test.go @@ -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) + +}