Differences From
Artifact [5d94fe752b]:
7 7 * compose.c contains some useful string utilities
8 8 * that libc lacks.
9 9
10 10 TODO add macro to use homebrew strlen instead of
11 11 dragging in <string.h> */
12 12
13 13 #ifdef k_header // only emit the declarations
14 -# define fn(x)
14 +# define k_impl(x)
15 15 #else
16 -# define fn(x) x
16 +# define k_impl(x) x
17 17 #endif
18 18
19 19 #include <string.h>
20 20
21 21 typedef struct pstr { size_t len; union {
22 22 const char* ptr;
23 23 char* mutptr;
................................................................................
32 32 # ifndef k_static
33 33 bool heap;
34 34 # endif
35 35 size_t len;
36 36 } safestr;
37 37
38 38 #ifndef k_static
39 - void delstr(safestr s) fn ({
39 + void delstr(safestr s) k_impl ({
40 40 if (s.heap) { free(s.mutptr); }
41 41 });
42 42 #endif
43 43
44 -void clrstr(safestr* s) fn ({
44 +void clrstr(safestr* s) k_impl ({
45 45 # ifndef k_static
46 46 delstr(*s);
47 47 s->heap = false;
48 48 # endif
49 49 s->ptr = NULL;
50 50 s->len = 0;
51 51 })
52 52
53 -size_t pstrsum(pstr* lst,size_t ct) fn({
53 +size_t pstrsum(pstr* lst,size_t ct) k_impl ({
54 54 size_t len = 0;
55 55 for (size_t i = 0; i < ct; ++i) {
56 56 if (lst[i].len == 0) {
57 57 if (lst[i].ptr == NULL) continue;
58 58 lst[i].len = strlen(lst[i].ptr);
59 59 }
60 60 len += lst[i].len;
61 61 }
62 62 return len;
63 63 })
64 64
65 -char* pstrcoll(pstr* lst, size_t ct, char* ptr) fn({
65 +char* pstrcoll(pstr* lst, size_t ct, char* ptr) k_impl ({
66 66 for (size_t i = 0; i < ct; ++i) {
67 67 if (lst[i].len == 0) continue;
68 68 strncpy(ptr,lst[i].ptr,lst[i].len);
69 69 ptr += lst[i].len;
70 70 }
71 71 return ptr;
72 72 })
73 73
74 74 #ifndef k_static
75 -char* compose(pstr* lst,size_t ct, size_t* strsz) fn({
75 +char* compose(pstr* lst,size_t ct, size_t* strsz) k_impl ({
76 76 size_t len = pstrsum(lst,ct)
77 77 if (strsz != NULL) *strsz = len;
78 78 if (len == 0) return NULL;
79 79
80 80 char* str = malloc(len + 1);
81 81 char* ptr = pstrcoll(lst, ct, ptr);
82 82 *ptr = 0;
83 83 return str;
84 84 });
85 85 #endif
86 86
87 -char* impose(pstr* lst,size_t ct, size_t* strsz, char* buf) fn({
87 +char* impose(pstr* lst,size_t ct, size_t* strsz, char* buf) k_impl({
88 88 size_t len = pstrsum(lst,ct);
89 89 if (strsz != NULL) *strsz = len;
90 90 if (len == 0) return NULL;
91 91
92 92 char* ptr = pstrcoll(lst, ct, buf);
93 93 *ptr = 0;
94 94 return ptr;
95 95 });
96 96
97 -char* imprint(pstr lst, size_t* strsz, char* buf) fn({
97 +char* imprint(pstr lst, size_t* strsz, char* buf) k_impl({
98 98 size_t len = pstrsum(&lst,1);
99 99 if (strsz != NULL) *strsz = len;
100 100 if (len == 0) return NULL;
101 101
102 102 char* ptr = pstrcoll(&lst,1,buf);
103 103 *ptr = 0;
104 104 return ptr;
105 105 });
106 -#undef fn
106 +#undef k_impl