glib-aux: add nm_time_map_clock() helper

This commit is contained in:
Thomas Haller 2022-10-13 16:37:10 +02:00
parent 2e27f16d26
commit 8506865345
No known key found for this signature in database
GPG key ID: 29C2366E4DFC5728
2 changed files with 35 additions and 0 deletions

View file

@ -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;
}
}

View file

@ -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__ */