https://github.com/python/cpython/commit/0f34848214e4c1987c5b0c4f8ef63e9efab96ccb
commit: 0f34848214e4c1987c5b0c4f8ef63e9efab96ccb
branch: main
author: Victor Stinner <[email protected]>
committer: vstinner <[email protected]>
date: 2026-09-01T15:29:26+02:00
summary:
gh-155742: Use PyBytesWriter in codecs (#155750)
Use PyBytesWriter in _PyCodec_SurrogateEscapeUnicodeEncodeError().
Replace soft deprecated PyBytes_FromStringAndSize() with
PyBytesWriter.
files:
M Python/codecs.c
diff --git a/Python/codecs.c b/Python/codecs.c
index 6d1ae651fa0005..84a0589c8e8317 100644
--- a/Python/codecs.c
+++ b/Python/codecs.c
@@ -1426,19 +1426,19 @@ _PyCodec_SurrogateEscapeUnicodeEncodeError(PyObject
*exc)
return NULL;
}
- PyObject *res = PyBytes_FromStringAndSize(NULL, slen);
- if (res == NULL) {
+ PyBytesWriter *writer = PyBytesWriter_Create(slen);
+ if (writer == NULL) {
Py_DECREF(obj);
return NULL;
}
- char *outp = PyBytes_AsString(res);
+ char *outp = PyBytesWriter_GetData(writer);
for (Py_ssize_t i = start; i < end; i++) {
Py_UCS4 ch = PyUnicode_READ_CHAR(obj, i);
if (ch < 0xdc80 || ch > 0xdcff) {
/* Not a UTF-8b surrogate, fail with original exception. */
Py_DECREF(obj);
- Py_DECREF(res);
+ PyBytesWriter_Discard(writer);
PyErr_SetObject(PyExceptionInstance_Class(exc), exc);
return NULL;
}
@@ -1446,6 +1446,8 @@ _PyCodec_SurrogateEscapeUnicodeEncodeError(PyObject *exc)
}
Py_DECREF(obj);
+ PyObject *res = PyBytesWriter_Finish(writer);
+ // Py_BuildValue() propagates the exception if res is NULL
return Py_BuildValue("(Nn)", res, end);
}
_______________________________________________
Python-checkins mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3//lists/python-checkins.python.org
Member address: [email protected]