From 808d5506ce033fee5b1e8b002e9d47a92355a582 Mon Sep 17 00:00:00 2001 From: Louis Burda Date: Sat, 3 Jun 2023 02:39:38 +0200 Subject: Add strvec_join and strvec_remove_str --- src/strvec.c | 63 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) (limited to 'src') diff --git a/src/strvec.c b/src/strvec.c index 296dccf..e668e35 100644 --- a/src/strvec.c +++ b/src/strvec.c @@ -203,6 +203,69 @@ strvec_remove(struct strvec *strvec, size_t index, size_t count) dvec_rm(&strvec->vec, index, count); } +int +strvec_remove_str(struct strvec *strvec, const char *str, + const struct allocator *allocator) +{ + const char **ent; + size_t i; + int rc; + + LIBSTRVEC_ABORT_ON_ARGS(!strvec); + + for (i = 0; i < strvec->vec.len; ) { + ent = strvec_at(strvec, i); + if (!str && !*ent || !strcmp(str, *ent)) { + if (allocator) { + rc = allocator->free(allocator, (char *) *ent); + if (rc) return -rc; + } + strvec_remove(strvec, i, 1); + } else { + i++; + } + } + + return 0; +} + +char * +strvec_join(struct strvec *strvec, const char *sep, + const struct allocator *allocator, int *_rc) +{ + const char **ent; + size_t len, seplen; + char *str; + + seplen = strlen(sep); + + len = 0; + for (STRVEC_ITER(strvec, ent)) { + if (!*ent) continue; + if (len) len += seplen; + len += strlen(*ent); + } + + str = allocator->alloc(allocator, len + 1, _rc); + if (!str && _rc) *_rc = -*_rc; + if (!str) return NULL; + + len = 0; + for (STRVEC_ITER(strvec, ent)) { + if (!*ent) continue; + + if (len) { + strcpy(str + len, sep); + len += seplen; + } + + strcpy(str + len, *ent); + len += strlen(*ent); + } + + return str; +} + const char ** strvec_iter_fwd(const struct strvec *strvec, const char **p) { -- cgit v1.2.3-71-gd317