Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion Lib/_pyio.py
Original file line number Diff line number Diff line change
Expand Up @@ -2308,7 +2308,16 @@ def write(self, s):
encoder = self._encoder or self._get_encoder()
# XXX What if we were just reading?
b = encoder.encode(s)
self.buffer.write(b)
while True:
n = self.buffer.write(b)
if n is None:
# Some legacy writers return None after writing all the data.
break
if n < 0 or n > len(b) or (n == 0 and b):
raise OSError("write() returned incorrect number of bytes")
b = b[n:]
if not b:
break
if self._line_buffering and (haslf or "\r" in s):
self.flush()
if self._snapshot is not None:
Expand Down
27 changes: 27 additions & 0 deletions Lib/test/test_io/test_textio.py
Original file line number Diff line number Diff line change
Expand Up @@ -1022,6 +1022,33 @@ def test_rawio_write_through(self):
txt.write('5')
self.assertEqual(b''.join(raw._write_stack), b'123\n45')

def test_rawio_short_write(self):
class ShortWriter(self.MockRawIO):
def write(self, b):
return super().write(b[:2])

raw = ShortWriter()
with self.TextIOWrapper(raw, encoding='utf-8', write_through=True) as txt:
self.assertEqual(txt.write('a\u20acb'), 3)
self.assertEqual(b''.join(raw._write_stack), b'a\xe2\x82\xacb')

def test_rawio_write_none(self):
raw = self.MockRawIO()
raw.write = raw._write_stack.append
with self.TextIOWrapper(raw, encoding='ascii', write_through=True) as txt:
self.assertEqual(txt.write('abc'), 3)
self.assertEqual(raw._write_stack, [b'abc'])

def test_rawio_write_invalid_result(self):
for result, error in ((0, OSError), (-1, OSError), (4, OSError),
('1', TypeError), (1.5, TypeError)):
with self.subTest(result=result):
raw = self.MockRawIO()
raw.write = lambda b: result
with self.TextIOWrapper(raw, encoding='ascii',
write_through=True) as txt:
self.assertRaises(error, txt.write, 'abc')

def test_bufio_write_through(self):
# Issue #21396: write_through=True doesn't force a flush()
# on the underlying binary buffered object.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Fix :class:`io.TextIOWrapper` silently losing data when the underlying
binary stream only writes part of the data.
47 changes: 39 additions & 8 deletions Modules/_io/textio.c
Original file line number Diff line number Diff line change
Expand Up @@ -1726,17 +1726,48 @@ _textiowrapper_writeflush(textio *self)
self->pending_bytes = NULL;
Py_DECREF(pending);

PyObject *ret;
do {
ret = buffer_callmethod_onearg(self, &_Py_ID(write), b);
} while (ret == NULL && _PyIO_trap_eintr());
while (1) {
PyObject *ret;
do {
ret = buffer_callmethod_onearg(self, &_Py_ID(write), b);
} while (ret == NULL && _PyIO_trap_eintr());
if (ret == NULL) {
goto error;
}
if (ret == Py_None) {
/* Some legacy writers return None after writing all the data. */
Py_DECREF(ret);
break;
}
Py_ssize_t n = PyNumber_AsSsize_t(ret, PyExc_OverflowError);
Py_DECREF(ret);
if (n == -1 && PyErr_Occurred()) {
goto error;
}
Py_ssize_t len = PyBytes_GET_SIZE(b);
if (n <= 0 || n > len) {
PyErr_SetString(PyExc_OSError,
"write() returned incorrect number of bytes");
goto error;
}
if (n == len) {
break;
}
PyObject *remaining = PyBytes_FromStringAndSize(
PyBytes_AS_STRING(b) + n, len - n);
if (remaining == NULL) {
goto error;
}
Py_SETREF(b, remaining);
}
Py_DECREF(b);
return 0;

error:
// NOTE: We cleared buffer but we don't know how many bytes are actually written
// when an error occurred.
if (ret == NULL)
return -1;
Py_DECREF(ret);
return 0;
Py_DECREF(b);
return -1;
}

/* Return borrowed Py_None on success, or NULL on error. */
Expand Down
Loading