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 (*reset)(struct _cstring_t *self);
34 void (*delete)(struct _cstring_t *self);
37 void cstring_expand(cstring_t *self, char x);
38 void cstring_expand_arr(cstring_t *self, char *x);
39 void cstring_reset(cstring_t *self);
40 void cstring_delete(cstring_t *self);
42 cstring_t *cstring_init() {
43 cstring_t *x = malloc(sizeof(cstring_t));
45 x->size = x->alloc = 0;
46 x->expand = cstring_expand;
47 x->expand_arr = cstring_expand_arr;
48 x->reset = cstring_reset;
49 x->delete = cstring_delete;
53 void cstring_expand(cstring_t *self, char x) {
54 if(self->size + sizeof(x) + sizeof(char) > self->alloc) {
55 self->alloc += (REALLOC_ADD * sizeof(char));
56 self->text = realloc(self->text, self->alloc);
58 self->text[self->size] = x;
59 self->text[self->size+1] = '\0';
60 self->size = strlen(self->text);
63 void cstring_expand_arr(cstring_t *self, char *x) {
64 if(self->size + strlen(x) + sizeof(char) > self->alloc) {
65 self->alloc += (REALLOC_ADD * sizeof(char));
66 self->text = realloc(self->text, self->alloc);
68 self->text = strcat(self->text, x);
69 self->size = strlen(self->text);
72 void cstring_reset(cstring_t *self) {
74 self->text = (void*)0;
75 self->size = self->alloc = 0;
78 void cstring_delete(cstring_t *self) {
83 #endif // !defined( CSTRING_H )