]> git.ozlabs.org Git - ccan/commitdiff
time: flesh out more timemono functions. master
authorRusty Russell <rusty@rustcorp.com.au>
Wed, 30 Apr 2025 00:44:44 +0000 (10:14 +0930)
committerRusty Russell <rusty@rustcorp.com.au>
Wed, 30 Apr 2025 00:44:44 +0000 (10:14 +0930)
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
ccan/time/test/run-monotonic.c
ccan/time/time.h

index 2da492d441b0160731ce4f431d31031c9b7e67a3..878d62496a5d40dc45228307fa9b462ad3e90ab1 100644 (file)
@@ -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();
 }
index 2fc8161e74ebc3696c05ae2f1247987face8d35f..48b8d1d2a4c8274deebb1616e4c0ca489d8ca2b2 100644 (file)
@@ -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;