Skip to content

Add macro nob_da_swap to swap elements in a dynamic array #61

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions nob.c
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ const char *test_names[] = {
"read_entire_dir",
"da_resize",
"da_last",
"da_swap",
"da_remove_unordered",
"da_append",
"sb_appendf",
Expand Down
12 changes: 12 additions & 0 deletions nob.h
Original file line number Diff line number Diff line change
Expand Up @@ -321,6 +321,17 @@ bool nob_delete_file(const char *path);
(da)->items[j] = (da)->items[--(da)->count]; \
} while(0)

#define nob_da_swap(da, i, j) \
do { \
size_t ii = (i); \
size_t jj = (j); \
NOB_ASSERT(ii < (da)->count); \
NOB_ASSERT(jj < (da)->count); \
nob_da_append((da), (da)->items[ii]); \
(da)->items[ii] = (da)->items[jj]; \
(da)->items[jj] = (da)->items[--((da)->count)]; \
} while(0)

// Foreach over Dynamic Arrays. Example:
// ```c
// typedef struct {
Expand Down Expand Up @@ -1927,6 +1938,7 @@ int closedir(DIR *dirp)
#define da_reserve nob_da_reserve
#define da_last nob_da_last
#define da_remove_unordered nob_da_remove_unordered
#define da_swap nob_da_swap
#define da_foreach nob_da_foreach
#define String_Builder Nob_String_Builder
#define read_entire_file nob_read_entire_file
Expand Down
19 changes: 19 additions & 0 deletions tests/da_swap.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
#define NOB_IMPLEMENTATION
#define NOB_STRIP_PREFIX
#include "nob.h"

typedef struct {
int *items;
size_t count;
size_t capacity;
} Numbers;

int main(void)
{
nob_log(INFO, "da_swap:");
Numbers xs = {0};
for (int i = 1; i <= 10; ++i) da_append(&xs, i);
for (int i = 0; i < 5; ++i) da_swap(&xs, i, xs.count - i - 1);
for (int i = 0; i < 10; ++i) nob_log(INFO, "%d", xs.items[i]);
return 0;
}