summaryrefslogtreecommitdiff
path: root/typeutils.h
diff options
context:
space:
mode:
Diffstat (limited to 'typeutils.h')
-rw-r--r--typeutils.h63
1 files changed, 63 insertions, 0 deletions
diff --git a/typeutils.h b/typeutils.h
new file mode 100644
index 0000000..1d260ef
--- /dev/null
+++ b/typeutils.h
@@ -0,0 +1,63 @@
+#pragma once
+
+#include <ctype.h>
+#include <stddef.h>
+#include <stdlib.h>
+#include <string.h>
+#include <stdbool.h>
+#include <stdio.h>
+
+
+#define DECLARE_VEC(T, Name) \
+ typedef struct { \
+ T* items; \
+ size_t count; \
+ size_t cap; \
+ size_t incr_step; \
+ } Name; \
+ static inline Name make_##Name(size_t step) { \
+ return (Name) { \
+ .items = malloc(step* sizeof(T)), \
+ .count = 0, \
+ .cap = step, \
+ .incr_step = step, \
+ }; \
+ } \
+ static inline void push_to_##Name(Name* vec, T item) { \
+ if (vec->count == vec->cap) { \
+ vec->cap += vec->incr_step; \
+ vec->items = realloc( \
+ vec->items, \
+ vec->cap * sizeof(T) \
+ ); \
+ } \
+ vec->items[vec->count++] = item; \
+ }
+
+
+DECLARE_VEC(char, String);
+
+void append_str_to_String(String* target, char* src_str) {
+ size_t required_size =
+ ((target->count + strlen(src_str)) / target->incr_step + 1) * target->incr_step;
+ if (required_size > target->cap) {
+ target->cap = required_size;
+ target->items = realloc(target->items, required_size * sizeof(char));
+ }
+ memcpy(target->items + target->count, src_str, strlen(src_str));
+ target->count += strlen(src_str);
+}
+
+static inline char* inner(String str) {
+ if (str.count == str.cap) {
+ str.items = realloc(str.items, (str.cap+1)*sizeof(char));
+ }
+ str.items[str.count] = '\0';
+ return str.items;
+}
+
+#define DECLARE_MAYBE(T) \
+ typedef struct { \
+ bool some; \
+ T value; \
+ } Maybe##T;