diff --git a/libutils/Timers.cpp b/libutils/Timers.cpp index fd3f4a957..4cfac57be 100644 --- a/libutils/Timers.cpp +++ b/libutils/Timers.cpp @@ -14,9 +14,6 @@ * limitations under the License. */ -// -// Timer functions. -// #include #include @@ -24,11 +21,12 @@ #include #include +#include static constexpr size_t clock_id_max = 5; static void checkClockId(int clock) { - if (clock < 0 || clock >= clock_id_max) abort(); + LOG_ALWAYS_FATAL_IF(clock < 0 || clock >= clock_id_max, "invalid clock id"); } #if defined(__linux__) @@ -56,18 +54,10 @@ nsecs_t systemTime(int clock) { } #endif -int toMillisecondTimeoutDelay(nsecs_t referenceTime, nsecs_t timeoutTime) -{ - nsecs_t timeoutDelayMillis; - if (timeoutTime > referenceTime) { - uint64_t timeoutDelay = uint64_t(timeoutTime - referenceTime); - if (timeoutDelay > uint64_t((INT_MAX - 1) * 1000000LL)) { - timeoutDelayMillis = -1; - } else { - timeoutDelayMillis = (timeoutDelay + 999999LL) / 1000000LL; - } - } else { - timeoutDelayMillis = 0; - } - return (int)timeoutDelayMillis; +int toMillisecondTimeoutDelay(nsecs_t referenceTime, nsecs_t timeoutTime) { + if (timeoutTime <= referenceTime) return 0; + + uint64_t timeoutDelay = uint64_t(timeoutTime - referenceTime); + if (timeoutDelay > uint64_t((INT_MAX - 1) * 1000000LL)) return -1; + return (timeoutDelay + 999999LL) / 1000000LL; } diff --git a/libutils/Timers_test.cpp b/libutils/Timers_test.cpp index ec0051e67..c0a6d4997 100644 --- a/libutils/Timers_test.cpp +++ b/libutils/Timers_test.cpp @@ -27,3 +27,12 @@ TEST(Timers, systemTime_invalid) { systemTime(SYSTEM_TIME_BOOTTIME); EXPECT_EXIT(systemTime(SYSTEM_TIME_BOOTTIME + 1), testing::KilledBySignal(SIGABRT), ""); } + +TEST(Timers, toMillisecondTimeoutDelay) { + EXPECT_EQ(0, toMillisecondTimeoutDelay(100, 100)); + EXPECT_EQ(0, toMillisecondTimeoutDelay(100, 10)); + + EXPECT_EQ(-1, toMillisecondTimeoutDelay(0, INT_MAX * 1000000LL)); + + EXPECT_EQ(123, toMillisecondTimeoutDelay(0, 123000000)); +}