diff options
Diffstat (limited to 'sway/stringop.c')
-rw-r--r-- | sway/stringop.c | 39 |
1 files changed, 39 insertions, 0 deletions
diff --git a/sway/stringop.c b/sway/stringop.c index 1dff97bf..c39e2c34 100644 --- a/sway/stringop.c +++ b/sway/stringop.c | |||
@@ -4,6 +4,7 @@ | |||
4 | #include "string.h" | 4 | #include "string.h" |
5 | #include "list.h" | 5 | #include "list.h" |
6 | #include <strings.h> | 6 | #include <strings.h> |
7 | #include <log.h> | ||
7 | 8 | ||
8 | /* Note: This returns 8 characters for trimmed_start per tab character. */ | 9 | /* Note: This returns 8 characters for trimmed_start per tab character. */ |
9 | char *strip_whitespace(char *_str, int *trimmed_start) { | 10 | char *strip_whitespace(char *_str, int *trimmed_start) { |
@@ -197,3 +198,41 @@ char *join_args(char **argv, int argc) { | |||
197 | res[len - 1] = '\0'; | 198 | res[len - 1] = '\0'; |
198 | return res; | 199 | return res; |
199 | } | 200 | } |
201 | |||
202 | /* | ||
203 | * Join a list of strings, adding separator in between. Separator can be NULL. | ||
204 | */ | ||
205 | char *join_list(list_t *list, char *separator) { | ||
206 | if (!sway_assert(list != NULL, "list != NULL") || list->length == 0) { | ||
207 | return NULL; | ||
208 | } | ||
209 | |||
210 | size_t len = 1; // NULL terminator | ||
211 | size_t sep_len = 0; | ||
212 | if (separator != NULL) { | ||
213 | sep_len = strlen(separator); | ||
214 | len += (list->length - 1) * sep_len; | ||
215 | } | ||
216 | |||
217 | for (int i = 0; i < list->length; i++) { | ||
218 | len += strlen(list->items[i]); | ||
219 | } | ||
220 | |||
221 | char *res = malloc(len); | ||
222 | |||
223 | char *p = res + strlen(list->items[0]); | ||
224 | strcpy(res, list->items[0]); | ||
225 | |||
226 | for (int i = 1; i < list->length; i++) { | ||
227 | if (sep_len) { | ||
228 | memcpy(p, separator, sep_len); | ||
229 | p += sep_len; | ||
230 | } | ||
231 | strcpy(p, list->items[i]); | ||
232 | p += strlen(list->items[i]); | ||
233 | } | ||
234 | |||
235 | *p = '\0'; | ||
236 | |||
237 | return res; | ||
238 | } | ||