X-Git-Url: https://git.danieliu.xyz/?a=blobdiff_plain;f=src%2Fcstring.c;h=558a78662bc29aa2a68859a58f1d0b01e20ec171;hb=417496b57b4e4cbbee620d054fe26becff5d736d;hp=59c549cf3f5a50657342a3c1de35f12b18e033b9;hpb=a10fcae3cba4f58550b24b0029f3932615dadbc3;p=smdp.git diff --git a/src/cstring.c b/src/cstring.c index 59c549c..558a786 100644 --- a/src/cstring.c +++ b/src/cstring.c @@ -19,26 +19,36 @@ * */ -#include // strlen +#include // strlen, memmove +#include // fprintf #include // malloc, realloc #include "cstring.h" cstring_t *cstring_init() { - cstring_t *x = malloc(sizeof(cstring_t)); - x->text = (void*)0; - x->size = x->alloc = 0; - x->expand = cstring_expand; - x->expand_arr = cstring_expand_arr; - x->reset = cstring_reset; - x->delete = cstring_delete; + cstring_t *x = NULL; + if((x = malloc(sizeof(cstring_t))) != NULL) { + x->text = NULL; + x->size = x->alloc = 0; + x->expand = cstring_expand; + x->expand_arr = cstring_expand_arr; + x->strip = cstring_strip; + x->reset = cstring_reset; + x->delete = cstring_delete; + } else { + fprintf(stderr, "%s\n", "cstring_init() failed to allocate memory."); + exit(EXIT_FAILURE); + } return x; } void cstring_expand(cstring_t *self, char x) { if(self->size + sizeof(x) + sizeof(char) > self->alloc) { self->alloc += (REALLOC_ADD * sizeof(char)); - self->text = realloc(self->text, self->alloc); + if((self->text = realloc(self->text, self->alloc)) == NULL) { + fprintf(stderr, "%s\n", "cstring_expand() failed to reallocate memory."); + exit(EXIT_FAILURE); + } } self->text[self->size] = x; self->text[self->size+1] = '\0'; @@ -48,16 +58,31 @@ void cstring_expand(cstring_t *self, char x) { void cstring_expand_arr(cstring_t *self, char *x) { if(self->size + strlen(x) + sizeof(char) > self->alloc) { self->alloc = ((strlen(x) + self->size + 1) * sizeof(char)); - self->text = realloc(self->text, self->alloc); + if((self->text = realloc(self->text, self->alloc)) == NULL) { + fprintf(stderr, "%s\n", "cstring_expand() failed to reallocate memory."); + exit(EXIT_FAILURE); + } } self->text = strcat(self->text, x); self->size = strlen(self->text); self->text[self->size+1] = '\0'; } +void cstring_strip(cstring_t *self, int pos, int len) { + if(pos + len >= self->size) { + if(pos <= self->size) { + self->text[pos] = '\0'; + self->size = pos; + } + return; + } + memmove(&self->text[pos], &self->text[pos+len], self->size - pos - len+1); + self->size -= len; +} + void cstring_reset(cstring_t *self) { free(self->text); - self->text = (void*)0; + self->text = NULL; self->size = self->alloc = 0; }