From 2524563177ac0a4cffd340b58589ee337378b4c9 Mon Sep 17 00:00:00 2001 From: qishenonly <1050026498@qq.com> Date: Tue, 4 Jul 2023 10:15:49 +0800 Subject: [PATCH] feat: new method--incrByFloat (#135) --- structure/string.go | 28 ++++++++++++++++++++++++++++ structure/string_test.go | 17 +++++++++++++++++ 2 files changed, 45 insertions(+) diff --git a/structure/string.go b/structure/string.go index 3719fcfa..318ef171 100644 --- a/structure/string.go +++ b/structure/string.go @@ -213,6 +213,34 @@ func (s *StringStructure) IncrBy(key []byte, amount int, ttl time.Duration) erro return s.Set(key, newValue, ttl) } +// IncrByFloat increments the float value of a key by the given amount +// If the key does not exist, it will be created +// If the key exists, it will be overwritten +// If the key is expired, it will be deleted +// If the key is not expired, it will be updated +func (s *StringStructure) IncrByFloat(key []byte, amount float64, ttl time.Duration) error { + // Get the old value + oldValue, err := s.Get(key) + if err != nil { + return err + } + + // Convert the old value to a float + oldFloatValue, err := strconv.ParseFloat(string(oldValue), 64) + if err != nil { + return err + } + + // Increment the float value + newFloatValue := oldFloatValue + amount + + // Convert the new float value to a byte slice + newValue := []byte(strconv.FormatFloat(newFloatValue, 'f', -1, 64)) + + // Set the value + return s.Set(key, newValue, ttl) +} + // encodeStringValue encodes the value // format: [type][expire][value] // type: 1 byte diff --git a/structure/string_test.go b/structure/string_test.go index 525ce060..6307d9c0 100644 --- a/structure/string_test.go +++ b/structure/string_test.go @@ -139,3 +139,20 @@ func TestStringStructure_IncrBy(t *testing.T) { v2, _ := str.Get(randkv.GetTestKey(1)) assert.Equal(t, string(v2), "21") } + +func TestStringStructure_IncrByFloat(t *testing.T) { + str := initdb() + + err = str.Set(randkv.GetTestKey(1), []byte("1"), 0) + assert.Nil(t, err) + + err := str.IncrByFloat(randkv.GetTestKey(1), 1.1, 0) + assert.Nil(t, err) + v1, _ := str.Get(randkv.GetTestKey(1)) + assert.Equal(t, string(v1), "2.1") + + err = str.IncrByFloat(randkv.GetTestKey(1), 1.1, 0) + assert.Nil(t, err) + v2, _ := str.Get(randkv.GetTestKey(1)) + assert.Equal(t, string(v2), "3.2") +}