Skip to content

Instantly share code, notes, and snippets.

@jstimpfle
Created May 24, 2018 23:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jstimpfle/562b2c3e9fe537e378351bb9d5be8cdb to your computer and use it in GitHub Desktop.
Save jstimpfle/562b2c3e9fe537e378351bb9d5be8cdb to your computer and use it in GitHub Desktop.
C code starting point for getting most of what std::vector offers
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