@@ -394,8 +394,9 @@ _io_BytesIO_tell_impl(bytesio *self)
394394 return PyLong_FromSsize_t (self -> pos );
395395}
396396
397+ // Read without advancing position
397398static PyObject *
398- read_bytes (bytesio * self , Py_ssize_t size )
399+ peek_bytes (bytesio * self , Py_ssize_t size )
399400{
400401 const char * output ;
401402
@@ -404,15 +405,20 @@ read_bytes(bytesio *self, Py_ssize_t size)
404405 if (size > 1 &&
405406 self -> pos == 0 && size == PyBytes_GET_SIZE (self -> buf ) &&
406407 self -> exports == 0 ) {
407- self -> pos += size ;
408408 return Py_NewRef (self -> buf );
409409 }
410410
411411 output = PyBytes_AS_STRING (self -> buf ) + self -> pos ;
412- self -> pos += size ;
413412 return PyBytes_FromStringAndSize (output , size );
414413}
415414
415+ static PyObject *
416+ read_bytes (bytesio * self , Py_ssize_t size ) {
417+ PyObject * bytes = peek_bytes (self , size );
418+ self -> pos += size ;
419+ return bytes ;
420+ }
421+
416422/*[clinic input]
417423_io.BytesIO.read
418424 size: Py_ssize_t(accept={int, NoneType}) = -1
@@ -465,17 +471,18 @@ _io_BytesIO_read1_impl(bytesio *self, Py_ssize_t size)
465471
466472/*[clinic input]
467473_io.BytesIO.peek
468- size: Py_ssize_t(accept={int, NoneType}) = - 1
474+ size: Py_ssize_t = 1
469475 /
470476
471477Return bytes from the stream without advancing the position.
472478
479+ If the size argument is zero or negative, read until EOF is reached.
473480Return an empty bytes object at EOF.
474481[clinic start generated code]*/
475482
476483static PyObject *
477484_io_BytesIO_peek_impl (bytesio * self , Py_ssize_t size )
478- /*[clinic end generated code: output=fa4d8ce28b35db9b input=afc80e71b37e7c59 ]*/
485+ /*[clinic end generated code: output=fa4d8ce28b35db9b input=cb06614a3ed0496e ]*/
479486{
480487 Py_ssize_t n ;
481488
@@ -488,11 +495,7 @@ _io_BytesIO_peek_impl(bytesio *self, Py_ssize_t size)
488495 if (size < 0 )
489496 size = 0 ;
490497 }
491- Py_ssize_t prev_pos = self -> pos ;
492- PyObject * result = read_bytes (self , size );
493- self -> pos = prev_pos ;
494-
495- return result ;
498+ return peek_bytes (self , size );
496499}
497500
498501
0 commit comments