Skip to content

Commit

Permalink
feat: optimize hash mem copy
Browse files Browse the repository at this point in the history
  • Loading branch information
xgzlucario committed Nov 30, 2024
1 parent f9a2818 commit a9aa60e
Show file tree
Hide file tree
Showing 4 changed files with 13 additions and 8 deletions.
11 changes: 8 additions & 3 deletions command.go
Original file line number Diff line number Diff line change
Expand Up @@ -93,11 +93,15 @@ func pingCommand(writer *resp.Writer, _ []resp.RESP) {
}

func setCommand(writer *resp.Writer, args []resp.RESP) {
key := args[0].ToString()
value := args[1].Clone()
key := args[0].ToStringUnsafe()
extra := args[2:]
var ttl int64

_, ttl = db.dict.Get(key)
if ttl == KeyNotExist {
key = args[0].ToString() // copy
}

for len(extra) > 0 {
arg := extra[0].ToStringUnsafe()

Expand Down Expand Up @@ -140,6 +144,7 @@ func setCommand(writer *resp.Writer, args []resp.RESP) {
}
}

value := args[1].Clone()
db.dict.SetWithTTL(key, value, ttl)
writer.WriteSString("OK")
}
Expand Down Expand Up @@ -212,7 +217,7 @@ func hsetCommand(writer *resp.Writer, args []resp.RESP) {
var count int
for i := 0; i < len(args); i += 2 {
field := args[i].ToString()
value := args[i+1].Clone()
value := args[i+1] // no need to clone
if hmap.Set(field, value) {
count++
}
Expand Down
4 changes: 2 additions & 2 deletions const.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@ const (
)

const (
KeepTTL = redis.KeepTTL
KeyNotExist = -2
KeepTTL int64 = redis.KeepTTL
KeyNotExist int64 = -2
)

const (
Expand Down
4 changes: 2 additions & 2 deletions dict.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ func New() *Dict {
}
}

func (dict *Dict) Get(key string) (any, int) {
func (dict *Dict) Get(key string) (any, int64) {
data, ok := dict.data.Get(key)
if !ok {
// key not exist
Expand All @@ -37,7 +37,7 @@ func (dict *Dict) Get(key string) (any, int) {
return nil, KeyNotExist
}

return data, int(ts-now) / int(time.Second)
return data, (ts - now) / int64(time.Second)
}

func (dict *Dict) Set(key string, data any) {
Expand Down
2 changes: 1 addition & 1 deletion dict_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ func TestDict(t *testing.T) {
time.Sleep(time.Second / 10)

data, ttl := dict.Get("key")
assert.Equal(ttl, 59)
assert.Equal(ttl, int64(59))
assert.Equal(data, []byte("hello"))

res := dict.SetTTL("key", time.Now().Add(-time.Second).UnixNano())
Expand Down

0 comments on commit a9aa60e

Please sign in to comment.