@@ -338,9 +338,9 @@ static PyObject *
338338list_repr (PyListObject * v )
339339{
340340 Py_ssize_t i ;
341- PyObject * s = NULL ;
342- _PyAccu acc ;
341+ PyObject * s ;
343342 static PyObject * sep = NULL ;
343+ _PyUnicodeWriter writer ;
344344
345345 if (Py_SIZE (v ) == 0 ) {
346346 return PyUnicode_FromString ("[]" );
@@ -357,38 +357,50 @@ list_repr(PyListObject *v)
357357 return i > 0 ? PyUnicode_FromString ("[...]" ) : NULL ;
358358 }
359359
360- if (_PyAccu_Init (& acc ))
361- goto error ;
360+ _PyUnicodeWriter_Init (& writer );
361+ writer .overallocate = 1 ;
362+ if (Py_SIZE (v ) > 1 ) {
363+ /* "[" + "1" + ", 2" * (len - 1) + "]" */
364+ writer .min_length = 1 + 1 + (2 + 1 ) * (Py_SIZE (v ) - 1 ) + 1 ;
365+ }
366+ else {
367+ /* "[1]" */
368+ writer .min_length = 3 ;
369+ }
362370
363- s = PyUnicode_FromString ("[" );
364- if (s == NULL || _PyAccu_Accumulate (& acc , s ))
371+ if (_PyUnicodeWriter_WriteChar (& writer , '[' ) < 0 )
365372 goto error ;
366- Py_CLEAR (s );
367373
368374 /* Do repr() on each element. Note that this may mutate the list,
369375 so must refetch the list size on each iteration. */
370376 for (i = 0 ; i < Py_SIZE (v ); ++ i ) {
377+ if (i > 0 ) {
378+ if (_PyUnicodeWriter_WriteStr (& writer , sep ) < 0 )
379+ goto error ;
380+ }
381+
371382 if (Py_EnterRecursiveCall (" while getting the repr of a list" ))
372383 goto error ;
373384 s = PyObject_Repr (v -> ob_item [i ]);
374385 Py_LeaveRecursiveCall ();
375- if (i > 0 && _PyAccu_Accumulate ( & acc , sep ) )
386+ if (s == NULL )
376387 goto error ;
377- if (s == NULL || _PyAccu_Accumulate (& acc , s ))
388+
389+ if (_PyUnicodeWriter_WriteStr (& writer , s ) < 0 ) {
390+ Py_DECREF (s );
378391 goto error ;
379- Py_CLEAR (s );
392+ }
393+ Py_DECREF (s );
380394 }
381- s = PyUnicode_FromString ( "]" );
382- if (s == NULL || _PyAccu_Accumulate ( & acc , s ) )
395+
396+ if (_PyUnicodeWriter_WriteChar ( & writer , ']' ) < 0 )
383397 goto error ;
384- Py_CLEAR (s );
385398
386399 Py_ReprLeave ((PyObject * )v );
387- return _PyAccu_Finish ( & acc );
400+ return _PyUnicodeWriter_Finish ( & writer );
388401
389402error :
390- _PyAccu_Destroy (& acc );
391- Py_XDECREF (s );
403+ _PyUnicodeWriter_Dealloc (& writer );
392404 Py_ReprLeave ((PyObject * )v );
393405 return NULL ;
394406}
0 commit comments