From 0d4d2c2f9945f600fc577b5b084904b3609c4ceb Mon Sep 17 00:00:00 2001 From: sam Date: Tue, 9 Jul 2024 22:09:15 +1200 Subject: [PATCH] switch old malloc/realloc to sl_malloc/sl_realloc, may help with serializing types --- slibs.h | 78 ++++++++++++++++++++++++++++----------------------------- 1 file changed, 39 insertions(+), 39 deletions(-) diff --git a/slibs.h b/slibs.h index c3ee534..42f2e4c 100644 --- a/slibs.h +++ b/slibs.h @@ -7,42 +7,6 @@ #include #include -#pragma region Miscellaneous - -#define sl_auto(name, x) typeof(x) name = x - -#define sl_new(type, ...) \ - ({ \ - type *ptr = malloc(sizeof(type)); \ - *ptr = (type){__VA_ARGS__}; \ - ptr; \ - }) - -#define sl_init(type, ...) \ - (type) { __VA_ARGS__ } - -#define sl_array_len(arr) sizeof(arr) / sizeof(arr[0]) - -#define sl_fmt_spec(arg) \ - _Generic((arg), \ - int8_t: "%d", \ - int16_t: "%d", \ - int32_t: "%d", \ - int64_t: "%lld", \ - uint8_t: "%u", \ - uint16_t: "%u", \ - uint32_t: "%lu", \ - uint64_t: "%llu", \ - double: "%lf", \ - float: "%f", \ - char: "%c", \ - char *: "%s", \ - void *: "%p", \ - default: "Unknown") - -#define sl_stringify(x) #x - -#pragma endregion #pragma region Memory typedef struct sl_metadata { @@ -112,6 +76,42 @@ sl_mem __sl_serialize_struct(sl_mem struc, size_t size) { } #endif +#pragma endregion +#pragma region Miscellaneous + +#define sl_auto(name, x) typeof(x) name = x + +#define sl_new(type, ...) \ + ({ \ + type *ptr = sl_malloc(sizeof(type)); \ + *ptr = (type){__VA_ARGS__}; \ + ptr; \ + }) + +#define sl_init(type, ...) \ + (type) { __VA_ARGS__ } + +#define sl_array_len(arr) sizeof(arr) / sizeof(arr[0]) + +#define sl_fmt_spec(arg) \ + _Generic((arg), \ + int8_t: "%d", \ + int16_t: "%d", \ + int32_t: "%d", \ + int64_t: "%lld", \ + uint8_t: "%u", \ + uint16_t: "%u", \ + uint32_t: "%lu", \ + uint64_t: "%llu", \ + double: "%lf", \ + float: "%f", \ + char: "%c", \ + char *: "%s", \ + void *: "%p", \ + default: "Unknown") + +#define sl_stringify(x) #x + #pragma endregion #pragma region Vector @@ -125,7 +125,7 @@ sl_mem __sl_serialize_struct(sl_mem struc, size_t size) { #define sl_vec_grow(vec) \ { \ (vec).capacity = (vec).capacity * 2 + 1; \ - void *ptr = realloc((vec).data, (vec).capacity * sizeof(*(vec).data)); \ + void *ptr = sl_realloc((vec).data, (vec).capacity * sizeof(*(vec).data)); \ if (ptr) \ (vec).data = ptr; \ } @@ -186,7 +186,7 @@ typedef sl_vec(char) sl_string; #define sl_tostring(val) \ ({ \ sl_auto(len, snprintf(NULL, 0, sl_fmt_spec(val), val) + 1); \ - sl_auto(buf, (char *)malloc(len)); \ + sl_auto(buf, (char *)sl_malloc(len)); \ snprintf(buf, len, sl_fmt_spec(val), val); \ sl_auto(str, sl_string(buf)); \ free(buf); \ @@ -305,7 +305,7 @@ uint8_t* sl_read_bytes(const char *filename, size_t *length) { size_t file_size = ftell(file); fseek(file, 0, SEEK_SET); - uint8_t *data = (uint8_t *)malloc(file_size); + uint8_t *data = (uint8_t *)sl_malloc(file_size); if (!data) { fprintf(stderr, "Error: could not allocate memory\n"); fclose(file);