@@ -2101,15 +2101,25 @@ diff_to_bool(int diff, int op)
21012101/* Convert a timedelta to a number of us,
21022102 * (24*3600*self.days + self.seconds)*1000000 + self.microseconds
21032103 * as a Python int.
2104- * Doing mixed-radix arithmetic by hand instead is excruciating in C,
2105- * due to ubiquitous overflow possibilities.
2104+ * The number of whole seconds always fits in int64_t, and so does the
2105+ * number of microseconds unless the delta is very large, so compute it
2106+ * in C when possible and fall back to Python int arithmetic otherwise.
2107+ * One second is reserved at the limit so that adding the microseconds
2108+ * field cannot overflow.
21062109 */
21072110static PyObject *
21082111delta_to_microseconds (PyDateTime_Delta * self )
21092112{
2113+ const int64_t max_seconds = INT64_MAX / 1000000 - 1 ;
2114+ int64_t seconds = (int64_t )GET_TD_DAYS (self ) * (24 * 3600 )
2115+ + GET_TD_SECONDS (self );
2116+ if (- max_seconds <= seconds && seconds <= max_seconds ) {
2117+ return PyLong_FromInt64 (seconds * 1000000
2118+ + GET_TD_MICROSECONDS (self ));
2119+ }
2120+
21102121 PyObject * x1 = NULL ;
21112122 PyObject * x2 = NULL ;
2112- PyObject * x3 = NULL ;
21132123 PyObject * result = NULL ;
21142124
21152125 PyObject * current_mod ;
@@ -2118,42 +2128,23 @@ delta_to_microseconds(PyDateTime_Delta *self)
21182128 return NULL ;
21192129 }
21202130
2121- x1 = PyLong_FromLong ( GET_TD_DAYS ( self ));
2131+ x1 = PyLong_FromInt64 ( seconds ); /* days and seconds in seconds */
21222132 if (x1 == NULL )
21232133 goto Done ;
2124- x2 = PyNumber_Multiply (x1 , CONST_SEC_PER_DAY (st )); /* days in seconds */
2134+ x2 = PyNumber_Multiply (x1 , CONST_US_PER_SECOND (st )); /* us */
21252135 if (x2 == NULL )
21262136 goto Done ;
2127- Py_SETREF (x1 , NULL );
21282137
2129- /* x2 has days in seconds */
2130- x1 = PyLong_FromLong (GET_TD_SECONDS (self )); /* seconds */
2138+ /* x2 has days+seconds in us */
2139+ Py_SETREF ( x1 , PyLong_FromLong (GET_TD_MICROSECONDS (self )));
21312140 if (x1 == NULL )
21322141 goto Done ;
2133- x3 = PyNumber_Add (x1 , x2 ); /* days and seconds in seconds */
2134- if (x3 == NULL )
2135- goto Done ;
2136- Py_DECREF (x1 );
2137- Py_DECREF (x2 );
2138- /* x1 = */ x2 = NULL ;
2139-
2140- /* x3 has days+seconds in seconds */
2141- x1 = PyNumber_Multiply (x3 , CONST_US_PER_SECOND (st )); /* us */
2142- if (x1 == NULL )
2143- goto Done ;
2144- Py_SETREF (x3 , NULL );
2145-
2146- /* x1 has days+seconds in us */
2147- x2 = PyLong_FromLong (GET_TD_MICROSECONDS (self ));
2148- if (x2 == NULL )
2149- goto Done ;
2150- result = PyNumber_Add (x1 , x2 );
2142+ result = PyNumber_Add (x2 , x1 );
21512143 assert (result == NULL || PyLong_CheckExact (result ));
21522144
21532145Done :
21542146 Py_XDECREF (x1 );
21552147 Py_XDECREF (x2 );
2156- Py_XDECREF (x3 );
21572148 RELEASE_CURRENT_STATE (st , current_mod );
21582149 return result ;
21592150}
0 commit comments