Skip to content

Commit e71c12c

Browse files
cfriedtkartben
authored andcommitted
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 <[email protected]>
1 parent 89c1f15 commit e71c12c

File tree

1 file changed

+7
-12
lines changed

1 file changed

+7
-12
lines changed

lib/posix/options/timespec_to_timeout.c

+7-12
Original file line numberDiff line numberDiff line change
@@ -6,24 +6,19 @@
66

77
#include "posix_clock.h"
88

9-
#include <zephyr/kernel.h>
10-
#include <ksched.h>
9+
#include <limits.h>
10+
#include <stdint.h>
11+
1112
#include <zephyr/posix/time.h>
13+
#include <zephyr/sys/util.h>
1214

1315
uint32_t timespec_to_timeoutms(clockid_t clock_id, const struct timespec *abstime)
1416
{
15-
int64_t milli_secs, secs, nsecs;
1617
struct timespec curtime;
1718

18-
clock_gettime(clock_id, &curtime);
19-
secs = abstime->tv_sec - curtime.tv_sec;
20-
nsecs = abstime->tv_nsec - curtime.tv_nsec;
21-
22-
if (secs < 0 || (secs == 0 && nsecs < NSEC_PER_MSEC)) {
23-
milli_secs = 0;
24-
} else {
25-
milli_secs = secs * MSEC_PER_SEC + nsecs / NSEC_PER_MSEC;
19+
if (clock_gettime(clock_id, &curtime) < 0) {
20+
return 0;
2621
}
2722

28-
return milli_secs;
23+
return CLAMP(tp_diff(abstime, &curtime) / NSEC_PER_MSEC, 0, UINT32_MAX);
2924
}

0 commit comments

Comments
 (0)