Fix #1288 - better mg_iobuf_append allocation strategy

This commit is contained in:
cpq 2021-05-29 09:44:07 +01:00
parent c0a8546330
commit 9d68e20dcc
3 changed files with 23 additions and 8 deletions

View File

@ -1533,10 +1533,13 @@ int mg_iobuf_init(struct mg_iobuf *io, size_t size) {
size_t mg_iobuf_append(struct mg_iobuf *io, const void *buf, size_t len,
size_t chunk_size) {
size_t new_size = io->len + len + chunk_size;
new_size -= new_size % chunk_size;
if (new_size != io->size) mg_iobuf_resize(io, new_size);
if (new_size != io->size) len = 0; // Realloc failure, append nothing
size_t new_size = io->len + len;
if (new_size > io->size) {
new_size += chunk_size;
new_size -= new_size % chunk_size;
if (new_size != io->size) mg_iobuf_resize(io, new_size);
if (new_size != io->size) len = 0; // Realloc failure, append nothing
}
if (buf != NULL) memmove(io->buf + io->len, buf, len);
io->len += len;
return len;

View File

@ -127,7 +127,16 @@
#include <stdarg.h>
#include <stdbool.h>
#include <stdint.h>
#if defined(__GNUC__)
#include <sys/time.h>
#else
typedef long suseconds_t;
struct timeval {
time_t tv_sec;
suseconds_t tv_usec;
};
#endif
#if MG_ENABLE_FS
#include <sys/stat.h>

View File

@ -44,10 +44,13 @@ int mg_iobuf_init(struct mg_iobuf *io, size_t size) {
size_t mg_iobuf_append(struct mg_iobuf *io, const void *buf, size_t len,
size_t chunk_size) {
size_t new_size = io->len + len + chunk_size;
new_size -= new_size % chunk_size;
if (new_size != io->size) mg_iobuf_resize(io, new_size);
if (new_size != io->size) len = 0; // Realloc failure, append nothing
size_t new_size = io->len + len;
if (new_size > io->size) {
new_size += chunk_size;
new_size -= new_size % chunk_size;
if (new_size != io->size) mg_iobuf_resize(io, new_size);
if (new_size != io->size) len = 0; // Realloc failure, append nothing
}
if (buf != NULL) memmove(io->buf + io->len, buf, len);
io->len += len;
return len;