gh-125196: Use PyUnicodeWriter in symtable.c (#125199) · python/cpython@9bda775

GitHub

Original file line numberDiff line numberDiff line change@@ -3120,33 +3120,30 @@ _Py_Mangle(PyObject *privateobj, PyObject *ident)

31203120if (ipriv==plen) {

31213121returnPy_NewRef(ident); /* Don't mangle if class is just underscores */

31223122 }

3123-plen-=ipriv;

312431233125-if (plen+nlen >= PY_SSIZE_T_MAX-1) {

3124+if (nlen+(plen-ipriv) >= PY_SSIZE_T_MAX-1) {

31263125PyErr_SetString(PyExc_OverflowError,

31273126"private identifier too large to be mangled");

31283127returnNULL;

31293128 }

313031293131-Py_UCS4maxchar=PyUnicode_MAX_CHAR_VALUE(ident);

3132-if (PyUnicode_MAX_CHAR_VALUE(privateobj) >maxchar) {

3133-maxchar=PyUnicode_MAX_CHAR_VALUE(privateobj);

3134- }

3135-3136-PyObject*result=PyUnicode_New(1+nlen+plen, maxchar);

3137-if (!result) {

3130+PyUnicodeWriter*writer=PyUnicodeWriter_Create(1+nlen+ (plen-ipriv));

3131+if (!writer) {

31383132returnNULL;

31393133 }

3140-/* ident = "_" + priv[ipriv:] + ident # i.e. 1+plen+nlen bytes */

3141-PyUnicode_WRITE(PyUnicode_KIND(result), PyUnicode_DATA(result), 0, '_');

3142-if (PyUnicode_CopyCharacters(result, 1, privateobj, ipriv, plen) <0) {

3143-Py_DECREF(result);

3144-returnNULL;

3134+// ident = "_" + priv[ipriv:] + ident

3135+if (PyUnicodeWriter_WriteChar(writer, '_') <0) {

3136+ goto error;

31453137 }

3146-if (PyUnicode_CopyCharacters(result, plen+1, ident, 0, nlen) <0) {

3147-Py_DECREF(result);

3148-returnNULL;

3138+if (PyUnicodeWriter_WriteSubstring(writer, privateobj, ipriv, plen) <0) {

3139+ goto error;

31493140 }

3150-assert(_PyUnicode_CheckConsistency(result, 1));

3151-returnresult;

3141+if (PyUnicodeWriter_WriteStr(writer, ident) <0) {

3142+ goto error;

3143+ }

3144+returnPyUnicodeWriter_Finish(writer);

3145+3146+error:

3147+PyUnicodeWriter_Discard(writer);

3148+returnNULL;

31523149}