@@ -255,20 +255,12 @@ static PyObject *
255255tuplerepr (PyTupleObject * v )
256256{
257257 Py_ssize_t i , n ;
258- PyObject * s = NULL ;
259- _PyAccu acc ;
260- static PyObject * sep = NULL ;
258+ _PyUnicodeWriter writer ;
261259
262260 n = Py_SIZE (v );
263261 if (n == 0 )
264262 return PyUnicode_FromString ("()" );
265263
266- if (sep == NULL ) {
267- sep = PyUnicode_FromString (", " );
268- if (sep == NULL )
269- return NULL ;
270- }
271-
272264 /* While not mutable, it is still possible to end up with a cycle in a
273265 tuple through an object that stores itself within a tuple (and thus
274266 infinitely asks for the repr of itself). This should only be
@@ -278,40 +270,58 @@ tuplerepr(PyTupleObject *v)
278270 return i > 0 ? PyUnicode_FromString ("(...)" ) : NULL ;
279271 }
280272
281- if (_PyAccu_Init (& acc ))
282- goto error ;
273+ _PyUnicodeWriter_Init (& writer );
274+ writer .overallocate = 1 ;
275+ if (Py_SIZE (v ) > 1 ) {
276+ /* "(" + "1" + ", 2" * (len - 1) + ")" */
277+ writer .min_length = 1 + 1 + (2 + 1 ) * (Py_SIZE (v ) - 1 ) + 1 ;
278+ }
279+ else {
280+ /* "(1,)" */
281+ writer .min_length = 4 ;
282+ }
283283
284- s = PyUnicode_FromString ("(" );
285- if (s == NULL || _PyAccu_Accumulate (& acc , s ))
284+ if (_PyUnicodeWriter_WriteChar (& writer , '(' ) < 0 )
286285 goto error ;
287- Py_CLEAR (s );
288286
289287 /* Do repr() on each element. */
290288 for (i = 0 ; i < n ; ++ i ) {
289+ PyObject * s ;
290+
291+ if (i > 0 ) {
292+ if (_PyUnicodeWriter_WriteASCIIString (& writer , ", " , 2 ) < 0 )
293+ goto error ;
294+ }
295+
291296 if (Py_EnterRecursiveCall (" while getting the repr of a tuple" ))
292297 goto error ;
293298 s = PyObject_Repr (v -> ob_item [i ]);
294299 Py_LeaveRecursiveCall ();
295- if (i > 0 && _PyAccu_Accumulate ( & acc , sep ) )
300+ if (s == NULL )
296301 goto error ;
297- if (s == NULL || _PyAccu_Accumulate (& acc , s ))
302+
303+ if (_PyUnicodeWriter_WriteStr (& writer , s ) < 0 ) {
304+ Py_DECREF (s );
305+ goto error ;
306+ }
307+ Py_DECREF (s );
308+ }
309+
310+ writer .overallocate = 0 ;
311+ if (n > 1 ) {
312+ if (_PyUnicodeWriter_WriteChar (& writer , ')' ) < 0 )
313+ goto error ;
314+ }
315+ else {
316+ if (_PyUnicodeWriter_WriteASCIIString (& writer , ",)" , 2 ) < 0 )
298317 goto error ;
299- Py_CLEAR (s );
300318 }
301- if (n > 1 )
302- s = PyUnicode_FromString (")" );
303- else
304- s = PyUnicode_FromString (",)" );
305- if (s == NULL || _PyAccu_Accumulate (& acc , s ))
306- goto error ;
307- Py_CLEAR (s );
308319
309320 Py_ReprLeave ((PyObject * )v );
310- return _PyAccu_Finish ( & acc );
321+ return _PyUnicodeWriter_Finish ( & writer );
311322
312323error :
313- _PyAccu_Destroy (& acc );
314- Py_XDECREF (s );
324+ _PyUnicodeWriter_Dealloc (& writer );
315325 Py_ReprLeave ((PyObject * )v );
316326 return NULL ;
317327}
0 commit comments