Simple buffer code

From: James Turner (turnerjh@XTN.NET)
Date: 07/12/98


Here's some simple buffer code, kind of like some of Erwin's stuff and
the dynamic buffer patch on George's site.  This is vastly simplified
but it works quite well.

--cut here--

struct buffer {
  char *p;
  char *curloc;
  int size;                     /* size of the buffer */
  int len;                      /* length of the string, len <= size */
};

typedef struct buffer Buffer;

void
bprintf(struct buffer *b, const char *fmt, ...)
{
  char tempbuf[3 * MAX_STRING_LENGTH + 1];
  va_list args;

  va_start(args, fmt);
  vsnprintf(tempbuf, 3 * MAX_STRING_LENGTH, fmt, args);
  va_end(args);

  buf_strcat(b, tempbuf);
}


struct buffer *
new_buffer(int i)
{
  struct buffer *b;

  b = mud_malloc(sizeof(*b));
  b->size = i + 5;
  b->curloc = b->p = mud_malloc(b->size);
  b->len = 0;

  return b;
}

void
free_buffer(struct buffer *b)
{
  mud_free(b->p);
  mud_free(b);
}

void
buf_strcpy(struct buffer *b, const char *s)
{
  mud_free(b->p);

  b->size = mud_strlen(s) + 4;
  b->len = mud_strlen(s);

  b->p = mud_malloc(b->size);
  mud_strcpy(b->p, s);
  b->curloc = b->p + b->len;

  buf_strcat(b, s);
}

void
buf_strcat(struct buffer *b, const char *s)
{
  int len;

  len = mud_strlen(s);

  if (len + b->len >= b->size) {
    int offset;

    offset = b->curloc - b->p;

    b->size = len + 2 * b->size + 2;
    b->p = mud_realloc(b->p, b->size);
    b->curloc = b->p + offset;
  }

  b->len += len;
  mud_strcpy(b->curloc, s);
  b->curloc += len;

}


--cut here--

--
James Turner                turnerjh@pattern.net         UIN: 1102038
                            http://www.vuse.vanderbilt.edu/~turnerjh/


     +------------------------------------------------------------+
     | Ensure that you have read the CircleMUD Mailing List FAQ:  |
     | http://democracy.queensu.ca/~fletcher/Circle/list-faq.html |
     +------------------------------------------------------------+



This archive was generated by hypermail 2b30 : 12/15/00 PST