strbuffer: Optimize string termination
[profile/ivi/jansson.git] / src / strbuffer.c
1 #define _GNU_SOURCE
2 #include <stdlib.h>
3 #include <string.h>
4 #include "strbuffer.h"
5 #include "util.h"
6
7 #define STRBUFFER_MIN_SIZE  16
8 #define STRBUFFER_FACTOR    2
9
10 int strbuffer_init(strbuffer_t *strbuff)
11 {
12     strbuff->size = STRBUFFER_MIN_SIZE;
13     strbuff->length = 0;
14
15     strbuff->value = malloc(strbuff->size);
16     if(!strbuff->value)
17         return -1;
18
19     /* initialize to empty */
20     strbuff->value[0] = '\0';
21     return 0;
22 }
23
24 void strbuffer_close(strbuffer_t *strbuff)
25 {
26     free(strbuff->value);
27     strbuff->size = 0;
28     strbuff->length = 0;
29     strbuff->value = NULL;
30 }
31
32 const char *strbuffer_value(strbuffer_t *strbuff)
33 {
34     return strbuff->value;
35 }
36
37 char *strbuffer_steal_value(strbuffer_t *strbuff)
38 {
39     char *result = strbuff->value;
40     strbuffer_init(strbuff);
41     return result;
42 }
43
44 int strbuffer_append(strbuffer_t *strbuff, const char *string)
45 {
46     return strbuffer_append_bytes(strbuff, string, strlen(string));
47 }
48
49 int strbuffer_append_bytes(strbuffer_t *strbuff, const char *data, int size)
50 {
51     if(strbuff->length + size >= strbuff->size)
52     {
53         strbuff->size = max(strbuff->size * STRBUFFER_FACTOR,
54                             strbuff->length + size + 1);
55
56         strbuff->value = realloc(strbuff->value, strbuff->size);
57         if(!strbuff->value)
58             return -1;
59     }
60
61     memcpy(strbuff->value + strbuff->length, data, size);
62     strbuff->length += size;
63     strbuff->value[strbuff->length] = '\0';
64
65     return 0;
66 }