initial import for sdlhaa & sdlhim
[sdlhildon] / sdlhim / src / ds.c
1 /* This file is part of SDL_him - SDL Hildon Input Method addon
2  * Copyright (C) 2010 Javier S. Pedro
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 3 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the
16  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17  * Boston, MA 02111-1307, USA or see <http://www.gnu.org/licenses/>.
18  */
19
20 #include <stdlib.h>
21 #include <string.h>
22 #include "ds.h"
23
24 /* This could be better. */
25
26 #define CAPACITY_MARGIN 10
27
28 void ds_clear(dstring_t *ds)
29 {
30         free(ds->str);
31         ds->capacity = CAPACITY_MARGIN;
32         ds->str = malloc(ds->capacity + 1);
33         ds->len = 0;
34         ds->str[ds->len] = '\0';
35 }
36
37 void ds_set(dstring_t *ds, const char *str)
38 {
39         if (!str) {
40                 /* Clean the string, but don't reallocate capacity. */
41                 ds->len = 0;
42                 if (ds->capacity > 0) {
43                         ds->str[0] = '\0';
44                 }
45                 return;
46         }
47
48         const size_t len = strlen(str);
49
50         if (ds->capacity < len) {
51                 free(ds->str);
52                 ds->capacity = len + CAPACITY_MARGIN;
53                 ds->str = malloc(ds->capacity + 1);
54         }
55
56         strcpy(ds->str, str);
57         ds->len = len;
58 }
59
60 void ds_append(dstring_t *ds, const char *str)
61 {
62         if (!str) return;
63         const size_t len = strlen(str);
64         const size_t new_len = ds->len + len;
65
66         if (ds->capacity < new_len) {
67                 ds->capacity = new_len + CAPACITY_MARGIN;
68                 ds->str = realloc(ds->str, ds->capacity + 1);
69         }
70
71         strcpy(&ds->str[ds->len], str);
72         ds->len = new_len;
73 }
74