| @@ -47,6 +47,14 @@ struct printbuf* printbuf_new(void) | |||||
| } | } | ||||
| /** | |||||
| * Extend the buffer p so it has a size of at least min_size. | |||||
| * | |||||
| * If the current size is large enough, nothing is changed. | |||||
| * | |||||
| * Note: this does not check the available space! The caller | |||||
| * is responsible for performing those calculations. | |||||
| */ | |||||
| static int printbuf_extend(struct printbuf *p, int min_size) | static int printbuf_extend(struct printbuf *p, int min_size) | ||||
| { | { | ||||
| char *t; | char *t; | ||||
| @@ -55,11 +63,11 @@ static int printbuf_extend(struct printbuf *p, int min_size) | |||||
| if (p->size >= min_size) | if (p->size >= min_size) | ||||
| return 0; | return 0; | ||||
| new_size = json_max(p->size * 2, p->bpos + min_size + 8); | |||||
| new_size = json_max(p->size * 2, min_size + 8); | |||||
| #ifdef PRINTBUF_DEBUG | #ifdef PRINTBUF_DEBUG | ||||
| MC_DEBUG("printbuf_memappend: realloc " | MC_DEBUG("printbuf_memappend: realloc " | ||||
| "bpos=%d wrsize=%d old_size=%d new_size=%d\n", | |||||
| p->bpos, size, p->size, new_size); | |||||
| "bpos=%d min_size=%d old_size=%d new_size=%d\n", | |||||
| p->bpos, min_size, p->size, new_size); | |||||
| #endif /* PRINTBUF_DEBUG */ | #endif /* PRINTBUF_DEBUG */ | ||||
| if(!(t = (char*)realloc(p->buf, new_size))) | if(!(t = (char*)realloc(p->buf, new_size))) | ||||
| return -1; | return -1; | ||||
| @@ -70,8 +78,8 @@ static int printbuf_extend(struct printbuf *p, int min_size) | |||||
| int printbuf_memappend(struct printbuf *p, const char *buf, int size) | int printbuf_memappend(struct printbuf *p, const char *buf, int size) | ||||
| { | { | ||||
| if(p->size - p->bpos <= size) { | |||||
| if (printbuf_extend(p, size) < 0) | |||||
| if (p->size <= p->bpos + size + 1) { | |||||
| if (printbuf_extend(p, p->bpos + size + 1) < 0) | |||||
| return -1; | return -1; | ||||
| } | } | ||||
| memcpy(p->buf + p->bpos, buf, size); | memcpy(p->buf + p->bpos, buf, size); | ||||
| @@ -87,7 +95,7 @@ int printbuf_memset(struct printbuf *pb, int offset, int charvalue, int len) | |||||
| if (offset == -1) | if (offset == -1) | ||||
| offset = pb->bpos; | offset = pb->bpos; | ||||
| size_needed = offset + len; | size_needed = offset + len; | ||||
| if(pb->size - pb->bpos <= size_needed) | |||||
| if (pb->size < size_needed) | |||||
| { | { | ||||
| if (printbuf_extend(pb, size_needed) < 0) | if (printbuf_extend(pb, size_needed) < 0) | ||||
| return -1; | return -1; | ||||