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