event-loop: Use timespec utils instead of hand-rolling our own

Signed-off-by: Sebastian Wick <sebastian.wick@redhat.com>
This commit is contained in:
Sebastian Wick 2024-02-07 18:46:58 +01:00 committed by Derek Foreman
parent 893e4fc46d
commit ff8b885523

View file

@ -38,6 +38,7 @@
#include <sys/signalfd.h>
#include <sys/timerfd.h>
#include <unistd.h>
#include "timespec-util.h"
#include "wayland-util.h"
#include "wayland-private.h"
#include "wayland-server-core.h"
@ -973,57 +974,6 @@ wl_event_loop_dispatch_idle(struct wl_event_loop *loop)
}
}
static int
timespec_to_ms(struct timespec value)
{
return (value.tv_sec * 1000) + (value.tv_nsec / 1000000);
}
static struct timespec
ms_to_timespec(int ms)
{
struct timespec val;
val.tv_sec = ms / 1000;
val.tv_nsec = (ms % 1000) * 1000000;
return val;
}
static struct timespec
timespec_normalize(struct timespec value)
{
struct timespec result = value;
while (result.tv_nsec >= 1000000000) {
result.tv_nsec -= 1000000000;
result.tv_sec++;
}
while (result.tv_nsec < 0) {
result.tv_nsec += 1000000000;
result.tv_sec--;
}
return result;
}
static struct timespec
timespec_add(struct timespec a, struct timespec b)
{
struct timespec result;
result.tv_sec = a.tv_sec + b.tv_sec;
result.tv_nsec = a.tv_nsec + b.tv_nsec;
return timespec_normalize(result);
}
static struct timespec
timespec_sub(struct timespec a, struct timespec b)
{
struct timespec result;
result.tv_sec = a.tv_sec - b.tv_sec;
result.tv_nsec = a.tv_nsec - b.tv_nsec;
return timespec_normalize(result);
}
/** Wait for events and dispatch them
*
* \param loop The event loop whose sources to wait for.
@ -1052,13 +1002,15 @@ wl_event_loop_dispatch(struct wl_event_loop *loop, int timeout)
int i, count;
bool has_timers = false;
bool use_timeout = timeout > 0;
struct timespec now, end;
struct timespec now;
struct timespec deadline = {0};
struct timespec result;
wl_event_loop_dispatch_idle(loop);
if (use_timeout) {
clock_gettime(CLOCK_MONOTONIC, &now);
end = timespec_add(now, ms_to_timespec(timeout));
timespec_add_msec(&deadline, &now, timeout);
}
while (true) {
@ -1070,7 +1022,8 @@ wl_event_loop_dispatch(struct wl_event_loop *loop, int timeout)
if (use_timeout) {
clock_gettime(CLOCK_MONOTONIC, &now);
timeout = timespec_to_ms(timespec_sub(end, now));
timespec_sub(&result, &deadline, &now);
timeout = timespec_to_msec(&result);
if (timeout <= 0) {
/* too late */
count = 0;