From bc6c7377c3e5537c16f11fcdde815298b1ea5c99 Mon Sep 17 00:00:00 2001 From: Rusty Russell Date: Wed, 30 Apr 2025 10:14:44 +0930 Subject: [PATCH] time: flesh out more timemono functions. Signed-off-by: Rusty Russell --- ccan/time/test/run-monotonic.c | 7 ++++-- ccan/time/time.h | 40 ++++++++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+), 2 deletions(-) diff --git a/ccan/time/test/run-monotonic.c b/ccan/time/test/run-monotonic.c index 2da492d4..878d6249 100644 --- a/ccan/time/test/run-monotonic.c +++ b/ccan/time/test/run-monotonic.c @@ -7,13 +7,13 @@ int main(void) struct timemono t1, t2; struct timerel t3; - plan_tests(5); + plan_tests(7); /* Test time_mono */ t1 = time_mono(); t2 = time_mono(); - ok1(!time_less_(t2.ts, t1.ts)); + ok1(!timemono_before(t2, t1)); t3.ts.tv_sec = 1; t3.ts.tv_nsec = 0; @@ -24,5 +24,8 @@ int main(void) ok1(timemono_add(t1, t3).ts.tv_sec == t1.ts.tv_sec + 1); ok1(timemono_add(t2, t3).ts.tv_nsec == t2.ts.tv_nsec); + ok1(timemono_sub(timemono_add(t1, t3), t3).ts.tv_sec == t1.ts.tv_sec); + ok1(timemono_sub(timemono_add(t1, t3), t3).ts.tv_nsec == t1.ts.tv_nsec); + return exit_status(); } diff --git a/ccan/time/time.h b/ccan/time/time.h index 2fc8161e..48b8d1d2 100644 --- a/ccan/time/time.h +++ b/ccan/time/time.h @@ -220,6 +220,23 @@ static inline bool time_before(struct timeabs a, struct timeabs b) return time_less_(a.ts, b.ts); } +/** + * timemono_before - is a before b? + * @a: one monotonic time. + * @b: another monotonic time. + * + * Example: + * static bool still_valid(const struct timemono *start) + * { + * #define TIMEOUT time_from_msec(1000) + * return timemono_before(time_mono(), timemono_add(*start, TIMEOUT)); + * } + */ +static inline bool timemono_before(struct timemono a, struct timemono b) +{ + return time_less_(a.ts, b.ts); +} + /** * time_less - is a before b? * @a: one relative time. @@ -404,6 +421,29 @@ static inline struct timeabs timeabs_sub(struct timeabs abs, struct timerel rel) return t; } +/** + * timemono_sub - subtract a relative time from a monotonic time + * @mono: the monotonic time. + * @rel: the relative time. + * + * This returns a well formed struct timemono of @mono - @rel. + * + * Example: + * // We do one every second. + * static struct timemono previous_time(void) + * { + * return timemono_sub(time_mono(), time_from_msec(1000)); + * } + */ +static inline struct timemono timemono_sub(struct timemono mono, struct timerel rel) +{ + struct timemono t; + + t.ts = time_sub_(mono.ts, rel.ts); + return t; +} + + static inline struct timespec time_add_(struct timespec a, struct timespec b) { struct timespec sum; -- 2.39.5