Skip to content

Commit

Permalink
Make xstrjoin accept arbitrarily many arguments
Browse files Browse the repository at this point in the history
  • Loading branch information
mahkoh committed Jul 31, 2016
1 parent 7846f67 commit 97ee376
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 9 deletions.
10 changes: 10 additions & 0 deletions utils.h
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,16 @@

#define N_ELEMENTS(array) (sizeof(array) / sizeof((array)[0]))

struct slice {
void *ptr;
size_t len;
};

#define TO_SLICE(type, ...) ((struct slice) { \
.ptr = ((type[]){__VA_ARGS__}), \
.len = N_ELEMENTS(((type[]){__VA_ARGS__})), \
})

#define STRINGIZE_HELPER(x) #x
#define STRINGIZE(x) STRINGIZE_HELPER(x)

Expand Down
28 changes: 20 additions & 8 deletions xstrjoin.c
Original file line number Diff line number Diff line change
Expand Up @@ -18,17 +18,29 @@

#include "xstrjoin.h"
#include "xmalloc.h"
#include "string.h"
#include "utils.h"

char *xstrjoin(const char *a, const char *b)
char *xstrjoin_slice(struct slice slice)
{
int a_len, b_len;
const char **str = slice.ptr;
size_t i, pos = 0, len = 0;
char *joined;
size_t *lens;

lens = xnew(size_t, slice.len);
for (i = 0; i < slice.len; i++) {
lens[i] = strlen(str[i]);
len += lens[i];
}

joined = xnew(char, len + 1);
for (i = 0; i < slice.len; i++) {
memcpy(joined + pos, str[i], lens[i]);
pos += lens[i];
}
joined[len] = 0;

free(lens);

a_len = strlen(a);
b_len = strlen(b);
joined = xnew(char, a_len + b_len + 1);
memcpy(joined, a, a_len);
memcpy(joined + a_len, b, b_len + 1);
return joined;
}
5 changes: 4 additions & 1 deletion xstrjoin.h
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@
#ifndef CMUS_XSTRJOIN_H
#define CMUS_XSTRJOIN_H

char *xstrjoin(const char *a, const char *b);
#include "utils.h"

char *xstrjoin_slice(struct slice);
#define xstrjoin(...) xstrjoin_slice(TO_SLICE(const char *, __VA_ARGS__))

#endif

0 comments on commit 97ee376

Please sign in to comment.