Added config.h, miscfn.h header files
[platform/upstream/rpm.git] / lib / stringbuf.c
1 #include "config.h"
2
3 #include <stdlib.h>
4 #include <ctype.h>
5 #include <string.h>
6
7 #include "miscfn.h"
8 #include "stringbuf.h"
9
10 #define BUF_CHUNK 1024
11
12 struct StringBufRec {
13     char *buf;
14     char *tail;     /* Points to first "free" char (usually '\0') */
15     int allocated;
16     int free;
17 };
18
19 StringBuf newStringBuf(void)
20 {
21     StringBuf sb = malloc(sizeof(struct StringBufRec));
22
23     sb->buf = malloc(BUF_CHUNK * sizeof(char));
24     sb->buf[0] = '\0';
25     sb->tail = sb->buf;
26     sb->allocated = BUF_CHUNK;
27     sb->free = BUF_CHUNK;
28     
29     return sb;
30 }
31
32 void freeStringBuf(StringBuf sb)
33 {
34     free(sb->buf);
35     free(sb);
36 }
37
38 void truncStringBuf(StringBuf sb)
39 {
40     sb->buf[0] = '\0';
41     sb->tail = sb->buf;
42     sb->free = sb->allocated;
43 }
44
45 void stripTrailingBlanksStringBuf(StringBuf sb)
46 {
47     while (sb->free != sb->allocated) {
48         if (! isspace(*(sb->tail - 1))) {
49             break;
50         }
51         sb->free++;
52         sb->tail--;
53     }
54     sb->tail[0] = '\0';
55 }
56
57 char *getStringBuf(StringBuf sb)
58 {
59     return sb->buf;
60 }
61
62 void appendStringBufAux(StringBuf sb, char *s, int nl)
63 {
64     int l;
65
66     l = strlen(s);
67     /* If free == l there is no room for NULL terminator! */
68     while ((l + nl + 1) > sb->free) {
69         sb->allocated += BUF_CHUNK;
70         sb->free += BUF_CHUNK;
71         sb->buf = realloc(sb->buf, sb->allocated);
72         sb->tail = sb->buf + (sb->allocated - sb->free);
73     }
74     
75     strcpy(sb->tail, s);
76     sb->tail += l;
77     sb->free -= l;
78     if (nl) {
79         sb->tail[0] = '\n';
80         sb->tail[1] = '\0';
81         sb->tail++;
82         sb->free--;
83     }
84 }