Last active
September 12, 2025 00:44
-
-
Save leok7v/9ca1a93c57d9f35f993368947df57ea1 to your computer and use it in GitHub Desktop.
Simple std::vector replacement in C
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
| struct _array { | |
| void* data; | |
| int count; | |
| int capacity; | |
| }; | |
| #define array_of(type) { \ | |
| type* data; \ | |
| int count; \ | |
| int capacity; \ | |
| } | |
| bool _array_init(struct _array* a, size_t count, size_t es); | |
| bool _array_grow(struct _array* a, size_t count, size_t es); | |
| bool _array_push(struct _array* a, void* data, size_t n, size_t es); | |
| void _array_free(struct _array* a); | |
| #define _array_es(a) sizeof((a)->data[0]) // element size | |
| #define array_init(a, n) _array_init((struct _array*)(a), n, _array_es(a)) | |
| #define array_free(a) _array_free((struct _array*)(a)) | |
| #define array_grow(a, n) _array_grow((struct _array*)(a), n, _array_es(a)) | |
| #define array_push(a, d, n) _array_push((struct _array*)(a), d, n, _array_es(a)) | |
| bool _array_init(struct _array* a, size_t count, size_t es) { | |
| assert(count <= INT_MAX); | |
| a->count = 0; | |
| a->data = malloc(count * es); | |
| a->capacity = a->data ? (int)count : 0; | |
| return a->data; | |
| } | |
| bool _array_grow(struct _array* a, size_t count, size_t es) { | |
| assert(a->capacity < count && count <= INT_MAX); | |
| assert(a->count <= a->capacity); | |
| void* data = (char*)realloc((void*)a->data, count * es); | |
| if (data) { a->data = data; a->capacity = (int)count; } | |
| return data; | |
| } | |
| bool _array_push(struct _array* a, void* data, size_t n, size_t es) { | |
| assert(n + 1 < INT_MAX - a->count); | |
| size_t c = a->count + n; | |
| if (c >= a->capacity) { | |
| size_t d = a->capacity * 2; // double of capacity | |
| if (!_array_grow(a, c > d ? c : d, es)) { return false; } | |
| } | |
| memcpy(a->data + a->count * es, data, n * es); | |
| a->count += n; | |
| return true; | |
| } | |
| void _array_free(struct _array* a) { | |
| if (a->data) { free(a->data); } | |
| memset(a, 0, sizeof(*a)); | |
| } | |
| /* | |
| struct tuple { | |
| int key; | |
| int val; | |
| }; | |
| struct string array_of(char) | |
| struct tuples array_of(struct tuple) | |
| */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment