From e71c12c68f1953b290b438b7ecaa93df4fefcb9c Mon Sep 17 00:00:00 2001 From: Chris Friedt Date: Wed, 23 Apr 2025 09:35:03 -0400 Subject: [PATCH] posix: refactor timespec_to_timeoutms() to use tp_diff() Use the tp_diff() macro as a means of converting an absolute timeout with respect to a specific clock to a relative timeout, in ms. Clamp the result between 0 and UINT32_MAX. Signed-off-by: Chris Friedt --- lib/posix/options/timespec_to_timeout.c | 19 +++++++------------ 1 file changed, 7 insertions(+), 12 deletions(-) diff --git a/lib/posix/options/timespec_to_timeout.c b/lib/posix/options/timespec_to_timeout.c index d307efa736e..068646c2064 100644 --- a/lib/posix/options/timespec_to_timeout.c +++ b/lib/posix/options/timespec_to_timeout.c @@ -6,24 +6,19 @@ #include "posix_clock.h" -#include -#include +#include +#include + #include +#include uint32_t timespec_to_timeoutms(clockid_t clock_id, const struct timespec *abstime) { - int64_t milli_secs, secs, nsecs; struct timespec curtime; - clock_gettime(clock_id, &curtime); - secs = abstime->tv_sec - curtime.tv_sec; - nsecs = abstime->tv_nsec - curtime.tv_nsec; - - if (secs < 0 || (secs == 0 && nsecs < NSEC_PER_MSEC)) { - milli_secs = 0; - } else { - milli_secs = secs * MSEC_PER_SEC + nsecs / NSEC_PER_MSEC; + if (clock_gettime(clock_id, &curtime) < 0) { + return 0; } - return milli_secs; + return CLAMP(tp_diff(abstime, &curtime) / NSEC_PER_MSEC, 0, UINT32_MAX); }