-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdynstr.c
55 lines (49 loc) · 1.22 KB
/
dynstr.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "joecc_assert.h"
#include "dynstr.h"
DYNSTR* strctor(char* strptr, int len, int maxlen) {
DYNSTR* retval = malloc(sizeof(DYNSTR));
retval->strptr = strptr;
retval->lenstr = len;
retval->maxlenstr = maxlen;
return retval;
}
void strdtor(DYNSTR* ds) {
free(ds->strptr);
free(ds);
}
void dsmodsize(DYNSTR* ds, int len) {
assert(ds->maxlenstr > 1);
if(ds->maxlenstr < (ds->lenstr += len)) {
while(ds->maxlenstr < ds->lenstr)
ds->maxlenstr *= 1.5;
ds->strptr = realloc(ds->strptr, ds->maxlenstr);
}
}
//dynamic string concatenate
void dscat(DYNSTR* ds, char* txt, int len) {
int lp = ds->lenstr;
dsmodsize(ds, len);
memcpy(ds->strptr + lp, txt, len);
}
//dynamic string concatenate character
void dsccat(DYNSTR* ds, char txt) {
int lp = ds->lenstr;
dsmodsize(ds, 1);
ds->strptr[lp] = txt;
}
void dsws(DYNSTR* ds) { //remove trailing whitespace
if(ds->strptr[ds->lenstr - 1]) { //no null terminator
while(ds->lenstr && isblank(ds->strptr[ds->lenstr - 1])) {
--ds->lenstr;
}
} else {
--ds->lenstr;
while(ds->lenstr && isblank(ds->strptr[ds->lenstr - 1])) {
--ds->lenstr;
}
dsccat(ds, 0);
}
}