From 8c49e03997128de4761acaaa6606d58f87d92c6c Mon Sep 17 00:00:00 2001 From: alex Date: Sun, 5 Jul 2026 22:56:44 +0200 Subject: added LPOP and RPOP keywords --- main.go | 66 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) (limited to 'main.go') diff --git a/main.go b/main.go index 510a0f0..2fd1bd3 100644 --- a/main.go +++ b/main.go @@ -238,6 +238,72 @@ func handleLrange(conn net.Conn, key string, start, stop int) { conn.Write(serializeRESP(resultList)) } +func handleLpop(conn net.Conn, key string){ + db.mu.Lock() + defer db.mu.Unlock() + + value, exists := db.data[key] + if !exists { + conn.Write(serializeRESP(nil)) + return + } + + typedList, ok := value.([]string) + if !ok { + err := errors.New("WRONGTYPE Operation against a key holding the wrong kind of value") + conn.Write(serializeRESP(err)) + return + } + + if len(typedList) == 0 { + conn.Write(serializeRESP(nil)) + return + } + + item := typedList[0] + newList := typedList[1:] + if len(newList) <= 0 { + delete(db.data, key) + }else{ + db.data[key] = newList + } + conn.Write(serializeRESP(item)) + +} + +func handleRpop(conn net.Conn, key string){ + db.mu.Lock() + defer db.mu.Unlock() + + value, exists := db.data[key] + if !exists { + conn.Write(serializeRESP(nil)) + return + } + + typedList, ok := value.([]string) + if !ok { + err := errors.New("WRONGTYPE Operation against a key holding the wrong kind of value") + conn.Write(serializeRESP(err)) + return + } + + if len(typedList) == 0 { + conn.Write(serializeRESP(nil)) + return + } + + item := typedList[len(typedList)-1] + newList := typedList[:len(typedList)-1] + if len(newList) <= 0 { + delete(db.data, key) + }else{ + db.data[key] = newList + } + conn.Write(serializeRESP(item)) + +} + func serializeRESP(v any) []byte { switch val := v.(type) { case string: -- cgit v1.2.3