@@ -603,28 +603,27 @@ PyBytes_Repr(PyObject *obj, int smartquotes)
603603 newsize = 3 ; /* b'' */
604604 s = (unsigned char * )op -> ob_sval ;
605605 for (i = 0 ; i < length ; i ++ ) {
606+ Py_ssize_t incr = 1 ;
606607 switch (s [i ]) {
607- case '\'' : squotes ++ ; newsize ++ ; break ;
608- case '"' : dquotes ++ ; newsize ++ ; break ;
608+ case '\'' : squotes ++ ; break ;
609+ case '"' : dquotes ++ ; break ;
609610 case '\\' : case '\t' : case '\n' : case '\r' :
610- newsize + = 2 ; break ; /* \C */
611+ incr = 2 ; break ; /* \C */
611612 default :
612613 if (s [i ] < ' ' || s [i ] >= 0x7f )
613- newsize += 4 ; /* \xHH */
614- else
615- newsize ++ ;
614+ incr = 4 ; /* \xHH */
616615 }
616+ if (newsize > PY_SSIZE_T_MAX - incr )
617+ goto overflow ;
618+ newsize += incr ;
617619 }
618620 quote = '\'' ;
619621 if (smartquotes && squotes && !dquotes )
620622 quote = '"' ;
621- if (squotes && quote == '\'' )
623+ if (squotes && quote == '\'' ) {
624+ if (newsize > PY_SSIZE_T_MAX - squotes )
625+ goto overflow ;
622626 newsize += squotes ;
623-
624- if (newsize > (PY_SSIZE_T_MAX - sizeof (PyUnicodeObject ) - 1 )) {
625- PyErr_SetString (PyExc_OverflowError ,
626- "bytes object is too large to make repr" );
627- return NULL ;
628627 }
629628
630629 v = PyUnicode_New (newsize , 127 );
@@ -656,6 +655,11 @@ PyBytes_Repr(PyObject *obj, int smartquotes)
656655 * p ++ = quote ;
657656 assert (_PyUnicode_CheckConsistency (v , 1 ));
658657 return v ;
658+
659+ overflow :
660+ PyErr_SetString (PyExc_OverflowError ,
661+ "bytes object is too large to make repr" );
662+ return NULL ;
659663}
660664
661665static PyObject *
0 commit comments