Small cleanup to aomstats.c - Multiplicative re-size instead of additive (amortized constant time -- although in practice, I could not see a difference). Still, multiplicative re-size is the gold standard. - Ensure that there is enough room for the data being written out, when growing the array - Readability cleanup (remove one level of nesting) Change-Id: I424617e845814cf1acb7dd5a08027964078cc9ae
diff --git a/stats/aomstats.c b/stats/aomstats.c index 4a15adf..8d59377 100644 --- a/stats/aomstats.c +++ b/stats/aomstats.c
@@ -11,10 +11,12 @@ #include "stats/aomstats.h" +#include <assert.h> #include <math.h> #include <stdlib.h> #include <string.h> +#include "aom_dsp/aom_dsp_common.h" #include "common/tools_common.h" int stats_open_file(stats_io_t *stats, const char *fpf, int pass) { @@ -83,24 +85,28 @@ void stats_write(stats_io_t *stats, const void *pkt, size_t len) { if (stats->file) { (void)fwrite(pkt, 1, len, stats->file); - } else { - if (stats->buf.sz + len > stats->buf_alloc_sz) { - size_t new_sz = stats->buf_alloc_sz + 64 * 1024; - char *new_ptr = realloc(stats->buf.buf, new_sz); - - if (new_ptr) { - stats->buf_ptr = new_ptr + (stats->buf_ptr - (char *)stats->buf.buf); - stats->buf.buf = new_ptr; - stats->buf_alloc_sz = new_sz; - } else { - fatal("Failed to realloc firstpass stats buffer."); - } - } - - memcpy(stats->buf_ptr, pkt, len); - stats->buf.sz += len; - stats->buf_ptr += len; + return; } + assert(stats->buf.sz <= stats->buf_alloc_sz); + assert(0 < stats->buf_alloc_sz); + if (stats->buf.sz + len > stats->buf_alloc_sz) { + // Grow by a factor of 1.5 each time, for amortized constant time. + // Also make sure there is enough room for the data. + size_t new_sz = AOMMAX((3 * stats->buf_alloc_sz) / 2, stats->buf.sz + len); + char *new_ptr = realloc(stats->buf.buf, new_sz); + + if (new_ptr) { + stats->buf_ptr = new_ptr + (stats->buf_ptr - (char *)stats->buf.buf); + stats->buf.buf = new_ptr; + stats->buf_alloc_sz = new_sz; + } else { + fatal("Failed to realloc firstpass stats buffer."); + } + } + + memcpy(stats->buf_ptr, pkt, len); + stats->buf.sz += len; + stats->buf_ptr += len; } aom_fixed_buf_t stats_get(stats_io_t *stats) { return stats->buf; }