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) {
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:
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()
}
@@ -88,14 +80,10 @@ func handleMGet(cmd []string, s Server, conn *bufio.Writer) {
for _, key := range cmd[1:] {
switch s.GetData(key).(type) {
default:
vals = append(vals, fmt.Sprintf("%v", s.GetData(key)))
case 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
{[]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", "key4"}, "+nil\r\n\n"},
{[]string{"get"}, "-Error wrong number of args for GET command\r\n\n"},

View File

@@ -9,10 +9,10 @@ import (
"flag"
"fmt"
"math"
"math/big"
"os"
"path"
"reflect"
"strconv"
"strings"
"github.com/tidwall/resp"
@@ -103,14 +103,15 @@ func IsInteger(n float64) bool {
func AdaptType(s string) interface{} {
// 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 {
return s
}
if IsInteger(n) {
return int(n)
if n.IsInt() {
i, _ := n.Int64()
return i
}
return n