File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -1415,13 +1415,34 @@ builtin_range(self, args)
14151415 PyErr_SetString (PyExc_ValueError , "zero step for range()" );
14161416 return NULL ;
14171417 }
1418- /* XXX ought to check overflow of subtraction */
1419- if (istep > 0 )
1420- n = (ihigh - ilow + istep - 1 ) / istep ;
1421- else
1422- n = (ihigh - ilow + istep + 1 ) / istep ;
1423- if (n < 0 )
1424- n = 0 ;
1418+ /* A bit convoluted because this might overflow; due to Tim Peters */
1419+ if (istep > 0 ) {
1420+ if (ihigh <= ilow )
1421+ n = 0 ;
1422+ else {
1423+ unsigned long hi = (unsigned long )ihigh ;
1424+ unsigned long lo = (unsigned long )ilow ;
1425+ unsigned long diff = hi - lo - 1 ;
1426+ n = (long )(diff / istep + 1 );
1427+ }
1428+ }
1429+ else {
1430+ /* But any errors in this branch are my own --Guido */
1431+ if (ihigh >= ilow )
1432+ n = 0 ;
1433+ else {
1434+ /* Swap lo and hi; use abs(istep) */
1435+ unsigned long hi = (unsigned long )ilow ;
1436+ unsigned long lo = (unsigned long )ihigh ;
1437+ unsigned long diff = hi - lo - 1 ;
1438+ n = (long )(diff / (- istep ) + 1 );
1439+ }
1440+ }
1441+ if (n < 0 ) {
1442+ PyErr_SetString (PyExc_OverflowError ,
1443+ "range() has more than sys.maxint items" );
1444+ return NULL ;
1445+ }
14251446 v = PyList_New (n );
14261447 if (v == NULL )
14271448 return NULL ;
You can’t perform that action at this time.
0 commit comments