]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-74953: Add _PyTime_FromMicrosecondsClamp() function (#93942)
authorVictor Stinner <vstinner@python.org>
Fri, 17 Jun 2022 14:11:13 +0000 (16:11 +0200)
committerGitHub <noreply@github.com>
Fri, 17 Jun 2022 14:11:13 +0000 (16:11 +0200)
Include/cpython/pytime.h
Python/pytime.c
Python/thread_pthread.h

index 23d4f16a8fd8472018590277ca920742afa9393c..e64f3b13e75ca171eea35f4f9adfb2dc1f082756 100644 (file)
@@ -130,6 +130,10 @@ PyAPI_FUNC(_PyTime_t) _PyTime_FromSeconds(int seconds);
 /* Create a timestamp from a number of nanoseconds. */
 PyAPI_FUNC(_PyTime_t) _PyTime_FromNanoseconds(_PyTime_t ns);
 
+/* Create a timestamp from a number of microseconds.
+ * Clamp to [_PyTime_MIN; _PyTime_MAX] on overflow. */
+PyAPI_FUNC(_PyTime_t) _PyTime_FromMicrosecondsClamp(_PyTime_t us);
+
 /* Create a timestamp from nanoseconds (Python int). */
 PyAPI_FUNC(int) _PyTime_FromNanosecondsObject(_PyTime_t *t,
     PyObject *obj);
index f49a25bf7bce7cefc1b870d5fd4c05baa8098359..01c07da074757e785f6542fe5d69e02f034c0254 100644 (file)
@@ -406,6 +406,14 @@ _PyTime_FromNanoseconds(_PyTime_t ns)
 }
 
 
+_PyTime_t
+_PyTime_FromMicrosecondsClamp(_PyTime_t us)
+{
+    _PyTime_t ns = _PyTime_Mul(us, US_TO_NS);
+    return pytime_from_nanoseconds(ns);
+}
+
+
 int
 _PyTime_FromNanosecondsObject(_PyTime_t *tp, PyObject *obj)
 {
index 1b2c28d0f399299539282d324d40c327e362d67d..195b277dfba502f737c9414143b636c0413fee8c 100644 (file)
@@ -438,22 +438,15 @@ PyThread_acquire_lock_timed(PyThread_type_lock lock, PY_TIMEOUT_T microseconds,
 
     _PyTime_t timeout;  // relative timeout
     if (microseconds >= 0) {
-        _PyTime_t ns;
-        if (microseconds <= _PyTime_MAX / 1000) {
-            ns = microseconds * 1000;
-        }
-        else {
-            // bpo-41710: PyThread_acquire_lock_timed() cannot report timeout
-            // overflow to the caller, so clamp the timeout to
-            // [_PyTime_MIN, _PyTime_MAX].
-            //
-            // _PyTime_MAX nanoseconds is around 292.3 years.
-            //
-            // _thread.Lock.acquire() and _thread.RLock.acquire() raise an
-            // OverflowError if microseconds is greater than PY_TIMEOUT_MAX.
-            ns = _PyTime_MAX;
-        }
-        timeout = _PyTime_FromNanoseconds(ns);
+        // bpo-41710: PyThread_acquire_lock_timed() cannot report timeout
+        // overflow to the caller, so clamp the timeout to
+        // [_PyTime_MIN, _PyTime_MAX].
+        //
+        // _PyTime_MAX nanoseconds is around 292.3 years.
+        //
+        // _thread.Lock.acquire() and _thread.RLock.acquire() raise an
+        // OverflowError if microseconds is greater than PY_TIMEOUT_MAX.
+        timeout = _PyTime_FromMicrosecondsClamp(microseconds);
     }
     else {
         timeout = _PyTime_FromNanoseconds(-1);