Skip to content

Commit

Permalink
Merge pull request #38 from codecrafters-io/unsafe-reads
Browse files Browse the repository at this point in the history
Enhance string decoding error handling in RealDecoder
  • Loading branch information
ryan-gang authored Dec 12, 2024
2 parents a27c6a6 + 7c9c216 commit a880f2c
Showing 1 changed file with 22 additions and 3 deletions.
25 changes: 22 additions & 3 deletions protocol/decoder/real_decoder.go
Original file line number Diff line number Diff line change
Expand Up @@ -256,6 +256,11 @@ func (rd *RealDecoder) GetString() (string, error) {
return "", err
}

if rd.Remaining() < n {
rem := rd.Remaining()
return "", errors.NewPacketDecodingError(fmt.Sprintf("Expected string length to be %d bytes, got %d bytes", n, rem), "STRING")
}

tmpStr := string(rd.raw[rd.off : rd.off+n])
rd.off += n
return tmpStr, nil
Expand All @@ -270,6 +275,11 @@ func (rd *RealDecoder) GetNullableString() (*string, error) {
return nil, err
}

if rd.Remaining() < n {
rem := rd.Remaining()
return nil, errors.NewPacketDecodingError(fmt.Sprintf("Expected string length to be %d bytes, got %d bytes", n, rem), "NULLABLE_STRING")
}

tmpStr := string(rd.raw[rd.off : rd.off+n])
rd.off += n
return &tmpStr, nil
Expand All @@ -288,6 +298,12 @@ func (rd *RealDecoder) GetCompactString() (string, error) {
if length < 0 {
return "", errors.NewPacketDecodingError(fmt.Sprintf("Expected COMPACT_STRING length to be > 0, got %d", length), "COMPACT_STRING")
}

if rd.Remaining() < length {
rem := rd.Remaining()
return "", errors.NewPacketDecodingError(fmt.Sprintf("Expected string length to be %d bytes, got %d bytes", length, rem), "COMPACT_STRING")
}

tmpStr := string(rd.raw[rd.off : rd.off+length])
rd.off += length
return tmpStr, nil
Expand All @@ -308,6 +324,11 @@ func (rd *RealDecoder) GetCompactNullableString() (*string, error) {
return nil, errors.NewPacketDecodingError(fmt.Sprintf("Expected compact nullable string length to be > 0, got %d", length), "COMPACT_NULLABLE_STRING")
}

if rd.Remaining() < length {
rem := rd.Remaining()
return nil, errors.NewPacketDecodingError(fmt.Sprintf("Expected string length to be %d bytes, got %d bytes", length, rem), "COMPACT_NULLABLE_STRING")
}

tmpStr := string(rd.raw[rd.off : rd.off+length])
rd.off += length
return &tmpStr, nil
Expand Down Expand Up @@ -456,9 +477,7 @@ func (rd *RealDecoder) GetRawBytesFromOffset(length int) ([]byte, error) {

if rd.off >= len(rd.raw) {
return nil, errors.NewPacketDecodingError(fmt.Sprintf("Expected offset to be less than length of raw bytes (%d), got %d", len(rd.raw), rd.off), "RAW_BYTES_FROM_OFFSET")
}

if rd.off+length > len(rd.raw) {
} else if rd.off+length > len(rd.raw) {
return nil, errors.NewPacketDecodingError(fmt.Sprintf("Expected offset to be less than length of raw bytes (%d), got %d", len(rd.raw), rd.off), "RAW_BYTES_FROM_OFFSET")
}

Expand Down

0 comments on commit a880f2c

Please sign in to comment.