Skip to content

Commit 82dfdc3

Browse files
authored
gh-125196: Use PyUnicodeWriter for repr(tuple) (#125242)
1 parent 1639d93 commit 82dfdc3

File tree

1 file changed

+24
-26
lines changed

1 file changed

+24
-26
lines changed

Objects/tupleobject.c

Lines changed: 24 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -232,56 +232,54 @@ tuple_repr(PyObject *self)
232232
return res > 0 ? PyUnicode_FromString("(...)") : NULL;
233233
}
234234

235-
_PyUnicodeWriter writer;
236-
_PyUnicodeWriter_Init(&writer);
237-
writer.overallocate = 1;
235+
Py_ssize_t prealloc;
238236
if (n > 1) {
239-
/* "(" + "1" + ", 2" * (len - 1) + ")" */
240-
writer.min_length = 1 + 1 + (2 + 1) * (n - 1) + 1;
237+
// "(" + "1" + ", 2" * (len - 1) + ")"
238+
prealloc = 1 + 1 + (2 + 1) * (n - 1) + 1;
241239
}
242240
else {
243-
/* "(1,)" */
244-
writer.min_length = 4;
241+
// "(1,)"
242+
prealloc = 4;
243+
}
244+
PyUnicodeWriter *writer = PyUnicodeWriter_Create(prealloc);
245+
if (writer == NULL) {
246+
goto error;
245247
}
246248

247-
if (_PyUnicodeWriter_WriteChar(&writer, '(') < 0)
249+
if (PyUnicodeWriter_WriteChar(writer, '(') < 0) {
248250
goto error;
251+
}
249252

250253
/* Do repr() on each element. */
251254
for (Py_ssize_t i = 0; i < n; ++i) {
252-
PyObject *s;
253-
254255
if (i > 0) {
255-
if (_PyUnicodeWriter_WriteASCIIString(&writer, ", ", 2) < 0)
256+
if (PyUnicodeWriter_WriteChar(writer, ',') < 0) {
256257
goto error;
258+
}
259+
if (PyUnicodeWriter_WriteChar(writer, ' ') < 0) {
260+
goto error;
261+
}
257262
}
258263

259-
s = PyObject_Repr(v->ob_item[i]);
260-
if (s == NULL)
261-
goto error;
262-
263-
if (_PyUnicodeWriter_WriteStr(&writer, s) < 0) {
264-
Py_DECREF(s);
264+
if (PyUnicodeWriter_WriteRepr(writer, v->ob_item[i]) < 0) {
265265
goto error;
266266
}
267-
Py_DECREF(s);
268267
}
269268

270-
writer.overallocate = 0;
271-
if (n > 1) {
272-
if (_PyUnicodeWriter_WriteChar(&writer, ')') < 0)
269+
if (n == 1) {
270+
if (PyUnicodeWriter_WriteChar(writer, ',') < 0) {
273271
goto error;
272+
}
274273
}
275-
else {
276-
if (_PyUnicodeWriter_WriteASCIIString(&writer, ",)", 2) < 0)
277-
goto error;
274+
if (PyUnicodeWriter_WriteChar(writer, ')') < 0) {
275+
goto error;
278276
}
279277

280278
Py_ReprLeave((PyObject *)v);
281-
return _PyUnicodeWriter_Finish(&writer);
279+
return PyUnicodeWriter_Finish(writer);
282280

283281
error:
284-
_PyUnicodeWriter_Dealloc(&writer);
282+
PyUnicodeWriter_Discard(writer);
285283
Py_ReprLeave((PyObject *)v);
286284
return NULL;
287285
}

0 commit comments

Comments
 (0)