123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155 |
- #include "config.h"
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #ifdef HAVE_STDARG_H
- # include <stdarg.h>
- #else
- # error Not enough var arg support!
- #endif
- #include "debug.h"
- #include "printbuf.h"
- #include "snprintf_compat.h"
- #include "vasprintf_compat.h"
- static int printbuf_extend(struct printbuf *p, int min_size);
- struct printbuf* printbuf_new(void)
- {
- struct printbuf *p;
- p = (struct printbuf*)calloc(1, sizeof(struct printbuf));
- if(!p) return NULL;
- p->size = 32;
- p->bpos = 0;
- if(!(p->buf = (char*)malloc(p->size))) {
- free(p);
- return NULL;
- }
- p->buf[0]= '\0';
- return p;
- }
- static int printbuf_extend(struct printbuf *p, int min_size)
- {
- char *t;
- int new_size;
- if (p->size >= min_size)
- return 0;
- new_size = p->size * 2;
- if (new_size < min_size + 8)
- new_size = min_size + 8;
- #ifdef PRINTBUF_DEBUG
- MC_DEBUG("printbuf_memappend: realloc "
- "bpos=%d min_size=%d old_size=%d new_size=%d\n",
- p->bpos, min_size, p->size, new_size);
- #endif
- if(!(t = (char*)realloc(p->buf, new_size)))
- return -1;
- p->size = new_size;
- p->buf = t;
- return 0;
- }
- int printbuf_memappend(struct printbuf *p, const char *buf, int size)
- {
- if (p->size <= p->bpos + size + 1) {
- if (printbuf_extend(p, p->bpos + size + 1) < 0)
- return -1;
- }
- memcpy(p->buf + p->bpos, buf, size);
- p->bpos += size;
- p->buf[p->bpos]= '\0';
- return size;
- }
- int printbuf_memset(struct printbuf *pb, int offset, int charvalue, int len)
- {
- int size_needed;
- if (offset == -1)
- offset = pb->bpos;
- size_needed = offset + len;
- if (pb->size < size_needed)
- {
- if (printbuf_extend(pb, size_needed) < 0)
- return -1;
- }
- memset(pb->buf + offset, charvalue, len);
- if (pb->bpos < size_needed)
- pb->bpos = size_needed;
- return 0;
- }
- int sprintbuf(struct printbuf *p, const char *msg, ...)
- {
- va_list ap;
- char *t;
- int size;
- char buf[128];
-
- va_start(ap, msg);
- size = vsnprintf(buf, 128, msg, ap);
- va_end(ap);
-
- if(size == -1 || size > 127) {
- va_start(ap, msg);
- if((size = vasprintf(&t, msg, ap)) < 0) { va_end(ap); return -1; }
- va_end(ap);
- printbuf_memappend(p, t, size);
- free(t);
- return size;
- } else {
- printbuf_memappend(p, buf, size);
- return size;
- }
- }
- void printbuf_reset(struct printbuf *p)
- {
- p->buf[0] = '\0';
- p->bpos = 0;
- }
- void printbuf_free(struct printbuf *p)
- {
- if(p) {
- free(p->buf);
- free(p);
- }
- }
|