X-Git-Url: http://git.droids-corp.org/?a=blobdiff_plain;f=lib%2Fecoli_strvec.c;h=c574b1b63764ea5e79a40198905e3cd17ba484b0;hb=dec2d7fa17ae1e8b3d1dec8e396d057757baf4f3;hp=132183d366654d59163e545667df6f6eb8d4d2a8;hpb=044f2e33e83ec36df6601e3950820d07facde0a7;p=protos%2Flibecoli.git diff --git a/lib/ecoli_strvec.c b/lib/ecoli_strvec.c index 132183d..c574b1b 100644 --- a/lib/ecoli_strvec.c +++ b/lib/ecoli_strvec.c @@ -2,6 +2,7 @@ * Copyright 2016, Olivier MATZ */ +#define _GNU_SOURCE /* qsort_r */ #include #include #include @@ -193,6 +194,24 @@ int ec_strvec_cmp(const struct ec_strvec *strvec1, return 0; } +static int +cmp_vec_elt(const void *p1, const void *p2, void *arg) +{ + int (*str_cmp)(const char *s1, const char *s2) = arg; + const struct ec_strvec_elt * const *e1 = p1, * const *e2 = p2; + + return str_cmp((*e1)->str, (*e2)->str); +} + +void ec_strvec_sort(struct ec_strvec *strvec, + int (*str_cmp)(const char *s1, const char *s2)) +{ + if (str_cmp == NULL) + str_cmp = strcmp; + qsort_r(strvec->vec, ec_strvec_len(strvec), + sizeof(*strvec->vec), cmp_vec_elt, str_cmp); +} + void ec_strvec_dump(FILE *out, const struct ec_strvec *strvec) { size_t i; @@ -354,6 +373,7 @@ static int ec_strvec_testcase(void) testres |= EC_TEST_CHECK(ec_strvec_cmp(strvec, strvec2) == 0, "strvec and strvec2 should be equal\n"); ec_strvec_free(strvec2); + strvec2 = NULL; f = open_memstream(&buf, &buflen); if (f == NULL) @@ -368,6 +388,24 @@ static int ec_strvec_testcase(void) ec_strvec_free(strvec); + strvec = EC_STRVEC("e", "a", "f", "d", "b", "c"); + if (strvec == NULL) { + EC_TEST_ERR("cannot create strvec from array\n"); + goto fail; + } + ec_strvec_sort(strvec, NULL); + strvec2 = EC_STRVEC("a", "b", "c", "d", "e", "f"); + if (strvec2 == NULL) { + EC_TEST_ERR("cannot create strvec from array\n"); + goto fail; + } + testres |= EC_TEST_CHECK(ec_strvec_cmp(strvec, strvec2) == 0, + "strvec and strvec2 should be equal\n"); + ec_strvec_free(strvec); + strvec = NULL; + ec_strvec_free(strvec2); + strvec2 = NULL; + return testres; fail: