From ad5003996e74d0f32b9babdd84b259481ca0807c Mon Sep 17 00:00:00 2001 From: Inada Naoki Date: Sat, 14 Mar 2020 12:44:25 +0900 Subject: [PATCH] Use _PyUnicode_GetUTF8Buffer() in fileobject.c --- Objects/fileobject.c | 18 +++++------------- 1 file changed, 5 insertions(+), 13 deletions(-) diff --git a/Objects/fileobject.c b/Objects/fileobject.c index 840d17bee66bae..4623fdb77e60aa 100644 --- a/Objects/fileobject.c +++ b/Objects/fileobject.c @@ -359,8 +359,6 @@ static PyObject * stdprinter_write(PyStdPrinter_Object *self, PyObject *args) { PyObject *unicode; - PyObject *bytes = NULL; - const char *str; Py_ssize_t n; int err; @@ -380,21 +378,15 @@ stdprinter_write(PyStdPrinter_Object *self, PyObject *args) } /* Encode Unicode to UTF-8/surrogateescape */ - str = PyUnicode_AsUTF8AndSize(unicode, &n); - if (str == NULL) { - PyErr_Clear(); - bytes = _PyUnicode_AsUTF8String(unicode, "backslashreplace"); - if (bytes == NULL) - return NULL; - str = PyBytes_AS_STRING(bytes); - n = PyBytes_GET_SIZE(bytes); + Py_buffer buf; + if (_PyUnicode_GetUTF8Buffer(unicode, "backslashreplace", &buf) < 0) { + return NULL; } - n = _Py_write(self->fd, str, n); + n = _Py_write(self->fd, buf.buf, buf.len); /* save errno, it can be modified indirectly by Py_XDECREF() */ err = errno; - - Py_XDECREF(bytes); + PyBuffer_Release(&buf); if (n == -1) { if (err == EAGAIN) {