1 #if !defined( CSTRING_H )
5 * A implementation of expandable c strings in heap memory.
7 * struct: cstring_t which defines a expandable c string type in heap memory
9 * function: cstring_init to intialize struct of type cstring_t
10 * function: cstring_t->expand to add one character to the string
11 * function: cstring_t->delete to free the allocated memory
14 * cstring_t *p = cstring_init();
15 * (p->expand)(p, 'X');
20 #include <string.h> // strlen
21 #include <stdlib.h> // malloc, realloc
23 // The amount of memory allocated from heap when string expansion hits the
24 // allocated memory limit
25 #define REALLOC_ADD 10
27 typedef struct _cstring_t {
31 void (*expand)(struct _cstring_t *self, char x);
32 void (*expand_arr)(struct _cstring_t *self, char *x);
33 void (*delete)(struct _cstring_t *self);
36 void cstring_expand(cstring_t *self, char x);
37 void cstring_expand_arr(cstring_t *self, char *x);
38 void cstring_delete(cstring_t *self);
40 cstring_t *cstring_init() {
41 cstring_t *x = malloc(sizeof(cstring_t));
43 x->size = x->alloc = 0;
44 x->expand = cstring_expand;
45 x->expand_arr = cstring_expand_arr;
46 x->delete = cstring_delete;
50 void cstring_expand(cstring_t *self, char x) {
51 if(self->size + sizeof(x) + sizeof(char) > self->alloc) {
52 self->alloc += (REALLOC_ADD * sizeof(char));
53 self->text = realloc(self->text, self->alloc);
55 self->text[self->size] = x;
56 self->text[self->size+1] = '\0';
57 self->size = strlen(self->text);
60 void cstring_expand_arr(cstring_t *self, char *x) {
61 if(self->size + strlen(x) + sizeof(char) > self->alloc) {
62 self->alloc += (REALLOC_ADD * sizeof(char));
63 self->text = realloc(self->text, self->alloc);
65 self->text = strcat(self->text, x);
66 self->size = strlen(self->text);
70 void cstring_delete(cstring_t *self) {
75 #endif // !defined( CSTRING_H )