-
Notifications
You must be signed in to change notification settings - Fork 0
/
stringbuf.c
113 lines (103 loc) · 2.39 KB
/
stringbuf.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
/* stringbuf.c */
#include "stringbuf.h"
#include <stdlib.h>
#include <string.h>
void init_stringbuf(stringbuf* pbuf)
{
pbuf->buffer = malloc(20);
pbuf->buffer[0] = 0; /* make empty string */
pbuf->used = 0;
pbuf->size = 20;
}
void destroy_stringbuf(stringbuf* pbuf)
{
free(pbuf->buffer);
pbuf->buffer = NULL;
pbuf->used = 0;
pbuf->size = 0;
}
void grow_stringbuf(stringbuf* pbuf)
{
int newsz;
newsz = pbuf->size * 2;
if (newsz > 1) {
int i;
char* pnew;
pnew = malloc(newsz);
for (i = 0;i<pbuf->used;i++)
pnew[i] = pbuf->buffer[i];
pnew[i] = 0;
free(pbuf->buffer);
pbuf->buffer = pnew;
pbuf->size = newsz;
}
}
void assign_stringbuf(stringbuf* pbuf,const char* str)
{
/* include null character */
int sz;
sz = strlen(str);
while (sz >= pbuf->size)
grow_stringbuf(pbuf);
strcpy(pbuf->buffer,str);
pbuf->used = sz;
}
void assign_stringbuf_ex(stringbuf* pbuf,const char* str,int n)
{
int sz = 0;
while (sz<n && str[sz])
++sz;
n = sz;
while (sz >= pbuf->size)
grow_stringbuf(pbuf);
strncpy(pbuf->buffer,str,n); /* provide null terminator */
pbuf->buffer[n] = 0;
pbuf->used = n;
}
void concat_stringbuf(stringbuf* pbuf,const char* str)
{
/* include null character */
int sz;
sz = strlen(str);
sz += pbuf->used;
while (sz >= pbuf->size)
grow_stringbuf(pbuf);
strcpy(pbuf->buffer+pbuf->used,str);
pbuf->used = sz;
}
void concat_stringbuf_ex(stringbuf* pbuf,const char* str,int n)
{
/* provide null terminator */
int sz = 0;
char* app;
while (sz<n && str[sz])
++sz;
n = sz;
sz += pbuf->used;
while (sz >= pbuf->size)
grow_stringbuf(pbuf);
app = pbuf->buffer+pbuf->used;
strncpy(app,str,n);
app[n] = 0; /* provide null terminator */
pbuf->used = sz;
}
void truncate_stringbuf(stringbuf* pbuf,int length)
{
if (length>=0 && length<pbuf->used) {
pbuf->buffer[length] = 0;
pbuf->used = length;
pbuf->size = length+1;
}
}
void append_terminator_stringbuf(stringbuf* pbuf)
{
++pbuf->used; /* include last terminator in string payload */
if (pbuf->used >= pbuf->size)
grow_stringbuf(pbuf);
pbuf->buffer[pbuf->used] = 0;
}
void reset_stringbuf(stringbuf* pbuf)
{
pbuf->used = 0;
pbuf->buffer[0] = 0;
}