Created
December 3, 2024 23:53
-
-
Save DenisBelmondo/2b8b04072132096f7fcca9ce14cf4c94 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #ifndef DYNAMIC_ARRAY_H | |
| #define DYNAMIC_ARRAY_H | |
| #ifndef DYNAMIC_ARRAY_MALLOC | |
| #include <stdlib.h> | |
| #define DYNAMIC_ARRAY_MALLOC malloc | |
| #endif | |
| #ifndef DYNAMIC_ARRAY_REALLOC | |
| #include <stdlib.h> | |
| #define DYNAMIC_ARRAY_REALLOC realloc | |
| #endif | |
| #ifndef DYNAMIC_ARRAY_MEMMOVE | |
| #include <string.h> | |
| #define DYNAMIC_ARRAY_MEMMOVE memmove | |
| #endif | |
| #ifndef DYNAMIC_ARRAY_SIZE_TYPE | |
| #define DYNAMIC_ARRAY_SIZE_TYPE int | |
| #endif | |
| #define DynamicArray(T) {\ | |
| T *elements;\ | |
| DYNAMIC_ARRAY_SIZE_TYPE count;\ | |
| DYNAMIC_ARRAY_SIZE_TYPE capacity;\ | |
| } | |
| #define DynamicArrayElementSize(ARRAY) (sizeof *((ARRAY)->elements)) | |
| #define DynamicArrayInit(ARRAY) do {\ | |
| (ARRAY)->elements = 0;\ | |
| (ARRAY)->count = 0;\ | |
| (ARRAY)->capacity = 0;\ | |
| } while (0) | |
| #define DynamicArrayReserve(ARRAY, COUNT_ELEMENTS) do {\ | |
| (ARRAY)->capacity = COUNT_ELEMENTS;\ | |
| (ARRAY)->elements = DYNAMIC_ARRAY_MALLOC(COUNT_ELEMENTS * DynamicArrayElementSize(ARRAY)); \ | |
| } while (0) | |
| #define DynamicArrayResize(ARRAY, COUNT_RESERVATIONS) do {\ | |
| (ARRAY)->capacity = COUNT_RESERVATIONS;\ | |
| (ARRAY)->elements = DYNAMIC_ARRAY_REALLOC((ARRAY)->elements, COUNT_RESERVATIONS * DynamicArrayElementSize(ARRAY)); \ | |
| } while (0) | |
| #define DynamicArrayMaybeExpand(ARRAY) do {\ | |
| if ((ARRAY)->count + 1 > (ARRAY)->capacity) {\ | |
| (ARRAY)->capacity *= 2;\ | |
| DynamicArrayResize(ARRAY, (ARRAY)->capacity);\ | |
| }\ | |
| } while (0) | |
| #define DynamicArrayPushBack(ARRAY, VALUE) do {\ | |
| DynamicArrayMaybeExpand(ARRAY);\ | |
| \ | |
| (ARRAY)->elements[(ARRAY)->count++] = (VALUE);\ | |
| } while (0) | |
| #define DynamicArrayPopBack(ARRAY) (ARRAY)->count-- | |
| #define DynamicArrayInsert(ARRAY, INDEX, VALUE) do {\ | |
| DynamicArrayMaybeExpand(ARRAY);\ | |
| \ | |
| memmove(\ | |
| &((ARRAY)->elements[INDEX + 1]),\ | |
| &((ARRAY)->elements[INDEX]),\ | |
| ((ARRAY)->count - INDEX) * DynamicArrayElementSize(ARRAY)\ | |
| );\ | |
| (ARRAY)->count += 1;\ | |
| (ARRAY)->elements[INDEX] = VALUE;\ | |
| } while (0) | |
| #define DynamicArrayShrinkToFit(ARRAY) do {\ | |
| DynamicArrayResize(ARRAY, (ARRAY)->count);\ | |
| } while (0) | |
| #endif /* DYNAMIC_ARRAY_H */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment