Created
May 24, 2018 23:25
-
-
Save jstimpfle/562b2c3e9fe537e378351bb9d5be8cdb to your computer and use it in GitHub Desktop.
C code starting point for getting most of what std::vector offers
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
static void _buf_init(void **buf, int *cap, int elsize, const char *file, const int line) | |
{ | |
fprintf(stderr, "_buf_init(%p, %s, %d)\n", buf, file, line); | |
*buf = NULL; | |
*cap = 0; | |
} | |
static void _buf_reserve(void **buf, int *cap, int cnt, int elsize, const char *file, const int line) | |
{ | |
fprintf(stderr, "_buf_reserve(%p, %s, %d)\n", buf, file, line); | |
void *ptr; | |
if (*cap >= cnt) | |
return; | |
cnt = 2*cnt - 1; while (cnt & (cnt-1)) cnt = cnt & (cnt-1); | |
ptr = realloc(*buf, cnt * elsize); | |
if (!ptr) | |
fatal("OOM!"); | |
*buf = ptr; | |
} | |
static void _buf_exit(void **buf, int *cap, int elsize, const char *file, const int line) | |
{ | |
fprintf(stderr, "_buf_exit(%p, %s, %d)\n", buf, file, line); | |
free(*buf); | |
*buf = NULL; | |
*cap = 0; | |
} | |
#define BUF_INIT(buf, cap) _buf_init((void**)&(buf), &(cap), sizeof(*(buf)), __FILE__, __LINE__); | |
#define BUF_RESERVE(buf, cap, cnt) _buf_reserve((void**)&(buf), &(cap), (cnt), sizeof(*(buf)), __FILE__, __LINE__); | |
#define BUF_EXIT(buf, cap) _buf_exit((void**)&(buf), &(cap), sizeof(*(buf)), __FILE__, __LINE__); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment