Skip to content

Commit

Permalink
DiceDB#1245: Fix RESP parser to parse strings with multiple \r (DiceD…
Browse files Browse the repository at this point in the history
  • Loading branch information
c-harish authored Nov 9, 2024
1 parent 9a28b15 commit 60c59df
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 9 deletions.
35 changes: 27 additions & 8 deletions internal/clientio/resp.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,15 +54,34 @@ func readLength(buf *bytes.Buffer) (int64, error) {
}

func readStringUntilSr(buf *bytes.Buffer) (string, error) {
s, err := buf.ReadString('\r')
if err != nil {
return utils.EmptyStr, err
}
// incrementing to skip `\n`
if _, err := buf.ReadByte(); err != nil {
return utils.EmptyStr, err
var result []byte

for {
byteRead, err := buf.ReadByte()
if err != nil {
return utils.EmptyStr, err
}

result = append(result, byteRead)

// If we find '\r', we check the next byte for '\n'
if byteRead == '\r' {
nextByte, err := buf.ReadByte() // Peek the next byte
if err != nil {
return utils.EmptyStr, err
}

// If the next byte is '\n', we've found a valid end of string
if nextByte == '\n' {
break
}

// Otherwise, add the next byte to the result and continue
result = append(result, nextByte)
}
}
return s[:len(s)-1], nil
// Return without the last '\r'
return string(result[:len(result)-1]), nil
}

// reads a RESP encoded simple string from data and returns
Expand Down
5 changes: 4 additions & 1 deletion internal/clientio/resp_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@ import (

func TestSimpleStringDecode(t *testing.T) {
cases := map[string]string{
"+OK\r\n": "OK",
"+OK\r\n": "OK",
"+Hello\rWorld\r\n": "Hello\rWorld",
"+Hello\rWorld\rAgain\r\n": "Hello\rWorld\rAgain",
}
for k, v := range cases {
p := clientio.NewRESPParser(bytes.NewBuffer([]byte(k)))
Expand All @@ -25,6 +27,7 @@ func TestSimpleStringDecode(t *testing.T) {
if v != value {
t.Fail()
}
fmt.Println(v, value)
}
}

Expand Down

0 comments on commit 60c59df

Please sign in to comment.