]> www.git.momoyon.org Git - commonlib.git/commitdiff
Add Dynamic-Array.
authormomoyonwork <ahmedsamyhwork@gmail.com>
Sat, 25 Jan 2025 07:17:09 +0000 (12:17 +0500)
committermomoyonwork <ahmedsamyhwork@gmail.com>
Sat, 25 Jan 2025 07:17:09 +0000 (12:17 +0500)
commonlib.h

index d2db74e8b3a7895fbd7e106ad9e4ddbad3032e37..0115ec14c5fd8887efafe131f21fa3db08578460 100644 (file)
@@ -37,10 +37,45 @@ typedef const wchar* wstr;
 \r
 #define c_ARRAY_LEN(arr) (sizeof(arr) / sizeof(arr[0]))\r
 \r
+//\r
 // Struct pre-decls\r
+//\r
 \r
 typedef struct c_Arena c_Arena;\r
 \r
+\r
+//\r
+// ## Data Structures\r
+//\r
+\r
+//\r
+// Dynamic-Array\r
+//\r
+\r
+// NOTE: To use c_da_append() the Dynamic-Array struct should be defined using\r
+// DEFINE_DYNAMIC_ARRAY or have the same members as below!\r
+#define DEFINE_DYNAMIC_ARRAY(struct_name, elm_type) typedef struct {\\r
+        elm_type *items;\\r
+        size_t count;\\r
+        size_t capacity;\\r
+    }\r
+\r
+#define c_DYNAMIC_ARRAY_INITIAL_CAPACITY (sizeof(size_t))\r
+\r
+#define c_da_append(da, elm) do {\\r
+               if ((da).items == NULL) {\\r
+                       (da).capacity = DYNAMIC_ARRAY_INITIAL_CAPACITY;\\r
+                       (da).count = 0;\\r
+                       (da).items = malloc(sizeof(elm) * (da).capacity);\\r
+               }\\r
+               if ((da).count + 1 > (da).capacity) {\\r
+                       (da).capacity *= 2;\\r
+                       if (DEBUG) log_info("%s realloced!", #da);\\r
+                       ASSERT(realloc((da).items, (da).capacity * sizeof(*(da).items)) != NULL, "TODO: Log error instead of asserting");\\r
+               }\\r
+               (da).items[(da).count++] = elm;\\r
+       } while (0)\r
+\r
 //\r
 // OS\r
 //\r