#include <stdlib.h>
#include <string.h>
#include "growstring.h"

const int GSChunkSize = 16;

void newGrowString(struct GrowString* gs) {
  gs->s = malloc(GSChunkSize);
  if (gs->s) {
    gs->s[0] = '\0';
    gs->l = GSChunkSize;
  }
}

void deleteGrowString(struct GrowString* gs) {
  if (gs->l && gs->s)
    free(gs->s);

  gs->l = 0;
  gs->s = 0;
}

void appendGrowString(struct GrowString* gs, char* s) {
  if (gs->s && (strlen(gs->s) + strlen(s) + 1 > gs->l)) {
    /* need to add more memory */
    char* nb = realloc(gs->s, gs->l + strlen(s) + GSChunkSize);

    if (!nb) {
      /* not enough memory */
      /* make no changes to the original growstring */
      return;
    }

    gs->s = nb;
    gs->l += strlen(s) + GSChunkSize;
  }

  strcat(gs->s, s);
}

