Browse Source

Rework duk_push_vsprintf() loop to reduce code size

pull/20/head
Sami Vaarala 11 years ago
parent
commit
c60adc128e
  1. 24
      src/duk_api.c

24
src/duk_api.c

@ -2579,7 +2579,7 @@ const char *duk_push_vsprintf(duk_context *ctx, const char *fmt, va_list ap) {
duk_uint8_t stack_buf[DUK_PUSH_SPRINTF_INITIAL_SIZE];
size_t sz = DUK_PUSH_SPRINTF_INITIAL_SIZE;
int pushed_buf = 0;
void *buf = (void *) stack_buf;
void *buf;
int len;
const char *res;
@ -2599,10 +2599,6 @@ const char *duk_push_vsprintf(duk_context *ctx, const char *fmt, va_list ap) {
sz = DUK_PUSH_SPRINTF_INITIAL_SIZE;
}
DUK_ASSERT(sz > 0);
if (sz > sizeof(stack_buf)) {
pushed_buf = 1;
buf = duk_push_dynamic_buffer(ctx, sz);
}
/* Try to make do with a stack buffer to avoid allocating a temporary buffer.
* This works 99% of the time which is quite nice.
@ -2610,6 +2606,16 @@ const char *duk_push_vsprintf(duk_context *ctx, const char *fmt, va_list ap) {
for (;;) {
va_list ap_copy; /* copied so that 'ap' can be reused */
if (sz <= sizeof(stack_buf)) {
buf = stack_buf;
} else if (!pushed_buf) {
pushed_buf = 1;
buf = duk_push_dynamic_buffer(ctx, sz);
} else {
buf = duk_resize_buffer(ctx, -1, sz);
}
DUK_ASSERT(buf != NULL);
DUK_VA_COPY(ap_copy, ap);
len = duk__try_push_vsprintf(ctx, buf, sz, fmt, ap_copy);
va_end(ap_copy);
@ -2622,14 +2628,6 @@ const char *duk_push_vsprintf(duk_context *ctx, const char *fmt, va_list ap) {
if (sz >= DUK_PUSH_SPRINTF_SANITY_LIMIT) {
DUK_ERROR(thr, DUK_ERR_API_ERROR, "cannot sprintf, required buffer insanely long");
}
if (!pushed_buf) {
pushed_buf = 1;
buf = duk_push_dynamic_buffer(ctx, sz);
} else {
buf = duk_resize_buffer(ctx, -1, sz);
}
DUK_ASSERT(buf != NULL);
}
/* Cannot use duk_to_string() on the buffer because it is usually

Loading…
Cancel
Save