summaryrefslogtreecommitdiff
path: root/utils.h
diff options
context:
space:
mode:
authorÁkos Kőrösi <korakos99@gmail.com>2026-05-18 09:35:05 +0200
committerÁkos Kőrösi <korakos99@gmail.com>2026-05-18 09:35:05 +0200
commitc454374b73b748dd711554b275ffaf62001b1fc9 (patch)
tree676136acd57dd26e7fce899e5bac8c87237570c1 /utils.h
parent8f6bd186173b0ab79e99de1b9c913e3ced002d21 (diff)
add utils.c
Diffstat (limited to 'utils.h')
-rw-r--r--utils.h102
1 files changed, 102 insertions, 0 deletions
diff --git a/utils.h b/utils.h
new file mode 100644
index 0000000..2463b45
--- /dev/null
+++ b/utils.h
@@ -0,0 +1,102 @@
+#pragma once
+
+#include <ctype.h>
+#include <stddef.h>
+#include <stdlib.h>
+#include <stdbool.h>
+#include <stdio.h>
+#include <string.h>
+
+
+#define DECLARE_VEC(T, Name) \
+ typedef struct { \
+ T **blocks; \
+ size_t count; \
+ size_t used; \
+ size_t cap; \
+ size_t block_size; \
+ } Name; \
+ \
+ static inline Name make_##Name(size_t block_size) { \
+ return (Name){ \
+ .blocks = NULL, \
+ .count = 0, \
+ .used = 0, \
+ .cap = 0, \
+ .block_size = block_size, \
+ }; \
+ } \
+ \
+ static inline T *push_to_##Name(Name *vec, T item) { \
+ size_t block_index = vec->count / vec->block_size; \
+ size_t item_index = vec->count % vec->block_size; \
+ \
+ if (block_index == vec->used) { \
+ if (vec->used == vec->cap) { \
+ size_t new_cap = vec->cap \
+ ? vec->cap * 2 \
+ : 8; \
+ \
+ T **new_blocks = realloc( \
+ vec->blocks, \
+ new_cap * sizeof(T *) \
+ ); \
+ \
+ if (!new_blocks) abort(); \
+ \
+ vec->blocks = new_blocks; \
+ vec->cap = new_cap; \
+ } \
+ \
+ vec->blocks[vec->used] = \
+ malloc(vec->block_size * sizeof(T)); \
+ \
+ if (!vec->blocks[vec->used]) abort(); \
+ \
+ vec->used++; \
+ } \
+ \
+ T *ptr = &vec->blocks[block_index][item_index]; \
+ *ptr = item; \
+ \
+ vec->count++; \
+ return ptr; \
+ } \
+ \
+ static inline T* get_from_##Name(Name *vec, size_t index) { \
+ if (index >= vec->count) return NULL; \
+ \
+ return &vec->blocks \
+ [index / vec->block_size] \
+ [index % vec->block_size]; \
+ }
+
+
+DECLARE_VEC(int, IntVec)
+
+DECLARE_VEC(char, String);
+DECLARE_VEC(char*, StrVec)
+
+
+void append_str_to_String(String* target, const char* src_str);
+char* inner(String* str);
+
+
+
+#define DECLARE_MAYBE(T, Name) \
+ typedef struct { \
+ bool some; \
+ T value; \
+ } Name;
+
+DECLARE_MAYBE(char*, MaybeStr)
+
+
+typedef struct {
+ char* key;
+ char* val;
+} StrPair;
+DECLARE_VEC(StrPair, KeyValMap)
+void set_map_pair(KeyValMap* map, char* key, char* val);
+MaybeStr get_map_value(KeyValMap* map, char* key);
+void unset_map_key(KeyValMap* map, char* key);