Skip to content

Comments

Fix Reader.peek() IndexError when index exceeds buffer length#912

Open
veeceey wants to merge 1 commit intoyaml:mainfrom
veeceey:fix/issue-904-reader-peek-indexerror
Open

Fix Reader.peek() IndexError when index exceeds buffer length#912
veeceey wants to merge 1 commit intoyaml:mainfrom
veeceey:fix/issue-904-reader-peek-indexerror

Conversation

@veeceey
Copy link

@veeceey veeceey commented Feb 13, 2026

Fixes #904

Problem

Reader.peek(index) raises IndexError when the requested index exceeds the available data in the buffer. This happens because after calling update(), the buffer may still not have enough data (e.g., for string inputs where raw_buffer is None and update() returns immediately). The second buffer access then crashes.

obj = yaml.loader.Loader('abc')
ret = obj.peek(4)  # IndexError: string index out of range

Fix

Added a bounds check after update() in peek(). If the requested position is still past the end of the buffer, return '\0' instead of indexing into the buffer. This is consistent with how '\0' is used as the end-of-stream sentinel throughout the parser.

Tests

Added tests covering:

  • String, bytes, and file-like stream inputs
  • Peek at exact end, one past end, and far past end
  • Empty string input
  • Normal in-range peek still works correctly

All 1280 existing legacy tests plus 3 existing modern tests continue to pass.

When peek() is called with an index beyond the available data, update()
may not be able to add enough data to the buffer (e.g. for string inputs
where raw_buffer is None). The second buffer access then raises an
IndexError instead of returning the '\0' sentinel.

Add a bounds check after update() so that peek() returns '\0' when the
requested position is past the end of the buffer, consistent with how
the null terminator is used throughout the parser.

Fixes yaml#904
@veeceey
Copy link
Author

veeceey commented Feb 19, 2026

Friendly ping - any chance someone could take a look at this when they get a chance? Happy to make any changes if needed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Reader.peek(index) throws IndexError when the stream ends, instead of returning '\0'

1 participant