aboutgitcodebugslistschat
path: root/util.h
diff options
context:
space:
mode:
Diffstat (limited to 'util.h')
-rw-r--r--util.h28
1 files changed, 28 insertions, 0 deletions
diff --git a/util.h b/util.h
index 53bb54b..9446ea7 100644
--- a/util.h
+++ b/util.h
@@ -227,6 +227,34 @@ int __daemon(int pidfile_fd, int devnull_fd);
int fls(unsigned long x);
int write_file(const char *path, const char *buf);
+/**
+ * mod_sub() - Modular arithmetic subtraction
+ * @a: Minued, unsigned value < @m
+ * @b: Subtrahend, unsigned value < @m
+ * @m: Modulus, must be less than (UINT_MAX / 2)
+ *
+ * Returns (@a - @b) mod @m, correctly handling unsigned underflows.
+ */
+static inline unsigned mod_sub(unsigned a, unsigned b, unsigned m)
+{
+ if (a < b)
+ a += m;
+ return a - b;
+}
+
+/**
+ * mod_between() - Determine if a value is in a cyclic range
+ * @x, @i, @j: Unsigned values < @m
+ * @m: Modulus
+ *
+ * Returns true iff @x is in the cyclic range of values from @i..@j (mod @m),
+ * inclusive of @i, exclusive of @j.
+ */
+static inline bool mod_between(unsigned x, unsigned i, unsigned j, unsigned m)
+{
+ return mod_sub(x, i, m) < mod_sub(j, i, m);
+}
+
/*
* Workarounds for https://github.com/llvm/llvm-project/issues/58992
*