Skip to content

Commit

Permalink
mx_util: Add mx_strconcat()
Browse files Browse the repository at this point in the history
  • Loading branch information
mariux committed Oct 27, 2015
1 parent 5f69404 commit 5f9fbac
Show file tree
Hide file tree
Showing 3 changed files with 66 additions and 0 deletions.
41 changes: 41 additions & 0 deletions mx_util.c
Original file line number Diff line number Diff line change
Expand Up @@ -856,6 +856,47 @@ int mx_strscan_ll(char **str, long long int *to)
return res;
}

char *_mx_strconcat_do(char *first, ...)
{
va_list ap;
char *join = NULL;
char *str;
char *ptr;
size_t len;

if (!first) {
join = strdup("");
return join;
}

len = strlen(first);

va_start(ap, first);
do {
str = va_arg(ap, char *);
if (!str)
break;
len += strlen(str);
} while(1);
va_end(ap);

join = malloc(len+1);
if (!join)
return NULL;

ptr = stpcpy(join, first);
va_start(ap, first);
do {
str = va_arg(ap, char *);
if (!str)
break;
ptr = stpcpy(ptr, str);
} while(1);
va_end(ap);

return join;
}

int mx_sleep(unsigned int seconds)
{
if (seconds)
Expand Down
3 changes: 3 additions & 0 deletions mx_util.h
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,9 @@ int mx_read_first_line_from_file(char *fname, char **line);
int mx_strscan_ull(char **str, unsigned long long int *to);
int mx_strscan_ll(char **str, long long int *to);

char *_mx_strconcat_do(char *first, ...);
#define mx_strconcat(s, ...) _mx_strconcat_do((s), ##__VA_ARGS__, NULL)

int mx_sleep(unsigned int seconds);
int mx_sleep_nofail(unsigned int seconds);

Expand Down
22 changes: 22 additions & 0 deletions test_mx_util.c
Original file line number Diff line number Diff line change
Expand Up @@ -384,6 +384,27 @@ static void test_mx_strvec() {
mx_strvec_free(strvec);
}

static void test_mx_strcat() {
char *str;
char *str2;

assert(str = mx_strconcat(NULL));
assert(mx_streq(str, ""));
mx_free_null(str);

assert(str = mx_strconcat("abc", "123"));
assert(mx_streq(str, "abc123"));

assert(str2 = mx_strconcat(str, "def", str, "456"));
assert(mx_streq(str2, "abc123defabc123456"));
mx_free_null(str2);

assert(str2 = mx_strconcat(str));
assert(mx_streq(str, str2));
mx_free_null(str);
mx_free_null(str2);
}

static void test_mx_cpuset(void)
{
cpu_set_t cpuset;
Expand Down Expand Up @@ -421,6 +442,7 @@ int main(int argc, char *argv[])
test_mx_read_first_line_from_file();
test_mx_strscan();
test_mx_strvec();
test_mx_strcat();
test_mx_cpuset();
return 0;
}

0 comments on commit 5f9fbac

Please sign in to comment.