Updated AdaptType function in utils to use big float and int64 for number coversions.

Updated setget and setget_test to account for new number formatting change.
This commit is contained in:
Kelvin Clement Mwinuka
2023-07-17 01:20:58 +08:00
parent 0549bcc745
commit ca7ada5731
3 changed files with 9 additions and 20 deletions

View File

@@ -60,18 +60,10 @@ func handleGet(cmd []string, s Server, conn *bufio.Writer) {
switch value.(type) { switch value.(type) {
default: default:
conn.Write([]byte("-Error type cannot be returned with the GET command\r\n\n")) conn.Write([]byte(fmt.Sprintf("+%v\r\n\n", value)))
case nil: case nil:
conn.Write([]byte("+nil\r\n\n")) conn.Write([]byte("+nil\r\n\n"))
case string:
conn.Write([]byte(fmt.Sprintf("+%s\r\n\n", value)))
case float64:
s := strings.TrimRight(fmt.Sprintf("%f", value), "0")
conn.Write([]byte(fmt.Sprintf("+%s\r\n\n", s)))
case int:
conn.Write([]byte(fmt.Sprintf(":%d\r\n\n", value)))
} }
conn.Flush() conn.Flush()
} }
@@ -88,14 +80,10 @@ func handleMGet(cmd []string, s Server, conn *bufio.Writer) {
for _, key := range cmd[1:] { for _, key := range cmd[1:] {
switch s.GetData(key).(type) { switch s.GetData(key).(type) {
default:
vals = append(vals, fmt.Sprintf("%v", s.GetData(key)))
case nil: case nil:
vals = append(vals, "nil") vals = append(vals, "nil")
case string:
vals = append(vals, fmt.Sprintf("%s", s.GetData(key)))
case float64:
vals = append(vals, strings.TrimRight(fmt.Sprintf("%f", s.GetData(key)), "0"))
case int:
vals = append(vals, fmt.Sprintf("%d", s.GetData(key)))
} }
} }

View File

@@ -37,7 +37,7 @@ func TestHandleCommand(t *testing.T) {
// GET test cases // GET test cases
{[]string{"get", "key1"}, "+value1\r\n\n"}, {[]string{"get", "key1"}, "+value1\r\n\n"},
{[]string{"get", "key2"}, ":30\r\n\n"}, {[]string{"get", "key2"}, "+30\r\n\n"},
{[]string{"get", "key3"}, "+3.142\r\n\n"}, {[]string{"get", "key3"}, "+3.142\r\n\n"},
{[]string{"get", "key4"}, "+nil\r\n\n"}, {[]string{"get", "key4"}, "+nil\r\n\n"},
{[]string{"get"}, "-Error wrong number of args for GET command\r\n\n"}, {[]string{"get"}, "-Error wrong number of args for GET command\r\n\n"},

View File

@@ -9,10 +9,10 @@ import (
"flag" "flag"
"fmt" "fmt"
"math" "math"
"math/big"
"os" "os"
"path" "path"
"reflect" "reflect"
"strconv"
"strings" "strings"
"github.com/tidwall/resp" "github.com/tidwall/resp"
@@ -103,14 +103,15 @@ func IsInteger(n float64) bool {
func AdaptType(s string) interface{} { func AdaptType(s string) interface{} {
// Adapt the type of the parameter to string, float64 or int // Adapt the type of the parameter to string, float64 or int
n, err := strconv.ParseFloat(s, 32) n, _, err := big.ParseFloat(s, 10, 256, big.RoundingMode(big.Exact))
if err != nil { if err != nil {
return s return s
} }
if IsInteger(n) { if n.IsInt() {
return int(n) i, _ := n.Int64()
return i
} }
return n return n