summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--src/basic/time-util.h14
-rw-r--r--src/test/test-time.c13
2 files changed, 21 insertions, 6 deletions
diff --git a/src/basic/time-util.h b/src/basic/time-util.h
index 87440faeee..080c1110f5 100644
--- a/src/basic/time-util.h
+++ b/src/basic/time-util.h
@@ -143,11 +143,13 @@ static inline usec_t usec_add(usec_t a, usec_t b) {
static inline usec_t usec_sub(usec_t timestamp, int64_t delta) {
if (delta < 0)
- timestamp = usec_add(timestamp, (usec_t) (-delta));
- else if (timestamp > (usec_t) delta)
- timestamp -= delta;
- else
- timestamp = 0;
+ return usec_add(timestamp, (usec_t) (-delta));
- return timestamp;
+ if (timestamp == USEC_INFINITY) /* Make sure infinity doesn't degrade */
+ return USEC_INFINITY;
+
+ if (timestamp < (usec_t) delta)
+ return 0;
+
+ return timestamp - delta;
}
diff --git a/src/test/test-time.c b/src/test/test-time.c
index 254a8d0e52..fdbf9fa881 100644
--- a/src/test/test-time.c
+++ b/src/test/test-time.c
@@ -191,6 +191,18 @@ static void test_usec_add(void) {
assert_se(usec_add(USEC_INFINITY, 2) == USEC_INFINITY);
}
+static void test_usec_sub(void) {
+ assert_se(usec_sub(0, 0) == 0);
+ assert_se(usec_sub(4, 1) == 3);
+ assert_se(usec_sub(4, 4) == 0);
+ assert_se(usec_sub(4, 5) == 0);
+ assert_se(usec_sub(USEC_INFINITY-3, -3) == USEC_INFINITY);
+ assert_se(usec_sub(USEC_INFINITY-3, -3) == USEC_INFINITY);
+ assert_se(usec_sub(USEC_INFINITY-3, -4) == USEC_INFINITY);
+ assert_se(usec_sub(USEC_INFINITY-3, -5) == USEC_INFINITY);
+ assert_se(usec_sub(USEC_INFINITY, 5) == USEC_INFINITY);
+}
+
int main(int argc, char *argv[]) {
uintmax_t x;
@@ -203,6 +215,7 @@ int main(int argc, char *argv[]) {
test_timezone_is_valid();
test_get_timezones();
test_usec_add();
+ test_usec_sub();
/* Ensure time_t is signed */
assert_cc((time_t) -1 < (time_t) 1);