#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <agxbuf.h>
#define N_GNEW(n,t) (t*)malloc((n)*sizeof(t))
void
agxbinit (agxbuf* xb, unsigned int hint, unsigned char* init)
{
if (init) {
xb->buf = init;
xb->dyna = 0;
}
else {
if (hint == 0) hint = BUFSIZ;
xb->dyna = 1;
xb->buf = N_GNEW(hint,unsigned char);
}
xb->eptr = xb->buf + hint;
xb->ptr = xb->buf;
*xb->ptr = '\0';
}
int
agxbmore (agxbuf* xb, unsigned int ssz)
{
int cnt;
int size;
int nsize;
unsigned char* nbuf;
size = xb->eptr - xb->buf;
nsize = 2*size;
if (size+ssz > nsize) nsize = size+ssz;
cnt = xb->ptr - xb->buf;
if (xb->dyna) {
nbuf = realloc(xb->buf,nsize);
}
else {
nbuf = N_GNEW(nsize,unsigned char);
memcpy (nbuf, xb->buf, cnt);
xb->dyna = 1;
}
xb->buf = nbuf;
xb->ptr = xb->buf + cnt;
xb->eptr = xb->buf + nsize;
return 0;
}
int
agxbput_n (agxbuf* xb, char* s, unsigned int ssz)
{
if (xb->ptr + ssz > xb->eptr)
agxbmore (xb, ssz);
memcpy (xb->ptr, s, ssz);
xb->ptr += ssz;
return ssz;
}
int
agxbput (agxbuf* xb, char* s)
{
unsigned int ssz = strlen (s);
return agxbput_n(xb,s,ssz);
}
void
agxbfree (agxbuf* xb)
{
if (xb->dyna) free (xb->buf);
}
int
agxbpop (agxbuf* xb)
{
int c;
if (xb->ptr > xb->buf) {
c = *xb->ptr--;
return c;
}
else return -1;
}