Skip to content

Commit

Permalink
feat: new method--decrBy (#135)
Browse files Browse the repository at this point in the history
  • Loading branch information
qishenonly committed Jul 4, 2023
1 parent d6ebb62 commit 8590416
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
28 changes: 28 additions & 0 deletions structure/string.go
Original file line number Diff line number Diff line change
Expand Up @@ -269,6 +269,34 @@ func (s *StringStructure) Decr(key []byte, ttl time.Duration) error {
return s.Set(key, newValue, ttl)
}

// DecrBy decrements the integer 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) DecrBy(key []byte, amount int, ttl time.Duration) error {
// Get the old value
oldValue, err := s.Get(key)
if err != nil {
return err
}

// Convert the old value to an integer
oldIntValue, err := strconv.Atoi(string(oldValue))
if err != nil {
return err
}

// Decrement the integer value
newIntValue := oldIntValue - amount

// Convert the new integer value to a byte slice
newValue := []byte(strconv.Itoa(newIntValue))

// Set the value
return s.Set(key, newValue, ttl)
}

// encodeStringValue encodes the value
// format: [type][expire][value]
// type: 1 byte
Expand Down
17 changes: 17 additions & 0 deletions structure/string_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -173,3 +173,20 @@ func TestStringStructure_Decr(t *testing.T) {
v2, _ := str.Get(randkv.GetTestKey(1))
assert.Equal(t, string(v2), "-1")
}

func TestStringStructure_DecrBy(t *testing.T) {
str := initdb()

err = str.Set(randkv.GetTestKey(1), []byte("1"), 0)
assert.Nil(t, err)

err := str.DecrBy(randkv.GetTestKey(1), 10, 0)
assert.Nil(t, err)
v1, _ := str.Get(randkv.GetTestKey(1))
assert.Equal(t, string(v1), "-9")

err = str.DecrBy(randkv.GetTestKey(1), 10, 0)
assert.Nil(t, err)
v2, _ := str.Get(randkv.GetTestKey(1))
assert.Equal(t, string(v2), "-19")
}

0 comments on commit 8590416

Please sign in to comment.