/src/clib/deps/str-flatten/str-flatten.c
Line | Count | Source (jump to first uncovered line) |
1 | | |
2 | | // |
3 | | // str-flatten.c |
4 | | // |
5 | | // Copyright (c) 2014 Stephen Mathieson |
6 | | // MIT licensed |
7 | | // |
8 | | |
9 | | #include <stdlib.h> |
10 | | #include <string.h> |
11 | | #include "str-flatten.h" |
12 | | |
13 | | char * |
14 | 0 | str_flatten(const char *array[], int start, int end) { |
15 | 0 | int count = end - start; |
16 | 0 | size_t lengths[count]; |
17 | 0 | size_t size = 0; |
18 | 0 | size_t pos = 0; |
19 | |
|
20 | 0 | for (int i = start, j = 0; i < end; ++i, ++j) { |
21 | 0 | lengths[j] = strlen(array[i]); |
22 | 0 | size += lengths[j]; |
23 | 0 | } |
24 | |
|
25 | 0 | char *str = malloc(size + count); |
26 | 0 | str[size + count - 1] = '\0'; |
27 | |
|
28 | 0 | for (int i = start, j = 0; i < (end - 1); ++i, ++j) { |
29 | 0 | memcpy(str + pos + j |
30 | | // current index |
31 | 0 | , array[i] |
32 | | // current index length |
33 | 0 | , lengths[j]); |
34 | | // add space |
35 | 0 | str[pos + lengths[j] + j] = ' '; |
36 | | // bump `pos` |
37 | 0 | pos += lengths[j]; |
38 | 0 | } |
39 | |
|
40 | 0 | memcpy(str + pos + count - 1 |
41 | 0 | , array[end - 1] |
42 | 0 | , lengths[count - 1]); |
43 | |
|
44 | 0 | return str; |
45 | 0 | } |