Skip to content

Commit

Permalink
Add minimal 'dynamic array' library using macros
Browse files Browse the repository at this point in the history
This is a one-file library built on C-macros to declare and use
dynamically allocated, growing arrays, which is most of the data
structures you'll ever need.
  • Loading branch information
bdw committed Aug 28, 2017
1 parent 892aa0b commit 5045cc7
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 0 deletions.
1 change: 1 addition & 0 deletions build/Makefile.in
Expand Up @@ -227,6 +227,7 @@ HEADERS = src/moar.h \
src/core/exceptions.h \
src/core/interp.h \
src/core/alloc.h \
src/core/dynar.h \
src/core/frame.h \
src/core/callstack.h \
src/core/compunit.h \
Expand Down
32 changes: 32 additions & 0 deletions src/core/dynar.h
@@ -0,0 +1,32 @@
/* An as-small-as-possible dynamic array implementation. */
#define MVM_DYNAR_DECL(type, x) type *x; \
size_t x ## _num; \
size_t x ## _alloc;

#define MVM_DYNAR_INIT(x, size) do { \
x = MVM_malloc((size)*sizeof(*x)); \
x ## _num = 0; \
x ## _alloc = (size); \
} while (0)

#define MVM_DYNAR_GROW(x, size) do {\
x = MVM_realloc(x, (size)*sizeof(*x)); \
x ## _alloc = (size); \
} while (0)

#define MVM_DYNAR_ENSURE(x, space) \
if (((x ## _num) + (space)) >= (x ## _alloc)) { \
MVM_DYNAR_GROW(x, (x ## _alloc)*2); \
}

#define MVM_DYNAR_PUSH(x, value) do { \
MVM_DYNAR_ENSURE(x, 1); \
x[x ## _num++] = (value); \
} while(0)

#define MVM_DYNAR_APPEND(x, ar, len) do { \
MVM_DYNAR_ENSURE(x, len); \
memcpy(x + x ## _num, ar, (len) * sizeof(x[0])); \
x ## _num += len; \
} while(0)

1 change: 1 addition & 0 deletions src/moar.h
Expand Up @@ -101,6 +101,7 @@ MVM_PUBLIC const MVMint32 MVM_jit_support(void);
#include "core/args.h"
#include "core/exceptions.h"
#include "core/alloc.h"
#include "core/dynar.h"
#include "core/frame.h"
#include "core/callstack.h"
#include "core/validation.h"
Expand Down

0 comments on commit 5045cc7

Please sign in to comment.