This source file includes following definitions.
- binit
- breset
- bfree
- bgrow
- bwrite
- bwritestr
- bstr
- btake
- bwriteb
- bequal
- bsubst
- vinit
- vreset
- vfree
- vgrow
- vcopy
- vadd
- vaddn
- strpcmp
- vuniq
- splitlines
- splitfields
#include "a.h"
void
binit(Buf *b)
{
b->p = nil;
b->len = 0;
b->cap = 0;
}
void
breset(Buf *b)
{
b->len = 0;
}
void
bfree(Buf *b)
{
xfree(b->p);
binit(b);
}
void
bgrow(Buf *b, int n)
{
int want;
want = b->len+n;
if(want > b->cap) {
b->cap = 2*want;
if(b->cap < 64)
b->cap = 64;
b->p = xrealloc(b->p, b->cap);
}
}
void
bwrite(Buf *b, void *v, int n)
{
bgrow(b, n);
xmemmove(b->p+b->len, v, n);
b->len += n;
}
void
bwritestr(Buf *b, char *p)
{
bwrite(b, p, xstrlen(p));
}
char*
bstr(Buf *b)
{
bgrow(b, 1);
b->p[b->len] = '\0';
return b->p;
}
char*
btake(Buf *b)
{
char *p;
p = bstr(b);
binit(b);
return p;
}
void
bwriteb(Buf *dst, Buf *src)
{
bwrite(dst, src->p, src->len);
}
bool
bequal(Buf *s, Buf *t)
{
return s->len == t->len && xmemcmp(s->p, t->p, s->len) == 0;
}
void
bsubst(Buf *b, char *x, char *y)
{
char *p;
int nx, ny, pos;
nx = xstrlen(x);
ny = xstrlen(y);
pos = 0;
for(;;) {
p = xstrstr(bstr(b)+pos, x);
if(p == nil)
break;
if(nx != ny) {
if(nx < ny) {
pos = p - b->p;
bgrow(b, ny-nx);
p = b->p + pos;
}
xmemmove(p+ny, p+nx, (b->p+b->len)-(p+nx));
}
xmemmove(p, y, ny);
pos = p+ny - b->p;
b->len += ny - nx;
}
}
void
vinit(Vec *v)
{
v->p = nil;
v->len = 0;
v->cap = 0;
}
void
vreset(Vec *v)
{
int i;
for(i=0; i<v->len; i++) {
xfree(v->p[i]);
v->p[i] = nil;
}
v->len = 0;
}
void
vfree(Vec *v)
{
vreset(v);
xfree(v->p);
vinit(v);
}
void
vgrow(Vec *v, int n)
{
int want;
want = v->len+n;
if(want > v->cap) {
v->cap = 2*want;
if(v->cap < 64)
v->cap = 64;
v->p = xrealloc(v->p, v->cap*sizeof v->p[0]);
}
}
void
vcopy(Vec *dst, char **src, int srclen)
{
int i;
for(i=0; i<srclen; i++)
vadd(dst, src[i]);
}
void
vadd(Vec *v, char *p)
{
vgrow(v, 1);
if(p != nil)
p = xstrdup(p);
v->p[v->len++] = p;
}
void
vaddn(Vec *v, char *p, int n)
{
char *q;
vgrow(v, 1);
q = xmalloc(n+1);
xmemmove(q, p, n);
q[n] = '\0';
v->p[v->len++] = q;
}
static int
strpcmp(const void *a, const void *b)
{
return xstrcmp(*(char**)a, *(char**)b);
}
void
vuniq(Vec *v)
{
int i, n;
xqsort(v->p, v->len, sizeof(v->p[0]), strpcmp);
n = 0;
for(i=0; i<v->len; i++) {
if(n>0 && streq(v->p[i], v->p[n-1]))
xfree(v->p[i]);
else
v->p[n++] = v->p[i];
}
v->len = n;
}
void
splitlines(Vec *v, char *p)
{
int i;
char *start;
vreset(v);
start = p;
for(i=0; p[i]; i++) {
if(p[i] == '\n') {
vaddn(v, start, (p+i+1)-start);
start = p+i+1;
}
}
if(*start != '\0')
vadd(v, start);
}
void
splitfields(Vec *v, char *p)
{
char *start;
vreset(v);
for(;;) {
while(*p == ' ' || *p == '\t' || *p == '\r' || *p == '\n')
p++;
if(*p == '\0')
break;
start = p;
while(*p != ' ' && *p != '\t' && *p != '\r' && *p != '\n' && *p != '\0')
p++;
vaddn(v, start, p-start);
}
}