@@ -7141,41 +7141,34 @@ PyUnicode_DecodeRawUnicodeEscape(const char *s,
7141
7141
PyObject *
7142
7142
PyUnicode_AsRawUnicodeEscapeString (PyObject * unicode )
7143
7143
{
7144
- PyObject * repr ;
7145
- char * p ;
7146
- Py_ssize_t expandsize , pos ;
7147
- int kind ;
7148
- const void * data ;
7149
- Py_ssize_t len ;
7150
-
7151
7144
if (!PyUnicode_Check (unicode )) {
7152
7145
PyErr_BadArgument ();
7153
7146
return NULL ;
7154
7147
}
7155
- kind = PyUnicode_KIND (unicode );
7156
- data = PyUnicode_DATA (unicode );
7157
- len = PyUnicode_GET_LENGTH (unicode );
7148
+ int kind = PyUnicode_KIND (unicode );
7149
+ const void * data = PyUnicode_DATA (unicode );
7150
+ Py_ssize_t len = PyUnicode_GET_LENGTH (unicode );
7151
+ if (len == 0 ) {
7152
+ return Py_GetConstant (Py_CONSTANT_EMPTY_BYTES );
7153
+ }
7158
7154
if (kind == PyUnicode_1BYTE_KIND ) {
7159
7155
return PyBytes_FromStringAndSize (data , len );
7160
7156
}
7161
7157
7162
7158
/* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
7163
7159
bytes, and 1 byte characters 4. */
7164
- expandsize = kind * 2 + 2 ;
7165
-
7160
+ Py_ssize_t expandsize = kind * 2 + 2 ;
7166
7161
if (len > PY_SSIZE_T_MAX / expandsize ) {
7167
7162
return PyErr_NoMemory ();
7168
7163
}
7169
- repr = PyBytes_FromStringAndSize (NULL , expandsize * len );
7170
- if (repr == NULL ) {
7164
+
7165
+ PyBytesWriter * writer = PyBytesWriter_Create (expandsize * len );
7166
+ if (writer == NULL ) {
7171
7167
return NULL ;
7172
7168
}
7173
- if (len == 0 ) {
7174
- return repr ;
7175
- }
7169
+ char * p = PyBytesWriter_GetData (writer );
7176
7170
7177
- p = PyBytes_AS_STRING (repr );
7178
- for (pos = 0 ; pos < len ; pos ++ ) {
7171
+ for (Py_ssize_t pos = 0 ; pos < len ; pos ++ ) {
7179
7172
Py_UCS4 ch = PyUnicode_READ (kind , data , pos );
7180
7173
7181
7174
/* U+0000-U+00ff range: Copy 8-bit characters as-is */
@@ -7207,11 +7200,7 @@ PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
7207
7200
}
7208
7201
}
7209
7202
7210
- assert (p > PyBytes_AS_STRING (repr ));
7211
- if (_PyBytes_Resize (& repr , p - PyBytes_AS_STRING (repr )) < 0 ) {
7212
- return NULL ;
7213
- }
7214
- return repr ;
7203
+ return PyBytesWriter_FinishWithPointer (writer , p );
7215
7204
}
7216
7205
7217
7206
/* --- Latin-1 Codec ------------------------------------------------------ */
0 commit comments