Skip to content

Commit 5105c55

Browse files
committed
Return at most DEFAULT_BUFFER_SIZE bytes if size is 0/-1/unspecified
1 parent 8a96f88 commit 5105c55

4 files changed

Lines changed: 11 additions & 5 deletions

File tree

Doc/library/io.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -775,7 +775,7 @@ than raw I/O does.
775775

776776
Return a copy of the buffer from the current position onwards without advancing the position.
777777

778-
If *size* is zero or omitted, the returned :class:`bytes` object extends to EOF.
778+
If *size* is less than one or omitted, at most `DEFAULT_BUFFER_SIZE` bytes are returned.
779779
Otherwise, at most *size* bytes are returned.
780780
Return an empty :class:`bytes` object at EOF.
781781

Lib/_pyio.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1004,7 +1004,7 @@ def peek(self, size=0):
10041004
if self.closed:
10051005
raise ValueError("peek on closed file")
10061006
if size < 1:
1007-
return self._buffer[self._pos:]
1007+
return self._buffer[self._pos:self._pos + io.DEFAULT_BUFFER_SIZE]
10081008
return self._buffer[self._pos:self._pos + size]
10091009

10101010
def truncate(self, pos=None):

Lib/test/test_io/test_memoryio.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -616,8 +616,11 @@ def test_peek(self):
616616
# Length greater than DEFAULT_BUFFER_SIZE
617617
buf = self.buftype("1234567890" * io.DEFAULT_BUFFER_SIZE)
618618
with self.ioclass(buf) as memio:
619-
self.assertEqual(memio.peek(), buf)
619+
self.assertEqual(memio.peek(), buf[:io.DEFAULT_BUFFER_SIZE])
620+
self.assertEqual(memio.peek(0), buf[:io.DEFAULT_BUFFER_SIZE])
621+
self.assertEqual(memio.peek(-1), buf[:io.DEFAULT_BUFFER_SIZE])
620622
self.assertEqual(memio.peek(io.DEFAULT_BUFFER_SIZE + 100), buf[:io.DEFAULT_BUFFER_SIZE + 100])
623+
self.assertEqual(memio.peek(io.DEFAULT_BUFFER_SIZE * 100), buf)
621624

622625
# Current position beyond buffer end
623626
with self.ioclass(buf) as memio:

Modules/_io/bytesio.c

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -527,10 +527,13 @@ _io_BytesIO_peek_impl(bytesio *self, Py_ssize_t size)
527527
{
528528
CHECK_CLOSED(self);
529529

530+
if (size < 1) {
531+
size = DEFAULT_BUFFER_SIZE;
532+
}
533+
530534
/* adjust invalid sizes */
531535
Py_ssize_t n = self->string_size - self->pos;
532-
533-
if (size < 1 || size > n) {
536+
if (size > n) {
534537
size = n;
535538
/* n can be negative after truncate() or seek() */
536539
if (size < 0) {

0 commit comments

Comments
 (0)