@@ -889,51 +889,34 @@ buffered_read1(buffered *self, PyObject *args)
889889 if (n == 0 )
890890 return PyBytes_FromStringAndSize (NULL , 0 );
891891
892- if (!ENTER_BUFFERED (self ))
893- return NULL ;
894-
895892 /* Return up to n bytes. If at least one byte is buffered, we
896893 only return buffered bytes. Otherwise, we do one raw read. */
897894
898- /* XXX: this mimicks the io.py implementation but is probably wrong.
899- If we need to read from the raw stream, then we could actually read
900- all `n` bytes asked by the caller (and possibly more, so as to fill
901- our buffer for the next reads). */
902-
903895 have = Py_SAFE_DOWNCAST (READAHEAD (self ), Py_off_t , Py_ssize_t );
904896 if (have > 0 ) {
905- if (n > have )
906- n = have ;
907- res = PyBytes_FromStringAndSize (self -> buffer + self -> pos , n );
908- if (res == NULL )
909- goto end ;
910- self -> pos += n ;
911- goto end ;
897+ n = Py_MIN (have , n );
898+ res = _bufferedreader_read_fast (self , n );
899+ assert (res != Py_None );
900+ return res ;
912901 }
913-
914- if (self -> writable ) {
915- res = buffered_flush_and_rewind_unlocked (self );
916- if (res == NULL )
917- goto end ;
902+ res = PyBytes_FromStringAndSize (NULL , n );
903+ if (res == NULL )
904+ return NULL ;
905+ if (!ENTER_BUFFERED (self )) {
918906 Py_DECREF (res );
907+ return NULL ;
919908 }
920-
921- /* Fill the buffer from the raw stream, and copy it to the result. */
922909 _bufferedreader_reset_buf (self );
923- r = _bufferedreader_fill_buffer (self );
924- if (r == -1 )
925- goto end ;
910+ r = _bufferedreader_raw_read (self , PyBytes_AS_STRING (res ), n );
911+ LEAVE_BUFFERED (self )
912+ if (r == -1 ) {
913+ Py_DECREF (res );
914+ return NULL ;
915+ }
926916 if (r == -2 )
927917 r = 0 ;
928918 if (n > r )
929- n = r ;
930- res = PyBytes_FromStringAndSize (self -> buffer , n );
931- if (res == NULL )
932- goto end ;
933- self -> pos = n ;
934-
935- end :
936- LEAVE_BUFFERED (self )
919+ _PyBytes_Resize (& res , r );
937920 return res ;
938921}
939922
0 commit comments