reset function for cstrings
[smdp.git] / include / cstring.h
1 #if !defined( CSTRING_H )
2 #define CSTRING_H
3
4 /*
5  * A implementation of expandable c strings in heap memory.
6  *
7  * struct: cstring_t which defines a expandable c string type in heap memory
8  *
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
12  *
13  * Example:
14  *      cstring_t *p = cstring_init();
15  *      (p->expand)(p, 'X');
16  *      (p->delete)(p);
17  *
18  */
19
20 #include <string.h> // strlen
21 #include <stdlib.h> // malloc, realloc
22
23 // The amount of memory allocated from heap when string expansion hits the
24 // allocated memory limit
25 #define REALLOC_ADD 10
26
27 typedef struct _cstring_t {
28     char *text;
29     size_t size;
30     size_t alloc;
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);
35 } cstring_t;
36
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);
41
42 cstring_t *cstring_init() {
43     cstring_t *x = malloc(sizeof(cstring_t));
44     x->text = (void*)0;
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;
50     return x;
51 }
52
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);
57     }
58     self->text[self->size] = x;
59     self->text[self->size+1] = '\0';
60     self->size = strlen(self->text);
61 }
62
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);
67     }
68     self->text = strcat(self->text, x);
69     self->size = strlen(self->text);
70 }
71
72 void cstring_reset(cstring_t *self) {
73     free(self->text);
74     self->text = (void*)0;
75     self->size = self->alloc = 0;
76 }
77
78 void cstring_delete(cstring_t *self) {
79     free(self->text);
80     free(self);
81 }
82
83 #endif // !defined( CSTRING_H )