Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit e532456

Browse files
committed
Issue #13393: In TextIOWrapper.read(n), try to read n characters as
once rather than limit ourselves to the default chunk size.
1 parent f34a0cd commit e532456

1 file changed

Lines changed: 9 additions & 5 deletions

File tree

Modules/_io/textio.c

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1388,7 +1388,7 @@ textiowrapper_get_decoded_chars(textio *self, Py_ssize_t n)
13881388
/* Read and decode the next chunk of data from the BufferedReader.
13891389
*/
13901390
static int
1391-
textiowrapper_read_chunk(textio *self)
1391+
textiowrapper_read_chunk(textio *self, Py_ssize_t size_hint)
13921392
{
13931393
PyObject *dec_buffer = NULL;
13941394
PyObject *dec_flags = NULL;
@@ -1430,7 +1430,10 @@ textiowrapper_read_chunk(textio *self)
14301430
}
14311431

14321432
/* Read a chunk, decode it, and put the result in self._decoded_chars. */
1433-
chunk_size = PyLong_FromSsize_t(self->chunk_size);
1433+
if (size_hint > 0) {
1434+
size_hint = Py_MAX(self->b2cratio, 1.0) * size_hint;
1435+
}
1436+
chunk_size = PyLong_FromSsize_t(Py_MAX(self->chunk_size, size_hint));
14341437
if (chunk_size == NULL)
14351438
goto fail;
14361439
input_chunk = PyObject_CallMethodObjArgs(self->buffer,
@@ -1553,7 +1556,7 @@ textiowrapper_read(textio *self, PyObject *args)
15531556

15541557
/* Keep reading chunks until we have n characters to return */
15551558
while (remaining > 0) {
1556-
res = textiowrapper_read_chunk(self);
1559+
res = textiowrapper_read_chunk(self, remaining);
15571560
if (res < 0)
15581561
goto fail;
15591562
if (res == 0) /* EOF */
@@ -1563,7 +1566,8 @@ textiowrapper_read(textio *self, PyObject *args)
15631566
if (chunks == NULL)
15641567
goto fail;
15651568
}
1566-
if (PyList_Append(chunks, result) < 0)
1569+
if (PyUnicode_GET_LENGTH(result) > 0 &&
1570+
PyList_Append(chunks, result) < 0)
15671571
goto fail;
15681572
Py_DECREF(result);
15691573
result = textiowrapper_get_decoded_chars(self, remaining);
@@ -1720,7 +1724,7 @@ _textiowrapper_readline(textio *self, Py_ssize_t limit)
17201724
res = 1;
17211725
while (!self->decoded_chars ||
17221726
!PyUnicode_GET_LENGTH(self->decoded_chars)) {
1723-
res = textiowrapper_read_chunk(self);
1727+
res = textiowrapper_read_chunk(self, 0);
17241728
if (res < 0)
17251729
goto error;
17261730
if (res == 0)

0 commit comments

Comments
 (0)