Skip to content

Commit

Permalink
opt: refact dict data structure
Browse files Browse the repository at this point in the history
  • Loading branch information
satoshi-099 committed Jul 3, 2024
1 parent 26bab17 commit ae15977
Show file tree
Hide file tree
Showing 10 changed files with 56 additions and 622 deletions.
39 changes: 22 additions & 17 deletions command.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,8 +83,8 @@ func pingCommand(writer *RESPWriter, _ []RESP) {

func setCommand(writer *RESPWriter, args []RESP) {
key := args[0].ToString()
value := args[1].ToBytes()
db.strs.Set(key, value)
value := args[1].Clone()
db.dict.Set(key, value)
writer.WriteString("OK")
}

Expand All @@ -96,48 +96,53 @@ func msetCommand(writer *RESPWriter, args []RESP) {
}
for i := 0; i < len(args); i += 2 {
key := args[i].ToString()
value := args[i+1].ToBytes()
db.strs.Set(key, value)
value := args[i+1].Clone()
db.dict.Set(key, value)
}
writer.WriteString("OK")
}

func incrCommand(writer *RESPWriter, args []RESP) {
key := args[0].ToString()

val, ok := db.strs.Get(key)
val, ok := db.dict.Get(key)
if !ok {
db.strs.Set(key, []byte("1"))
db.dict.Set(key, []byte("1"))
writer.WriteInteger(1)
return
}

num, err := RESP(val).ToInt()
valBytes, ok := val.([]byte)
if !ok {
writer.WriteError(ErrWrongType)
return
}

num, err := RESP(valBytes).ToInt()
if err != nil {
writer.WriteError(ErrParseInteger)
return
}
num++

db.strs.Set(key, []byte(strconv.Itoa(num)))
db.dict.Set(key, []byte(strconv.Itoa(num)))
writer.WriteInteger(num)
}

func getCommand(writer *RESPWriter, args []RESP) {
key := args[0].ToStringUnsafe()

value, ok := db.strs.Get(key)
if ok {
writer.WriteBulk(value)
val, ok := db.dict.Get(key)
if !ok {
writer.WriteNull()
return
}

// check extra maps
_, ok = db.extras.Get(key)
valBytes, ok := val.([]byte)
if ok {
writer.WriteError(ErrWrongType)
writer.WriteBulk(valBytes)
} else {
writer.WriteNull()
writer.WriteError(ErrWrongType)
}
}

Expand Down Expand Up @@ -403,7 +408,7 @@ func fetchZSet(key string, setnx ...bool) (ZSet, error) {
}

func fetch[T any](key string, new func() T, setnx ...bool) (v T, err error) {
item, ok := db.extras.Get(key)
item, ok := db.dict.Get(key)
if ok {
v, ok := item.(T)
if ok {
Expand All @@ -413,7 +418,7 @@ func fetch[T any](key string, new func() T, setnx ...bool) (v T, err error) {
}
v = new()
if len(setnx) > 0 && setnx[0] {
db.extras.Put(key, v)
db.dict.Set(key, v)
}
return v, nil
}
94 changes: 0 additions & 94 deletions internal/dict/bench_test.go

This file was deleted.

87 changes: 0 additions & 87 deletions internal/dict/benchmark/main.go

This file was deleted.

Loading

0 comments on commit ae15977

Please sign in to comment.