/src/clib/deps/substr/substr.c
Line | Count | Source (jump to first uncovered line) |
1 | | |
2 | | // |
3 | | // substr.c |
4 | | // |
5 | | // Copyright (c) 2013 Stephen Mathieson |
6 | | // MIT licensed |
7 | | // |
8 | | |
9 | | #include <stdlib.h> |
10 | | #include <string.h> |
11 | | #include "strdup/strdup.h" |
12 | | #include "substr.h" |
13 | | |
14 | | /* |
15 | | * Get a substring of `str` from `start` to `end` |
16 | | */ |
17 | | |
18 | | char * |
19 | 4 | substr(const char *str, int start, int end) { |
20 | 4 | if (0 > start) return NULL; |
21 | 4 | int len = strlen(str); |
22 | | // -1 == length of string |
23 | 4 | if (-1 == end) end = len; |
24 | 4 | if (end <= start) return NULL; |
25 | 0 | int diff = end - start; |
26 | 0 | if (len == diff) return strdup(str); |
27 | 0 | if (len < start) return NULL; |
28 | 0 | if (len + 1 < end) return NULL; |
29 | | |
30 | 0 | char *res = malloc(sizeof(char) * diff + 1); |
31 | 0 | if (NULL == res) return NULL; |
32 | 0 | memset(res, '\0', diff + 1); |
33 | 0 | strncpy(res, str + start, diff); |
34 | 0 | return res; |
35 | 0 | } |