]> git.lizzy.rs Git - nothing.git/blob - src/system/str.c
60016b0339d5f5aeac5eb793f441b574b1d80b19
[nothing.git] / src / system / str.c
1 #include "system/stacktrace.h"
2 #include <stdlib.h>
3 #include <stdio.h>
4 #include <string.h>
5 #include "system/stacktrace.h"
6
7 #include "str.h"
8 #include "system/nth_alloc.h"
9
10 char *string_duplicate(const char *str,
11                        const char *str_end)
12 {
13     trace_assert(str);
14
15     if (str_end != NULL && str > str_end) {
16         return NULL;
17     }
18
19     const size_t n = str_end == NULL ? strlen(str) : (size_t) (str_end - str);
20     char *dup_str = nth_calloc(1, sizeof(char) * (n + 1));
21     if (dup_str == NULL) {
22         return NULL;
23     }
24
25     memcpy(dup_str, str, n);
26     dup_str[n] = '\0';
27
28     return dup_str;
29 }
30
31 char *trim_endline(char *s)
32 {
33     const size_t n = strlen(s);
34
35     if (n == 0) {
36         return s;
37     }
38
39     if (s[n - 1] == '\n') {
40         s[n - 1] = '\0';
41     }
42
43     return s;
44 }
45
46 char *string_append(char *prefix, const char *suffix)
47 {
48     trace_assert(suffix);
49
50     if (prefix == NULL) {
51         return string_duplicate(suffix, NULL);
52     }
53
54     prefix = nth_realloc(prefix, strlen(prefix) + strlen(suffix) + 1);
55     return strcat(prefix, suffix);
56 }