Skip to content

Commit 52f70da

Browse files
authored
gh-125196: Use PyUnicodeWriter for repr(list) (#125202)
Replace the private _PyUnicodeWriter with the public PyUnicodeWriter. Replace PyObject_Repr() + _PyUnicodeWriter_WriteStr() with PyUnicodeWriter_WriteRepr().
1 parent 7d2c397 commit 52f70da

File tree

1 file changed

+23
-22
lines changed

1 file changed

+23
-22
lines changed

Objects/listobject.c

+23-22
Original file line numberDiff line numberDiff line change
@@ -522,49 +522,50 @@ list_dealloc(PyObject *self)
522522
static PyObject *
523523
list_repr_impl(PyListObject *v)
524524
{
525-
PyObject *s;
526-
_PyUnicodeWriter writer;
527-
Py_ssize_t i = Py_ReprEnter((PyObject*)v);
528-
if (i != 0) {
529-
return i > 0 ? PyUnicode_FromString("[...]") : NULL;
525+
int res = Py_ReprEnter((PyObject*)v);
526+
if (res != 0) {
527+
return (res > 0 ? PyUnicode_FromString("[...]") : NULL);
530528
}
531529

532-
_PyUnicodeWriter_Init(&writer);
533-
writer.overallocate = 1;
534530
/* "[" + "1" + ", 2" * (len - 1) + "]" */
535-
writer.min_length = 1 + 1 + (2 + 1) * (Py_SIZE(v) - 1) + 1;
531+
Py_ssize_t prealloc = 1 + 1 + (2 + 1) * (Py_SIZE(v) - 1) + 1;
532+
PyUnicodeWriter *writer = PyUnicodeWriter_Create(prealloc);
533+
if (writer == NULL) {
534+
goto error;
535+
}
536536

537-
if (_PyUnicodeWriter_WriteChar(&writer, '[') < 0)
537+
if (PyUnicodeWriter_WriteChar(writer, '[') < 0) {
538538
goto error;
539+
}
539540

540541
/* Do repr() on each element. Note that this may mutate the list,
541542
so must refetch the list size on each iteration. */
542-
for (i = 0; i < Py_SIZE(v); ++i) {
543+
for (Py_ssize_t i = 0; i < Py_SIZE(v); ++i) {
543544
if (i > 0) {
544-
if (_PyUnicodeWriter_WriteASCIIString(&writer, ", ", 2) < 0)
545+
if (PyUnicodeWriter_WriteChar(writer, ',') < 0) {
546+
goto error;
547+
}
548+
if (PyUnicodeWriter_WriteChar(writer, ' ') < 0) {
545549
goto error;
550+
}
546551
}
547552

548-
s = PyObject_Repr(v->ob_item[i]);
549-
if (s == NULL)
550-
goto error;
551-
552-
if (_PyUnicodeWriter_WriteStr(&writer, s) < 0) {
553-
Py_DECREF(s);
553+
if (PyUnicodeWriter_WriteRepr(writer, v->ob_item[i]) < 0) {
554554
goto error;
555555
}
556-
Py_DECREF(s);
557556
}
558557

559-
writer.overallocate = 0;
560-
if (_PyUnicodeWriter_WriteChar(&writer, ']') < 0)
558+
if (PyUnicodeWriter_WriteChar(writer, ']') < 0) {
561559
goto error;
560+
}
562561

563562
Py_ReprLeave((PyObject *)v);
564-
return _PyUnicodeWriter_Finish(&writer);
563+
return PyUnicodeWriter_Finish(writer);
565564

566565
error:
567-
_PyUnicodeWriter_Dealloc(&writer);
566+
if (writer != NULL) {
567+
PyUnicodeWriter_Discard(writer);
568+
}
568569
Py_ReprLeave((PyObject *)v);
569570
return NULL;
570571
}

0 commit comments

Comments
 (0)