From 8506865345b8ae9c1772f2cfe2f679eef7a87cba Mon Sep 17 00:00:00 2001 From: Thomas Haller Date: Thu, 13 Oct 2022 16:37:10 +0200 Subject: [PATCH] glib-aux: add nm_time_map_clock() helper --- src/libnm-glib-aux/nm-time-utils.c | 33 ++++++++++++++++++++++++++++++ src/libnm-glib-aux/nm-time-utils.h | 2 ++ 2 files changed, 35 insertions(+) diff --git a/src/libnm-glib-aux/nm-time-utils.c b/src/libnm-glib-aux/nm-time-utils.c index 4f9200e5dd..077d0a4ca7 100644 --- a/src/libnm-glib-aux/nm-time-utils.c +++ b/src/libnm-glib-aux/nm-time-utils.c @@ -341,3 +341,36 @@ nm_utils_clock_gettime_msec(clockid_t clockid) return -NM_ERRNO_NATIVE(errno); return nm_utils_timespec_to_msec(&tp); } + +/*****************************************************************************/ + +/* Taken from systemd's map_clock_usec_internal(). */ +gint64 +nm_time_map_clock(gint64 from, gint64 from_base, gint64 to_base) +{ + /* Maps the time 'from' between two clocks, based on a common reference point where the first clock + * is at 'from_base' and the second clock at 'to_base'. Basically calculates: + * + * from - from_base + to_base + * + * But takes care of overflows/underflows and avoids signed operations. */ + + if (from >= from_base) { + gint64 delta = from - from_base; + + /* In the future */ + if (to_base >= G_MAXINT64 - delta) + return G_MAXINT64; + + return to_base + delta; + + } else { + gint64 delta = from_base - from; + + /* In the past */ + if (to_base <= G_MININT64 + delta) + return G_MININT64; + + return to_base - delta; + } +} diff --git a/src/libnm-glib-aux/nm-time-utils.h b/src/libnm-glib-aux/nm-time-utils.h index b4f70d4a9c..d31536865f 100644 --- a/src/libnm-glib-aux/nm-time-utils.h +++ b/src/libnm-glib-aux/nm-time-utils.h @@ -78,4 +78,6 @@ gint64 nm_utils_clock_gettime_nsec(clockid_t clockid); gint64 nm_utils_clock_gettime_usec(clockid_t clockid); gint64 nm_utils_clock_gettime_msec(clockid_t clockid); +gint64 nm_time_map_clock(gint64 from, gint64 from_base, gint64 to_base); + #endif /* __NM_TIME_UTILS_H__ */