@@ -3120,33 +3120,30 @@ _Py_Mangle(PyObject *privateobj, PyObject *ident)
31203120 if (ipriv == plen ) {
31213121 return Py_NewRef (ident ); /* Don't mangle if class is just underscores */
31223122 }
3123- plen -= ipriv ;
31243123
3125- if (plen + nlen >= PY_SSIZE_T_MAX - 1 ) {
3124+ if (nlen + ( plen - ipriv ) >= PY_SSIZE_T_MAX - 1 ) {
31263125 PyErr_SetString (PyExc_OverflowError ,
31273126 "private identifier too large to be mangled" );
31283127 return NULL ;
31293128 }
31303129
3131- Py_UCS4 maxchar = 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 ) {
31383132 return NULL ;
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- return NULL ;
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- return NULL ;
3138+ if (PyUnicodeWriter_WriteSubstring (writer , privateobj , ipriv , plen ) < 0 ) {
3139+ goto error ;
31493140 }
3150- assert (_PyUnicode_CheckConsistency (result , 1 ));
3151- return result ;
3141+ if (PyUnicodeWriter_WriteStr (writer , ident ) < 0 ) {
3142+ goto error ;
3143+ }
3144+ return PyUnicodeWriter_Finish (writer );
3145+
3146+ error :
3147+ PyUnicodeWriter_Discard (writer );
3148+ return NULL ;
31523149}
0 commit comments