@@ -586,8 +586,6 @@ _PyUnicodeWriter_WriteLatin1String(_PyUnicodeWriter *writer,
586586PyObject *
587587_PyUnicodeWriter_Finish (_PyUnicodeWriter * writer )
588588{
589- PyObject * str ;
590-
591589#ifdef Py_DEBUG
592590 // Check for buffer overflow
593591 if (writer -> buffer != NULL ) {
@@ -602,23 +600,28 @@ _PyUnicodeWriter_Finish(_PyUnicodeWriter *writer)
602600 }
603601#endif
604602
605- if (writer -> pos == 0 ) {
606- Py_CLEAR (writer -> buffer );
607- return _PyUnicode_GetEmpty ();
608- }
609-
610- str = writer -> buffer ;
603+ PyObject * str = writer -> buffer ;
611604 writer -> buffer = NULL ;
612605
613- if (writer -> readonly ) {
614- assert (PyUnicode_GET_LENGTH (str ) == writer -> pos );
615- assert (_PyUnicode_CheckConsistency (str , 1 ));
616- return str ;
606+ Py_ssize_t final_size = writer -> pos ;
607+ if (final_size == 0 ) {
608+ PyObject * empty = _PyUnicode_GetEmpty ();
609+ Py_XDECREF (str ); // writer->buffer can be NULL if the position is 0
610+ return empty ;
617611 }
618612
619- if (PyUnicode_GET_LENGTH (str ) != writer -> pos ) {
620- PyObject * str2 ;
621- str2 = _PyUnicode_ResizeCompact (str , writer -> pos );
613+ Py_ssize_t length = PyUnicode_GET_LENGTH (str );
614+ if (final_size == 1 && PyUnicode_KIND (str ) == PyUnicode_1BYTE_KIND ) {
615+ assert (length >= 1 );
616+ const Py_UCS1 * data = PyUnicode_1BYTE_DATA (str );
617+ Py_UCS1 ch = data [0 ];
618+ PyObject * latin1_char = _Py_LATIN1_CHR (ch );
619+ Py_DECREF (str );
620+ return latin1_char ;
621+ }
622+
623+ if (!writer -> readonly && length != final_size ) {
624+ PyObject * str2 = _PyUnicode_ResizeCompact (str , final_size );
622625 if (str2 == NULL ) {
623626 Py_DECREF (str );
624627 return NULL ;
@@ -627,7 +630,7 @@ _PyUnicodeWriter_Finish(_PyUnicodeWriter *writer)
627630 }
628631
629632 assert (_PyUnicode_CheckConsistency (str , 1 ));
630- return _PyUnicode_Result ( str ) ;
633+ return str ;
631634}
632635
633636
0 commit comments