@@ -420,8 +420,9 @@ _io_BytesIO_tell_impl(bytesio *self)
420420 return PyLong_FromSsize_t (self -> pos );
421421}
422422
423+ // Read without advancing position
423424static PyObject *
424- read_bytes_lock_held (bytesio * self , Py_ssize_t size )
425+ peek_bytes_lock_held (bytesio * self , Py_ssize_t size )
425426{
426427 _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED (self );
427428
@@ -432,7 +433,6 @@ read_bytes_lock_held(bytesio *self, Py_ssize_t size)
432433 if (size > 1 &&
433434 self -> pos == 0 && size == PyBytes_GET_SIZE (self -> buf ) &&
434435 FT_ATOMIC_LOAD_SSIZE_RELAXED (self -> exports ) == 0 ) {
435- self -> pos += size ;
436436 return Py_NewRef (self -> buf );
437437 }
438438
@@ -444,10 +444,16 @@ read_bytes_lock_held(bytesio *self, Py_ssize_t size)
444444 }
445445
446446 output = PyBytes_AS_STRING (self -> buf ) + self -> pos ;
447- self -> pos += size ;
448447 return PyBytes_FromStringAndSize (output , size );
449448}
450449
450+ static PyObject *
451+ read_bytes_lock_held (bytesio * self , Py_ssize_t size ) {
452+ PyObject * bytes = peek_bytes_lock_held (self , size );
453+ self -> pos += size ;
454+ return bytes ;
455+ }
456+
451457/*[clinic input]
452458@critical_section
453459_io.BytesIO.read
@@ -502,17 +508,18 @@ _io_BytesIO_read1_impl(bytesio *self, Py_ssize_t size)
502508
503509/*[clinic input]
504510_io.BytesIO.peek
505- size: Py_ssize_t(accept={int, NoneType}) = - 1
511+ size: Py_ssize_t = 1
506512 /
507513
508514Return bytes from the stream without advancing the position.
509515
516+ If the size argument is zero or negative, read until EOF is reached.
510517Return an empty bytes object at EOF.
511518[clinic start generated code]*/
512519
513520static PyObject *
514521_io_BytesIO_peek_impl (bytesio * self , Py_ssize_t size )
515- /*[clinic end generated code: output=fa4d8ce28b35db9b input=afc80e71b37e7c59 ]*/
522+ /*[clinic end generated code: output=fa4d8ce28b35db9b input=cb06614a3ed0496e ]*/
516523{
517524 Py_ssize_t n ;
518525
@@ -525,11 +532,7 @@ _io_BytesIO_peek_impl(bytesio *self, Py_ssize_t size)
525532 if (size < 0 )
526533 size = 0 ;
527534 }
528- Py_ssize_t prev_pos = self -> pos ;
529- PyObject * result = read_bytes_lock_held (self , size );
530- self -> pos = prev_pos ;
531-
532- return result ;
535+ return peek_bytes_lock_held (self , size );
533536}
534537
535538
0 commit comments