jonyoder opened a new pull request, #3293:
URL: https://github.com/apache/fory/pull/3293

   ## What does this PR do?
   
   Fixes a panic in `readUTF16LE` when the byte count is odd (malformed UTF-16 
data).
   
   ## Problem
   
   When `readUTF16LE` receives an odd byte count, the function panics with:
   ```
   panic: runtime error: index out of range [N] with length N
   ```
   
   This occurs because the loop iterates up to `byteCount` but tries to access 
`data[i+1]` on the last iteration when `i = byteCount - 1` (for odd 
`byteCount`).
   
   ### Steps to Reproduce
   
   ```go
   func TestReadUTF16LE_OddByteCount(t *testing.T) {
       // Data: 5 bytes where only first 4 form valid UTF-16
       data := []byte{0x48, 0x00, 0x69, 0x00, 0xFF}
       buf := NewByteBuffer(data)
       err := &Error{}
   
       // This panics without the fix
       result := readUTF16LE(buf, 5, err)
   }
   ```
   
   ### Root Cause
   
   In `go/fory/string.go`, line 89-90:
   ```go
   for i := 0; i < byteCount; i += 2 {
       u16s[i/2] = uint16(data[i]) | uint16(data[i+1])<<8  // Panics when i+1 
>= len(data)
   }
   ```
   
   ## Solution
   
   Round down `byteCount` to the nearest even boundary before iterating:
   ```go
   evenByteCount := byteCount &^ 1  // Round down to even
   for i := 0; i < evenByteCount; i += 2 {
       u16s[i/2] = uint16(data[i]) | uint16(data[i+1])<<8
   }
   ```
   
   This gracefully handles malformed UTF-16 data by ignoring the trailing byte 
instead of panicking.
   
   ## Tests Added
   
   - `TestReadUTF16LE_OddByteCount`: Verifies no panic with odd byte count
   - `TestReadUTF16LE_SingleByte`: Verifies empty string for single byte input
   - `TestReadUTF16LE_EvenByteCount`: Verifies normal case still works
   - `TestReadUTF16LE_EmptyBuffer`: Verifies empty input handling
   - `TestReadUTF16LE_SurrogatePair`: Verifies emoji/surrogate pair decoding
   
   ## Checklist
   
   - [x] I have read the [Contributing 
Guidelines](https://github.com/apache/fory/blob/main/CONTRIBUTING.md)
   - [x] All tests pass (`go test -v ./...` in `go/fory`)
   - [x] License headers are correct (hawkeye check passed)
   - [x] PR title follows conventional commits format


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to