small readme changes
[smdp.git] / cstring.c
1 /*
2  * An implementation of expandable c strings in heap memory.
3  * Copyright (C) 2014 Michael Goehler
4  *
5  * This file is part of mdp.
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation, either version 3 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program. If not, see <http://www.gnu.org/licenses/>.
19  *
20  */
21
22 #include <string.h> // strlen
23 #include <stdlib.h> // malloc, realloc
24
25 #include "include/cstring.h"
26
27 cstring_t *cstring_init() {
28     cstring_t *x = malloc(sizeof(cstring_t));
29     x->text = (void*)0;
30     x->size = x->alloc = 0;
31     x->expand = cstring_expand;
32     x->expand_arr = cstring_expand_arr;
33     x->reset = cstring_reset;
34     x->delete = cstring_delete;
35     return x;
36 }
37
38 void cstring_expand(cstring_t *self, char x) {
39     if(self->size + sizeof(x) + sizeof(char) > self->alloc) {
40         self->alloc += (REALLOC_ADD * sizeof(char));
41         self->text = realloc(self->text, self->alloc);
42     }
43     self->text[self->size] = x;
44     self->text[self->size+1] = '\0';
45     self->size = strlen(self->text);
46 }
47
48 void cstring_expand_arr(cstring_t *self, char *x) {
49     if(self->size + strlen(x) + sizeof(char) > self->alloc) {
50         self->alloc += (REALLOC_ADD * sizeof(char));
51         self->text = realloc(self->text, self->alloc);
52     }
53     self->text = strcat(self->text, x);
54     self->size = strlen(self->text);
55 }
56
57 void cstring_reset(cstring_t *self) {
58     free(self->text);
59     self->text = (void*)0;
60     self->size = self->alloc = 0;
61 }
62
63 void cstring_delete(cstring_t *self) {
64     free(self->text);
65     free(self);
66 }
67