aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorThomas Voss <mail@thomasvoss.com> 2023-12-19 16:56:26 +0100
committerThomas Voss <mail@thomasvoss.com> 2023-12-19 17:04:31 +0100
commit8c8c5ef8786121e3b6815b937f9e88f823fad2f3 (patch)
tree92570571d93069a5502f0ec5890d6ae581c6e680
parent63ae64d8bf7fa06eecfc2c50e3999800720c9173 (diff)
Add the da_foreach macro
-rw-r--r--da.h14
1 files changed, 13 insertions, 1 deletions
diff --git a/da.h b/da.h
index 888ac1a..9bda5df 100644
--- a/da.h
+++ b/da.h
@@ -14,7 +14,9 @@
* You should include ‘err.h’ and ‘stdlib.h’ along with this file. If you want
* to use da_remove(), include ‘string.h’. The da_remove() macro also doesn’t
* bother with shrinking your array when the length is far lower than the
- * capacity. If you care about that, do it yourself.
+ * capacity. If you care about that, do it yourself. To use the da_foreach()
+ * macro, you need to have ptrdiff_t defined; to be absolutely sure you can
+ * include ‘stddef.h’.
*
* Remember to call free() on your dynamic arrays ‘buf’ field after use.
*
@@ -27,6 +29,8 @@
* da_append(a, x) Append the item ‘x’ to the array
* da_remove(a, x) Remove the item ‘x’ from the array
* da_remove_range(a, x, y) Remove the items between the range [x, y)
+ * da_foreach(a, t, i) Iterate the pointer ‘i’ of type ‘t’ over each
+ * element of the array.
*
* The ‘da_append()’ macro will by default double the arrays capacity when it
* gets full. If you would like to use a different growth factor instead of 2,
@@ -50,6 +54,11 @@
* da_append(&nums, 1337);
* da_append(&nums, 420);
*
+ * da_foreach (&nums, int *, n) {
+ * int x = *n << 1;
+ * printf("n = %d; n² = %d\n", *n, x);
+ * }
+ *
* // Remove 1337 and 420 from nums
* da_remove_range(&nums, 1, 3);
*
@@ -94,4 +103,7 @@
(a)->len -= j - i; \
} while (0)
+#define da_foreach(a, t, i) \
+ for (t i = (a)->buf; i - (a)->buf < (ptrdiff_t)(a)->len; i++)
+
#endif /* !MANGO_DA_H */