/*
 * dynamic strings
 * March 1989, Miles Bader
 */

#include "common.h"
#include "dstr.h"

struct dstr *dstr_Create(initsize)
int initsize;
{
    struct dstr *n=NEW(struct dstr);
    
    DBUG_ENTER("dstr_Create");

    if(n==NULL)
       fatal("couldn't allocate a dstr");

    n->buf=malloc(initsize+1);

    if(n->buf==NULL)
       fatal("couldn't allocate dstr of size %d",initsize);

    n->max=initsize;
    n->len=0;
    *n->buf='\0';

    DBUG_RETURN(struct dstr *,n);
}

void dstr_Free(ds)
struct dstr *ds;
{
    DBUG_ENTER("dstr_Free");

    if(ds->buf!=NULL)
       FREE(ds->buf);
    FREE(ds);

    DBUG_VOID_RETURN;
}

void dstr_Clear(ds)
struct dstr *ds;
{
   ds->len=0;
   *ds->buf='\0';
}

void dstr_Append(ds,str)
struct dstr *ds;
char *str;
{
    int len=strlen(str);
    
    DBUG_ENTER("dstr_Append");

    if(len+ds->len>ds->max){
       ds->max+=len+len;
       ds->buf=(char *)realloc((void *)ds->buf,ds->max);

       if(ds->buf==NULL)
           fatal("couldn't extend a dstr to %d chars",ds->max);
    }

    strcpy(ds->buf+ds->len,str);
    ds->len+=len;

    DBUG_VOID_RETURN;
}

void dstr_Set(ds,str)
struct dstr *ds;
char *str;
{
    DBUG_ENTER("dstr_Set");

    ds->len=0;
    dstr_Append(ds,str);

    DBUG_VOID_RETURN;
}

void dstr_Addf(ds,fmt,a1,a2,a3,a4,a5,a6,a7)
struct dstr *ds;
char *fmt;
char *a1,*a2,*a3,*a4,*a5,*a6,*a7;
{
    char buf[500];

    DBUG_ENTER("dstr_Addf");

    sprintf(buf,fmt,a1,a2,a3,a4,a5,a6,a7);

    DBUG_2("buf",buf);

    dstr_Append(ds,buf);

    DBUG_VOID_RETURN;
}
