1
0
mirror of https://github.com/mpv-player/mpv synced 2024-12-19 05:15:12 +00:00

bstr: avoid redundant vsnprintf calls

Until now, bstr_xappend_vasprintf() called vsnprintf() always twice:
once to determine how much output the call would produce, and a second
time to actually output the data to the (possibly resized) target
memory.

Change this so that it tries to output to the already allocated memory
first, and repeat the call only if allocation is required.

This is especially helpful, as bstr_xappend_vasprintf() is designed to
avoid reallocation when building strings. Usually, the second
vsnprintf() will happen only at the beginning, when the buffer hasn't
been extended to his largest needed size yet.

Not sure if there is a need to optimize this; but see the next commit.
This commit is contained in:
wm4 2016-03-23 22:00:16 +01:00
parent c7f802ee45
commit f9084c7bce

View File

@ -401,15 +401,21 @@ void bstr_xappend_vasprintf(void *talloc_ctx, bstr *s, const char *fmt,
int size;
va_list copy;
va_copy(copy, ap);
size_t avail = talloc_get_size(s->start) - s->len;
char *dest = s->start ? s->start + s->len : NULL;
char c;
size = vsnprintf(&c, 1, fmt, copy);
if (avail < 1)
dest = &c;
size = vsnprintf(dest, MPMAX(avail, 1), fmt, copy);
va_end(copy);
if (size < 0)
abort();
resize_append(talloc_ctx, s, size + 1);
vsnprintf(s->start + s->len, size + 1, fmt, ap);
if (avail < 1 || size + 1 > avail) {
resize_append(talloc_ctx, s, size + 1);
vsnprintf(s->start + s->len, size + 1, fmt, ap);
}
s->len += size;
}