From a4dad4805181812c106168656a678d43fa6468f2 Mon Sep 17 00:00:00 2001 From: Shashi sah <86319846+shashi-sah2003@users.noreply.github.com> Date: Wed, 16 Oct 2024 18:06:03 +0530 Subject: [PATCH] #1101: Refactor evalAPPEND to handle leading zeros in value (#1107) --- integration_tests/commands/async/append_test.go | 11 +++++++++++ internal/eval/eval.go | 9 +++++++++ internal/eval/eval_test.go | 17 +++++++++++++++++ 3 files changed, 37 insertions(+) diff --git a/integration_tests/commands/async/append_test.go b/integration_tests/commands/async/append_test.go index cea333524..189b75190 100644 --- a/integration_tests/commands/async/append_test.go +++ b/integration_tests/commands/async/append_test.go @@ -46,6 +46,17 @@ func TestAPPEND(t *testing.T) { }, expected: []interface{}{int64(0), int64(1), int64(2), "12", "OK", int64(2), "12"}, }, + { + name: "APPEND with leading zeros", + commands: []string{ + "DEL key", + "APPEND key 0043", + "GET key", + "APPEND key 0034", + "GET key", + }, + expected: []interface{}{int64(0), int64(4), "0043", int64(8), "00430034"}, + }, { name: "APPEND with Various Data Types", commands: []string{ diff --git a/internal/eval/eval.go b/internal/eval/eval.go index 901f7b753..83a48b117 100644 --- a/internal/eval/eval.go +++ b/internal/eval/eval.go @@ -4582,6 +4582,15 @@ func evalAPPEND(args []string, store *dstore.Store) []byte { if obj == nil { // Key does not exist path + + // check if the value starts with '0' and has more than 1 character to handle leading zeros + if len(value) > 1 && value[0] == '0' { + // treat as string if has leading zeros + store.Put(key, store.NewObj(value, -1, object.ObjTypeString, object.ObjEncodingRaw)) + return clientio.Encode(len(value), false) + } + + // Deduce type and encoding based on the value if no leading zeros oType, oEnc := deduceTypeEncoding(value) var storedValue interface{} diff --git a/internal/eval/eval_test.go b/internal/eval/eval_test.go index d02b53dd5..ff6762154 100644 --- a/internal/eval/eval_test.go +++ b/internal/eval/eval_test.go @@ -5171,6 +5171,23 @@ func testEvalAPPEND(t *testing.T, store *dstore.Store) { input: []string{"bitKey", "val"}, output: diceerrors.NewErrWithFormattedMessage(diceerrors.WrongTypeErr), }, + "append value with leading zeros":{ + setup: func() { + store.Del("key_with_leading_zeros") + }, + input: []string{"key_with_leading_zeros", "0043"}, + output: clientio.Encode(4, false), // The length of "0043" is 4 + validator: func(output []byte){ + obj := store.Get("key_with_leading_zeros") + _, enc := object.ExtractTypeEncoding(obj) + if enc != object.ObjEncodingRaw { + t.Errorf("expected encoding to be Raw for string with leading zeros") + } + if obj.Value.(string) != "0043" { + t.Errorf("expected value to be '0043', got %v", obj.Value) + } + }, + }, } runEvalTests(t, tests, evalAPPEND, store)