Implemented LPUSH, RPUSH, and LRANGE commands

This commit is contained in:
Kelvin Clement Mwinuka
2023-07-05 07:10:59 +08:00
parent f744ed8a06
commit 2ea87c64f3
5 changed files with 228 additions and 23 deletions

View File

@@ -10,6 +10,8 @@ import (
)
type Server interface {
Lock()
Unlock()
GetData(key string) interface{}
SetData(key string, value interface{})
}
@@ -53,11 +55,13 @@ func handleGet(cmd []string, s Server, conn *bufio.Writer) {
return
}
s.Lock()
value := s.GetData(cmd[1])
s.Unlock()
switch value.(type) {
default:
fmt.Println("Error. The requested object's type cannot be returned with the GET command")
conn.Write([]byte("-Error type cannot be returned with the GET command\r\n\n"))
case nil:
conn.Write([]byte("+nil\r\n\n"))
case string:
@@ -74,6 +78,8 @@ func handleGet(cmd []string, s Server, conn *bufio.Writer) {
func handleMGet(cmd []string, s Server, conn *bufio.Writer) {
vals := []string{}
s.Lock()
for _, key := range cmd[1:] {
switch s.GetData(key).(type) {
case nil:
@@ -87,6 +93,8 @@ func handleMGet(cmd []string, s Server, conn *bufio.Writer) {
}
}
s.Unlock()
conn.Write([]byte(fmt.Sprintf("*%d\r\n", len(vals))))
for _, val := range vals {
@@ -103,11 +111,15 @@ func handleSet(cmd []string, s Server, conn *bufio.Writer) {
conn.Write([]byte("-Error wrong number of args for SET command\r\n\n"))
conn.Flush()
case x > 3:
s.Lock()
s.SetData(cmd[1], strings.Join(cmd[2:], " "))
s.Unlock()
conn.Write([]byte("+OK\r\n"))
case x == 3:
val, err := strconv.ParseFloat(cmd[2], 32)
s.Lock()
if err != nil {
s.SetData(cmd[1], cmd[2])
} else if !utils.IsInteger(val) {
@@ -116,6 +128,8 @@ func handleSet(cmd []string, s Server, conn *bufio.Writer) {
s.SetData(cmd[1], int(val))
}
s.Unlock()
conn.Write([]byte("+OK\r\n\n"))
conn.Flush()
}