@@ -15,7 +15,7 @@ stringlib_expandtabs(PyObject *self, PyObject *args, PyObject *kwds)
1515{
1616 const char * e , * p ;
1717 char * q ;
18- size_t i , j ;
18+ Py_ssize_t i , j ;
1919 PyObject * u ;
2020 static char * kwlist [] = {"tabsize" , 0 };
2121 int tabsize = 8 ;
@@ -27,44 +27,40 @@ stringlib_expandtabs(PyObject *self, PyObject *args, PyObject *kwds)
2727 /* First pass: determine size of output string */
2828 i = j = 0 ;
2929 e = STRINGLIB_STR (self ) + STRINGLIB_LEN (self );
30- for (p = STRINGLIB_STR (self ); p < e ; p ++ )
30+ for (p = STRINGLIB_STR (self ); p < e ; p ++ ) {
3131 if (* p == '\t' ) {
3232 if (tabsize > 0 ) {
33- j += tabsize - (j % tabsize );
34- if (j > PY_SSIZE_T_MAX ) {
35- PyErr_SetString (PyExc_OverflowError ,
36- "result is too long" );
37- return NULL ;
38- }
33+ Py_ssize_t incr = tabsize - (j % tabsize );
34+ if (j > PY_SSIZE_T_MAX - incr )
35+ goto overflow ;
36+ j += incr ;
3937 }
4038 }
4139 else {
40+ if (j > PY_SSIZE_T_MAX - 1 )
41+ goto overflow ;
4242 j ++ ;
4343 if (* p == '\n' || * p == '\r' ) {
44+ if (i > PY_SSIZE_T_MAX - j )
45+ goto overflow ;
4446 i += j ;
4547 j = 0 ;
46- if (i > PY_SSIZE_T_MAX ) {
47- PyErr_SetString (PyExc_OverflowError ,
48- "result is too long" );
49- return NULL ;
50- }
5148 }
5249 }
53-
54- if ((i + j ) > PY_SSIZE_T_MAX ) {
55- PyErr_SetString (PyExc_OverflowError , "result is too long" );
56- return NULL ;
5750 }
5851
52+ if (i > PY_SSIZE_T_MAX - j )
53+ goto overflow ;
54+
5955 /* Second pass: create output string and fill it */
6056 u = STRINGLIB_NEW (NULL , i + j );
6157 if (!u )
6258 return NULL ;
6359
6460 j = 0 ;
6561 q = STRINGLIB_STR (u );
66-
67- for (p = STRINGLIB_STR (self ); p < e ; p ++ )
62+
63+ for (p = STRINGLIB_STR (self ); p < e ; p ++ ) {
6864 if (* p == '\t' ) {
6965 if (tabsize > 0 ) {
7066 i = tabsize - (j % tabsize );
@@ -79,8 +75,12 @@ stringlib_expandtabs(PyObject *self, PyObject *args, PyObject *kwds)
7975 if (* p == '\n' || * p == '\r' )
8076 j = 0 ;
8177 }
78+ }
8279
8380 return u ;
81+ overflow :
82+ PyErr_SetString (PyExc_OverflowError , "result too long" );
83+ return NULL ;
8484}
8585
8686Py_LOCAL_INLINE (PyObject * )
0 commit comments