commit 399aed28d8e41cfef8b225fd082ac4897aece33d
parent e6a73e442a2aebf2e03a46d10a4652e9c9349a15
Author: bsandro <email@bsandro.tech>
Date: Fri, 27 Feb 2026 01:22:15 +0200
array.h draft
Diffstat:
| A | array.h | | | 40 | ++++++++++++++++++++++++++++++++++++++++ |
1 file changed, 40 insertions(+), 0 deletions(-)
diff --git a/array.h b/array.h
@@ -0,0 +1,40 @@
+#include <stdlib.h>
+
+struct array_hdr {
+ size_t len;
+ size_t cap;
+};
+
+#define array_init(ar, capacity) do { \
+ struct array_hdr *hdr = malloc(sizeof(struct array_hdr)+sizeof(*(ar))*(capacity)); \
+ printf("init %p\n", (void *)hdr); \
+ hdr->len = 0; \
+ hdr->cap = (capacity); \
+ (ar) = (void *)(hdr+1); \
+} while(0);
+
+#define array_free(ar) do { \
+ void *base = ((struct array_hdr *)(ar))-1; \
+ printf("free %p\n", (void *)base); \
+ free(base); \
+ (ar) = NULL; \
+} while(0);
+
+inline size_t array_len(void *ar) {
+ return (((struct array_hdr *)ar)-1)->len;
+}
+
+inline size_t array_cap(void *ar) {
+ return (((struct array_hdr *)ar)-1)->cap;
+}
+
+#define array_push(ar, val) do { \
+ struct array_hdr *hdr = ((struct array_hdr *)(ar))-1; \
+ printf("push: %lu of %lu\n", hdr->len, hdr->cap); \
+ if (hdr->len+1>=hdr->cap) { \
+ hdr = realloc(hdr, sizeof(*ar)*hdr->cap*2+sizeof(struct array_hdr)); \
+ hdr->cap*=2; \
+ (ar) = (void *)(hdr+1); \
+ } \
+ (ar)[hdr->len++] = val; \
+} while(0);