Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add minimal 'dynamic array' library using macros
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
Showing
3 changed files
with
34 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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) | ||
|
This file contains 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