diff --git a/Doc/whatsnew/3.16.rst b/Doc/whatsnew/3.16.rst index 336171ca041f906..394ba3a16a78d28 100644 --- a/Doc/whatsnew/3.16.rst +++ b/Doc/whatsnew/3.16.rst @@ -139,6 +139,13 @@ Other language changes :func:`asyncio.print_call_graph` can see through them into the awaited code. (Contributed by Kumar Aditya in :gh:`157361`.) +* Functions that take timestamp or timeout arguments + no longer convert numbers other than integers and floats + (such as :class:`~decimal.Decimal` and :class:`~fractions.Fraction`) + to :class:`float`. + They are converted exactly, which avoids the precision loss. + (Contributed by Serhiy Storchaka in :gh:`67795`.) + Default interactive shell ========================= diff --git a/Include/internal/pycore_global_objects_fini_generated.h b/Include/internal/pycore_global_objects_fini_generated.h index 8418722b622dc52..572fbe0a983c36c 100644 --- a/Include/internal/pycore_global_objects_fini_generated.h +++ b/Include/internal/pycore_global_objects_fini_generated.h @@ -424,6 +424,7 @@ _PyStaticObjects_CheckAll(PyInterpreterState *interp) { _PyStaticObject_CheckUnicodeSingleton((PyObject *)&_Py_ID(default), "default", 7); _PyStaticObject_CheckUnicodeSingleton((PyObject *)&_Py_ID(defaultaction), "defaultaction", 13); _PyStaticObject_CheckUnicodeSingleton((PyObject *)&_Py_ID(delete), "delete", 6); + _PyStaticObject_CheckUnicodeSingleton((PyObject *)&_Py_ID(denominator), "denominator", 11); _PyStaticObject_CheckUnicodeSingleton((PyObject *)&_Py_ID(depth), "depth", 5); _PyStaticObject_CheckUnicodeSingleton((PyObject *)&_Py_ID(desired_access), "desired_access", 14); _PyStaticObject_CheckUnicodeSingleton((PyObject *)&_Py_ID(detect_types), "detect_types", 12); @@ -692,6 +693,7 @@ _PyStaticObjects_CheckAll(PyInterpreterState *interp) { _PyStaticObject_CheckUnicodeSingleton((PyObject *)&_Py_ID(nt), "nt", 2); _PyStaticObject_CheckUnicodeSingleton((PyObject *)&_Py_ID(null), "null", 4); _PyStaticObject_CheckUnicodeSingleton((PyObject *)&_Py_ID(number), "number", 6); + _PyStaticObject_CheckUnicodeSingleton((PyObject *)&_Py_ID(numerator), "numerator", 9); _PyStaticObject_CheckUnicodeSingleton((PyObject *)&_Py_ID(obj), "obj", 3); _PyStaticObject_CheckUnicodeSingleton((PyObject *)&_Py_ID(object), "object", 6); _PyStaticObject_CheckUnicodeSingleton((PyObject *)&_Py_ID(offset), "offset", 6); diff --git a/Include/internal/pycore_global_strings.h b/Include/internal/pycore_global_strings.h index 02f6a0a3011fb71..4b5f9fa731d8e47 100644 --- a/Include/internal/pycore_global_strings.h +++ b/Include/internal/pycore_global_strings.h @@ -436,6 +436,7 @@ struct _Py_global_strings { STRUCT_FOR_ID(default) STRUCT_FOR_ID(defaultaction) STRUCT_FOR_ID(delete) + STRUCT_FOR_ID(denominator) STRUCT_FOR_ID(depth) STRUCT_FOR_ID(desired_access) STRUCT_FOR_ID(detect_types) @@ -704,6 +705,7 @@ struct _Py_global_strings { STRUCT_FOR_ID(nt) STRUCT_FOR_ID(null) STRUCT_FOR_ID(number) + STRUCT_FOR_ID(numerator) STRUCT_FOR_ID(obj) STRUCT_FOR_ID(object) STRUCT_FOR_ID(offset) diff --git a/Include/internal/pycore_runtime_init_generated.h b/Include/internal/pycore_runtime_init_generated.h index bce100733f8436f..479310bdc2d896c 100644 --- a/Include/internal/pycore_runtime_init_generated.h +++ b/Include/internal/pycore_runtime_init_generated.h @@ -1711,6 +1711,7 @@ extern "C" { INIT_ID(default), \ INIT_ID(defaultaction), \ INIT_ID(delete), \ + INIT_ID(denominator), \ INIT_ID(depth), \ INIT_ID(desired_access), \ INIT_ID(detect_types), \ @@ -1979,6 +1980,7 @@ extern "C" { INIT_ID(nt), \ INIT_ID(null), \ INIT_ID(number), \ + INIT_ID(numerator), \ INIT_ID(obj), \ INIT_ID(object), \ INIT_ID(offset), \ diff --git a/Include/internal/pycore_unicodeobject_generated.h b/Include/internal/pycore_unicodeobject_generated.h index 02e9a22918bbfd2..2db08616edd693f 100644 --- a/Include/internal/pycore_unicodeobject_generated.h +++ b/Include/internal/pycore_unicodeobject_generated.h @@ -388,6 +388,7 @@ _PyUnicode_InitStaticStrings(PyInterpreterState *interp) { offsetof(struct _Py_global_strings, identifiers._py_default._ascii.ob_base), offsetof(struct _Py_global_strings, identifiers._py_defaultaction._ascii.ob_base), offsetof(struct _Py_global_strings, identifiers._py_delete._ascii.ob_base), + offsetof(struct _Py_global_strings, identifiers._py_denominator._ascii.ob_base), offsetof(struct _Py_global_strings, identifiers._py_depth._ascii.ob_base), offsetof(struct _Py_global_strings, identifiers._py_desired_access._ascii.ob_base), offsetof(struct _Py_global_strings, identifiers._py_detect_types._ascii.ob_base), @@ -656,6 +657,7 @@ _PyUnicode_InitStaticStrings(PyInterpreterState *interp) { offsetof(struct _Py_global_strings, identifiers._py_nt._ascii.ob_base), offsetof(struct _Py_global_strings, identifiers._py_null._ascii.ob_base), offsetof(struct _Py_global_strings, identifiers._py_number._ascii.ob_base), + offsetof(struct _Py_global_strings, identifiers._py_numerator._ascii.ob_base), offsetof(struct _Py_global_strings, identifiers._py_obj._ascii.ob_base), offsetof(struct _Py_global_strings, identifiers._py_object._ascii.ob_base), offsetof(struct _Py_global_strings, identifiers._py_offset._ascii.ob_base), diff --git a/Lib/_pydatetime.py b/Lib/_pydatetime.py index b974887fbe09703..735569c654bf67e 100644 --- a/Lib/_pydatetime.py +++ b/Lib/_pydatetime.py @@ -1792,14 +1792,28 @@ def _fromtimestamp(cls, t, utc, tz): A timezone info object may be passed in as well. """ - frac, t = _math.modf(t) - us = round(frac * 1e6) - if us >= 1000000: + if isinstance(t, float): + frac, t = _math.modf(t) + us = round(frac * 1e6) + else: + try: + try: + n, d = t.as_integer_ratio() + except AttributeError: + n = t.numerator + d = t.denominator + except AttributeError: + frac, t = _math.modf(t) + us = round(frac * 1e6) + else: + t, n = divmod(n, d) + us = _divide_and_round(n * 1_000_000, d) + if us >= 1_000_000: t += 1 - us -= 1000000 + us -= 1_000_000 elif us < 0: t -= 1 - us += 1000000 + us += 1_000_000 converter = _time.gmtime if utc else _time.localtime y, m, d, hh, mm, ss, weekday, jday, dst = converter(t) diff --git a/Lib/test/datetimetester.py b/Lib/test/datetimetester.py index 323bf1921778a85..2e2e64ff09f7bb1 100644 --- a/Lib/test/datetimetester.py +++ b/Lib/test/datetimetester.py @@ -2999,11 +2999,11 @@ def utcfromtimestamp(*args, **kwargs): self.assertEqual(t, zero) t = fts(D('0.000_000_5')) self.assertEqual(t, zero) - t = fts(D('0.000_000_500_000_000_000_000_1')) + t = fts(D('0.000_000_500_000_000_000_000_000_000_000_000_000_001')) self.assertEqual(t, one) t = fts(D('0.000_000_9')) self.assertEqual(t, one) - t = fts(D('0.999_999_499_999_999_9')) + t = fts(D('0.999_999_499_999_999_999_999_999_999_999_999_999_999')) self.assertEqual(t.second, 0) self.assertEqual(t.microsecond, 999_999) t = fts(D('0.999_999_5')) @@ -3016,6 +3016,21 @@ def utcfromtimestamp(*args, **kwargs): self.assertEqual(t.second, 0) self.assertEqual(t.microsecond, 7812) + t = fts(D('2_147_475_000.000_000_5')) + self.assertEqual(t.second, 0) + self.assertEqual(t.microsecond, 0) + t = fts(D('2_147_475_000' + '.000_000_500_000_000_000_000_000_000_000_000_000_001')) + self.assertEqual(t.second, 0) + self.assertEqual(t.microsecond, 1) + t = fts(D('2_147_475_000' + '.999_999_499_999_999_999_999_999_999_999_999_999_999')) + self.assertEqual(t.second, 0) + self.assertEqual(t.microsecond, 999_999) + t = fts(D('2_147_475_000.999_999_5')) + self.assertEqual(t.second, 1) + self.assertEqual(t.microsecond, 0) + @support.run_with_tz('MSK-03') # Something east of Greenwich def test_microsecond_rounding_fraction(self): F = fractions.Fraction @@ -3046,11 +3061,13 @@ def utcfromtimestamp(*args, **kwargs): self.assertEqual(t, zero) t = fts(F(5, 10_000_000)) self.assertEqual(t, zero) - t = fts(F(5_000_000_000, 9_999_999_999_999_999)) + t = fts(F( 5_000_000_000_000_000_000_000_000_000_000_000, + 9_999_999_999_999_999_999_999_999_999_999_999_999_999)) self.assertEqual(t, one) t = fts(F(9, 10_000_000)) self.assertEqual(t, one) - t = fts(F(9_999_995_000_000_000, 10_000_000_000_000_001)) + t = fts(F( 9_999_995_000_000_000_000_000_000_000_000_000_000_000, + 10_000_000_000_000_000_000_000_000_000_000_000_000_001)) self.assertEqual(t.second, 0) self.assertEqual(t.microsecond, 999_999) t = fts(F(9_999_995, 10_000_000)) @@ -3063,6 +3080,48 @@ def utcfromtimestamp(*args, **kwargs): self.assertEqual(t.second, 0) self.assertEqual(t.microsecond, 7812) + t = fts(2_147_475_000 + F(5, 10_000_000)) + self.assertEqual(t.second, 0) + self.assertEqual(t.microsecond, 0) + t = fts(2_147_475_000 + + F( 5_000_000_000_000_000_000_000_000_000_000_000, + 9_999_999_999_999_999_999_999_999_999_999_999_999_999)) + self.assertEqual(t.second, 0) + self.assertEqual(t.microsecond, 1) + t = fts(2_147_475_000 + + F( 9_999_995_000_000_000_000_000_000_000_000_000_000_000, + 10_000_000_000_000_000_000_000_000_000_000_000_000_001)) + self.assertEqual(t.second, 0) + self.assertEqual(t.microsecond, 999_999) + t = fts(2_147_475_000 + F(9_999_995, 10_000_000)) + self.assertEqual(t.second, 1) + self.assertEqual(t.microsecond, 0) + + @support.run_with_tz('MSK-03') # Something east of Greenwich + def test_microsecond_rounding_ratio(self): + # A number which only has the numerator and denominator attributes. + class Ratio: + def __init__(self, fraction): + self.numerator = fraction.numerator + self.denominator = fraction.denominator + + F = fractions.Fraction + fts = self.theclass.fromtimestamp + for value in [ + F(0), F(1, 1_000_000), F(-1, 1_000_000), + F(5, 10_000_000), F(-5, 10_000_000), F(15, 10_000_000), + 2_147_475_000 + F(5, 10_000_000), + 2_147_475_000 + + F( 5_000_000_000_000_000_000_000_000_000_000_000, + 9_999_999_999_999_999_999_999_999_999_999_999_999_999), + 2_147_475_000 + + F( 9_999_995_000_000_000_000_000_000_000_000_000_000_000, + 10_000_000_000_000_000_000_000_000_000_000_000_000_001), + 2_147_475_000 + F(9_999_995, 10_000_000), + ]: + with self.subTest(value=value): + self.assertEqual(fts(Ratio(value)), fts(value)) + def test_timestamp_limits(self): with self.subTest("minimum UTC"): min_dt = self.theclass.min.replace(tzinfo=timezone.utc) diff --git a/Lib/test/test_os/test_os.py b/Lib/test/test_os/test_os.py index 8b6b7deb65b88bd..4c80285a50a5f70 100644 --- a/Lib/test/test_os/test_os.py +++ b/Lib/test/test_os/test_os.py @@ -1181,16 +1181,12 @@ def ns_to_sec(ns): @staticmethod def ns_to_sec_decimal(ns): # Convert a number of nanosecond (int) to a number of seconds (Decimal). - # Round towards infinity by adding 0.5 nanosecond to avoid rounding - # issue, os.utime() rounds towards minus infinity. - return decimal.Decimal('1e-9') * ns + decimal.Decimal('0.5e-9') + return decimal.Decimal('1e-9') * ns @staticmethod def ns_to_sec_fraction(ns): # Convert a number of nanosecond (int) to a number of seconds (Fraction). - # Round towards infinity by adding 0.5 nanosecond to avoid rounding - # issue, os.utime() rounds towards minus infinity. - return fractions.Fraction(ns, 10**9) + fractions.Fraction(1, 2*10**9) + return fractions.Fraction(ns, 10**9) def test_utime_by_indexed(self): # pass times as floating-point seconds as the second indexed parameter diff --git a/Lib/test/test_time.py b/Lib/test/test_time.py index 861076357e0019a..2f4eda96c052169 100644 --- a/Lib/test/test_time.py +++ b/Lib/test/test_time.py @@ -57,6 +57,13 @@ class _PyTime(enum.IntEnum): ) +class RatioNumber: + """A number which only has the numerator and denominator attributes.""" + def __init__(self, numerator, denominator): + self.numerator = numerator + self.denominator = denominator + + class TimeTestCase(unittest.TestCase): def setUp(self): @@ -1049,6 +1056,54 @@ def decimal_round(self, x): d = d.quantize(1) return int(d) + def check_ratio_rounding(self, pytime_converter, expected_func, + sec_to_unit, value_filter=None): + """Test the conversion of numbers which are neither int nor float. + + The number of seconds is converted exactly to the number of units + (sec_to_unit per second), rounded with the specified rounding mode + and passed to expected_func(). + """ + exp = round(math.log10(sec_to_unit)) - 12 + # Timestamps in picoseconds: rounding to a nanosecond is required. + ps_timestamps = sorted({ns * 1000 + delta + for ns in self._rounding_values(False) + for delta in (-501, -500, -499, -1, 0, + 1, 499, 500, 501)}) + for time_rnd, decimal_rnd in ROUNDING_MODES: + with decimal.localcontext() as context: + context.rounding = decimal_rnd + for ps in ps_timestamps: + units = int(decimal.Decimal(ps).scaleb(exp).quantize(1)) + if value_filter and not value_filter(units // sec_to_unit): + continue + expected = expected_func(units) + for value in (fractions.Fraction(ps, 10**12), + decimal.Decimal(ps).scaleb(-12), + RatioNumber(ps, 10**12)): + debug_info = {'value': value, 'rounding': decimal_rnd} + self.assertEqual(pytime_converter(value, time_rnd), + expected, debug_info) + + # test overflow + for time_rnd, _ in ROUNDING_MODES: + for seconds in (-self.OVERFLOW_SECONDS, self.OVERFLOW_SECONDS): + for value in (fractions.Fraction(seconds), + decimal.Decimal(seconds), + RatioNumber(seconds, 1)): + debug_info = {'value': value, 'rounding': time_rnd} + with self.assertRaises(OverflowError, msg=debug_info): + pytime_converter(value, time_rnd) + + for time_rnd, _ in ROUNDING_MODES: + # test nan + with self.assertRaises(ValueError): + pytime_converter(decimal.Decimal('nan'), time_rnd) + # a type is not a number + for value in (int, fractions.Fraction, RatioNumber): + with self.assertRaisesRegex(TypeError, 'must be real number'): + pytime_converter(value, time_rnd) + class TestCPyTime(CPyTimeTestCase, unittest.TestCase): """ @@ -1084,6 +1139,11 @@ def test_FromSecondsObject(self): _PyTime_FromSecondsObject, lambda ns: self.decimal_round(ns * SEC_TO_NS)) + self.check_ratio_rounding( + _PyTime_FromSecondsObject, + lambda ns: ns, SEC_TO_NS, + value_filter=lambda secs: PyTime_MIN <= secs * SEC_TO_NS <= PyTime_MAX) + # test nan for time_rnd, _ in ROUNDING_MODES: with self.assertRaises(ValueError): @@ -1235,6 +1295,10 @@ def test_object_to_time_t(self): self.decimal_round, value_filter=self.time_t_filter) + self.check_ratio_rounding(_PyTime_ObjectToTime_t, + lambda secs: secs, 1, + value_filter=self.time_t_filter) + def create_converter(self, sec_to_unit): def converter(secs): floatpart, intpart = math.modf(secs) @@ -1261,6 +1325,11 @@ def test_object_to_timeval(self): self.create_converter(SEC_TO_US), value_filter=self.time_t_filter) + self.check_ratio_rounding(_PyTime_ObjectToTimeval, + lambda units: divmod(units, SEC_TO_US), + SEC_TO_US, + value_filter=self.time_t_filter) + # test nan for time_rnd, _ in ROUNDING_MODES: with self.assertRaises(ValueError): @@ -1277,6 +1346,11 @@ def test_object_to_timespec(self): self.create_converter(SEC_TO_NS), value_filter=self.time_t_filter) + self.check_ratio_rounding(_PyTime_ObjectToTimespec, + lambda units: divmod(units, SEC_TO_NS), + SEC_TO_NS, + value_filter=self.time_t_filter) + # test nan for time_rnd, _ in ROUNDING_MODES: with self.assertRaises(ValueError): diff --git a/Misc/NEWS.d/next/Library/2026-05-04-20-10-04.gh-issue-67795.v9wb5q.rst b/Misc/NEWS.d/next/Library/2026-05-04-20-10-04.gh-issue-67795.v9wb5q.rst new file mode 100644 index 000000000000000..dcc0c1d65b161a5 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-05-04-20-10-04.gh-issue-67795.v9wb5q.rst @@ -0,0 +1,3 @@ +Avoid the precision loss caused by the :class:`float` type in functions that +take more precise numbers (such as :class:`~decimal.Decimal` and +:class:`~fractions.Fraction`) as timestamp or timeout arguments. diff --git a/Python/pytime.c b/Python/pytime.c index 53c82736137a16b..d0f6c3372846be0 100644 --- a/Python/pytime.c +++ b/Python/pytime.c @@ -1,5 +1,6 @@ #include "Python.h" #include "pycore_initconfig.h" // _PyStatus_ERR +#include "pycore_long.h" // _PyLong_DivmodNear() #include "pycore_pystate.h" // _Py_AssertHoldsTstate() #include "pycore_runtime.h" // _PyRuntime #include "pycore_time.h" // export _PyLong_FromTime_t() @@ -449,34 +450,289 @@ pytime_double_to_denominator(double d, time_t *sec, long *numerator, } +/* Convert a number to a fraction representation. + * + * Set *ratio to a 2-tuple (numerator, denominator) and return 1 on success. + * Set *ratio to NULL and return 0 if the number has neither the + * as_integer_ratio() method nor the numerator and denominator attributes. + * Return -1 on error. + */ +static int +maybe_as_integer_ratio(PyObject *number, PyObject **ratio) +{ + *ratio = NULL; + if (PyType_Check(number)) { + PyErr_Format(PyExc_TypeError, + "must be real number, not %T", number); + return -1; + } + PyObject *meth; + if (PyObject_GetOptionalAttr(number, &_Py_ID(as_integer_ratio), &meth) < 0) { + return -1; + } + if (meth) { + *ratio = PyObject_CallNoArgs(meth); + Py_DECREF(meth); + if (*ratio == NULL) { + return -1; + } + if (!PyTuple_Check(*ratio)) { + PyErr_Format(PyExc_TypeError, + "unexpected return type from %T.as_integer_ratio(): " + "expected tuple, not '%T'", + number, *ratio); + Py_CLEAR(*ratio); + return -1; + } + if (PyTuple_GET_SIZE(*ratio) != 2) { + PyErr_Format(PyExc_ValueError, + "%T.as_integer_ratio() must return a 2-tuple", + number); + Py_CLEAR(*ratio); + return -1; + } + return 1; + } + + PyObject *numerator, *denominator; + int rc = PyObject_GetOptionalAttr(number, &_Py_ID(numerator), &numerator); + if (rc <= 0) { + return rc; + } + rc = PyObject_GetOptionalAttr(number, &_Py_ID(denominator), &denominator); + if (rc <= 0) { + Py_DECREF(numerator); + return rc; + } + *ratio = PyTuple_Pack(2, numerator, denominator); + Py_DECREF(numerator); + Py_DECREF(denominator); + return *ratio ? 1 : -1; +} + +/* PyNumber_Divmod() that always returns a 2-tuple. */ +static PyObject * +checked_divmod(PyObject *a, PyObject *b) +{ + PyObject *result = PyNumber_Divmod(a, b); + if (result == NULL) { + return NULL; + } + if (!PyTuple_Check(result)) { + PyErr_Format(PyExc_TypeError, + "divmod() returned non-tuple (type %T)", + result); + Py_DECREF(result); + return NULL; + } + if (PyTuple_GET_SIZE(result) != 2) { + PyErr_Format(PyExc_TypeError, + "divmod() returned a tuple of size %zd", + PyTuple_GET_SIZE(result)); + Py_DECREF(result); + return NULL; + } + return result; +} + +/* Calculate numerator / denominator rounded to integer using + * the specified rounding mode. */ +static PyObject * +divide_and_round(PyObject *numerator, PyObject *denominator, _PyTime_round_t round) +{ + if (round == _PyTime_ROUND_UP) { + int isneg = PyObject_RichCompareBool(numerator, _PyLong_GetZero(), Py_LT); + if (isneg < 0) { + return NULL; + } + round = isneg ? _PyTime_ROUND_FLOOR : _PyTime_ROUND_CEILING; + } + + if (round == _PyTime_ROUND_FLOOR) { + return PyNumber_FloorDivide(numerator, denominator); + } + + PyObject *divmod, *result; + if (round == _PyTime_ROUND_CEILING) { + divmod = checked_divmod(numerator, denominator); + if (divmod == NULL) { + return NULL; + } + int nonzero = PyObject_IsTrue(PyTuple_GET_ITEM(divmod, 1)); + if (nonzero < 0) { + result = NULL; + } + else if (nonzero) { + result = PyNumber_Add(PyTuple_GET_ITEM(divmod, 0), _PyLong_GetOne()); + } + else { + result = Py_NewRef(PyTuple_GET_ITEM(divmod, 0)); + } + } + else { + assert(round == _PyTime_ROUND_HALF_EVEN); + divmod = _PyLong_DivmodNear(numerator, denominator); + if (divmod == NULL) { + return NULL; + } + result = Py_NewRef(PyTuple_GET_ITEM(divmod, 0)); + } + Py_DECREF(divmod); + return result; +} + +/* Calculate scale * numerator / denominator rounded to integer using + * the specified rounding mode. */ +static PyObject * +multiply_divide_and_round(long scale, PyObject *numerator, PyObject *denominator, + _PyTime_round_t round) +{ + PyObject *scaleobj = PyLong_FromLong(scale); + if (scaleobj == NULL) { + return NULL; + } + numerator = PyNumber_Multiply(numerator, scaleobj); + Py_DECREF(scaleobj); + if (numerator == NULL) { + return NULL; + } + PyObject *result = divide_and_round(numerator, denominator, round); + Py_DECREF(numerator); + return result; +} + +static int +pytime_ratio_to_denominator(PyObject *numerator, PyObject *denominator, + time_t *sec, long *subsec, + long scale, _PyTime_round_t round) +{ + PyObject *divmod = checked_divmod(numerator, denominator); + if (divmod == NULL) { + return -1; + } + *sec = _PyLong_AsTime_t(PyTuple_GET_ITEM(divmod, 0)); + if (*sec == (time_t)-1 && PyErr_Occurred()) { + Py_DECREF(divmod); + return -1; + } + if (round == _PyTime_ROUND_UP) { + /* The remainder is non-negative, so the direction of rounding + depends on the sign of the whole number. */ + round = *sec < 0 ? _PyTime_ROUND_FLOOR : _PyTime_ROUND_CEILING; + } + PyObject *tmp = multiply_divide_and_round(scale, + PyTuple_GET_ITEM(divmod, 1), + denominator, + round); + Py_DECREF(divmod); + if (tmp == NULL) { + return -1; + } + *subsec = PyLong_AsLong(tmp); + Py_DECREF(tmp); + if (*subsec == -1 && PyErr_Occurred()) { + return -1; + } + if (*subsec < 0) { + *subsec += scale; + if (*sec <= PY_TIME_T_MIN) { + pytime_time_t_overflow(); + return -1; + } + *sec -= 1; + } + else if (*subsec >= scale) { + *subsec -= scale; + if (*sec >= PY_TIME_T_MAX) { + pytime_time_t_overflow(); + return -1; + } + *sec += 1; + } + return 0; +} + + +static int +pytime_pyfloat_to_denominator(PyObject *obj, time_t *sec, long *numerator, + long denominator, _PyTime_round_t round) +{ + double d = PyFloat_AsDouble(obj); + if (d == -1 && PyErr_Occurred()) { + return -1; + } + if (isnan(d)) { + PyErr_SetString(PyExc_ValueError, "Invalid value NaN (not a number)"); + return -1; + } + return pytime_double_to_denominator(d, sec, numerator, + denominator, round); +} + + static int pytime_object_to_denominator(PyObject *obj, time_t *sec, long *numerator, long denominator, _PyTime_round_t round) { assert(denominator >= 1); + *numerator = 0; if (PyIndex_Check(obj)) { *sec = _PyLong_AsTime_t(obj); - *numerator = 0; if (*sec == (time_t)-1 && PyErr_Occurred()) { return -1; } return 0; } + else if (PyFloat_Check(obj)) { + return pytime_pyfloat_to_denominator(obj, sec, numerator, + denominator, round); + } else { - double d = PyFloat_AsDouble(obj); - if (d == -1 && PyErr_Occurred()) { - *numerator = 0; + PyObject *ratio; + if (maybe_as_integer_ratio(obj, &ratio) < 0) { return -1; } - if (isnan(d)) { - *numerator = 0; - PyErr_SetString(PyExc_ValueError, "Invalid value NaN (not a number)"); - return -1; + if (ratio == NULL) { + return pytime_pyfloat_to_denominator(obj, sec, numerator, + denominator, round); } - return pytime_double_to_denominator(d, sec, numerator, - denominator, round); + int rc = pytime_ratio_to_denominator(PyTuple_GET_ITEM(ratio, 0), + PyTuple_GET_ITEM(ratio, 1), + sec, numerator, + denominator, round); + Py_DECREF(ratio); + return rc; + } +} + + +static int +pytime_pyfloat_to_time_t(PyObject *obj, time_t *sec, _PyTime_round_t round) +{ + double intpart; + /* volatile avoids optimization changing how numbers are rounded */ + volatile double d; + + d = PyFloat_AsDouble(obj); + if (d == -1 && PyErr_Occurred()) { + return -1; } + if (isnan(d)) { + PyErr_SetString(PyExc_ValueError, "Invalid value NaN (not a number)"); + return -1; + } + + d = pytime_round(d, round); + (void)modf(d, &intpart); + + /* See comments in pytime_double_to_denominator */ + if (!((double)PY_TIME_T_MIN <= intpart && intpart < -(double)PY_TIME_T_MIN)) { + pytime_time_t_overflow(); + return -1; + } + *sec = (time_t)intpart; + return 0; } @@ -490,29 +746,29 @@ _PyTime_ObjectToTime_t(PyObject *obj, time_t *sec, _PyTime_round_t round) } return 0; } + else if (PyFloat_Check(obj)) { + return pytime_pyfloat_to_time_t(obj, sec, round); + } else { - double intpart; - /* volatile avoids optimization changing how numbers are rounded */ - volatile double d; - - d = PyFloat_AsDouble(obj); - if (d == -1 && PyErr_Occurred()) { + PyObject *ratio; + if (maybe_as_integer_ratio(obj, &ratio) < 0) { return -1; } - if (isnan(d)) { - PyErr_SetString(PyExc_ValueError, "Invalid value NaN (not a number)"); + if (ratio == NULL) { + return pytime_pyfloat_to_time_t(obj, sec, round); + } + PyObject *secobj = divide_and_round(PyTuple_GET_ITEM(ratio, 0), + PyTuple_GET_ITEM(ratio, 1), + round); + Py_DECREF(ratio); + if (secobj == NULL) { return -1; } - - d = pytime_round(d, round); - (void)modf(d, &intpart); - - /* See comments in pytime_double_to_denominator */ - if (!((double)PY_TIME_T_MIN <= intpart && intpart < -(double)PY_TIME_T_MIN)) { - pytime_time_t_overflow(); + *sec = _PyLong_AsTime_t(secobj); + Py_DECREF(secobj); + if (*sec == (time_t)-1 && PyErr_Occurred()) { return -1; } - *sec = (time_t)intpart; return 0; } } @@ -647,6 +903,22 @@ pytime_from_double(PyTime_t *tp, double value, _PyTime_round_t round, } +static int +pytime_from_pyfloat(PyTime_t *tp, PyObject *obj, _PyTime_round_t round, + long unit_to_ns) +{ + double d = PyFloat_AsDouble(obj); + if (d == -1 && PyErr_Occurred()) { + return -1; + } + if (isnan(d)) { + PyErr_SetString(PyExc_ValueError, "Invalid value NaN (not a number)"); + return -1; + } + return pytime_from_double(tp, d, round, unit_to_ns); +} + + static int pytime_from_object(PyTime_t *tp, PyObject *obj, _PyTime_round_t round, long unit_to_ns) @@ -671,17 +943,63 @@ pytime_from_object(PyTime_t *tp, PyObject *obj, _PyTime_round_t round, *tp = ns; return 0; } + else if (PyFloat_Check(obj)) { + return pytime_from_pyfloat(tp, obj, round, unit_to_ns); + } else { - double d; - d = PyFloat_AsDouble(obj); - if (d == -1 && PyErr_Occurred()) { + PyObject *ratio; + if (maybe_as_integer_ratio(obj, &ratio) < 0) { return -1; } - if (isnan(d)) { - PyErr_SetString(PyExc_ValueError, "Invalid value NaN (not a number)"); + if (ratio == NULL) { + return pytime_from_pyfloat(tp, obj, round, unit_to_ns); + } + PyObject *divmod = checked_divmod(PyTuple_GET_ITEM(ratio, 0), + PyTuple_GET_ITEM(ratio, 1)); + if (divmod == NULL) { + Py_DECREF(ratio); + return -1; + } + PyTime_t units; + if (PyLong_AsInt64(PyTuple_GET_ITEM(divmod, 0), &units) < 0) { + Py_DECREF(divmod); + Py_DECREF(ratio); + if (PyErr_ExceptionMatches(PyExc_OverflowError)) { + pytime_overflow(); + } + return -1; + } + if (round == _PyTime_ROUND_UP) { + /* The remainder is non-negative, so the direction of rounding + depends on the sign of the whole number. */ + round = units < 0 ? _PyTime_ROUND_FLOOR : _PyTime_ROUND_CEILING; + } + PyObject *fracobj = multiply_divide_and_round( + unit_to_ns, PyTuple_GET_ITEM(divmod, 1), + PyTuple_GET_ITEM(ratio, 1), round); + Py_DECREF(divmod); + Py_DECREF(ratio); + if (fracobj == NULL) { + return -1; + } + long frac = PyLong_AsLong(fracobj); + Py_DECREF(fracobj); + if (frac == -1 && PyErr_Occurred()) { + return -1; + } + if (units < 0 && frac > 0) { + /* Avoid a spurious overflow near PyTime_MIN. */ + units += 1; + frac -= unit_to_ns; + } + if (pytime_mul(&units, unit_to_ns) < 0 + || pytime_add(&units, frac) < 0) + { + pytime_overflow(); return -1; } - return pytime_from_double(tp, d, round, unit_to_ns); + *tp = units; + return 0; } }