Skip to content

Commit

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

// IncrBy increments 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) IncrBy(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
}

// Increment 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
21 changes: 19 additions & 2 deletions structure/string_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -115,10 +115,27 @@ func TestStringStructure_Incr(t *testing.T) {
err := str.Incr(randkv.GetTestKey(1), 0)
assert.Nil(t, err)
v1, _ := str.Get(randkv.GetTestKey(1))
t.Log(string(v1))
assert.Equal(t, string(v1), "2")

err = str.Incr(randkv.GetTestKey(1), 0)
assert.Nil(t, err)
v2, _ := str.Get(randkv.GetTestKey(1))
t.Log(string(v2))
assert.Equal(t, string(v2), "3")
}

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

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

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

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

0 comments on commit 033e236

Please sign in to comment.