aboutsummaryrefslogtreecommitdiff
path: root/strbuf.c
diff options
context:
space:
mode:
authorMark Pulford <mark@kyne.com.au>2011-05-29 18:03:22 +0930
committerMark Pulford <mark@kyne.com.au>2011-05-29 18:03:22 +0930
commit3d1c5e19f45cf484774926ba6e2555d1c8e4c39b (patch)
treef6cd7cc888ec643d025a37810fe7f15cc91d7381 /strbuf.c
parentc0b473a8e974407dc308ce0fd0058136b9faa90c (diff)
downloadlua-cjson-3d1c5e19f45cf484774926ba6e2555d1c8e4c39b.tar.gz
lua-cjson-3d1c5e19f45cf484774926ba6e2555d1c8e4c39b.tar.bz2
lua-cjson-3d1c5e19f45cf484774926ba6e2555d1c8e4c39b.zip
Add support for runtime number precision config
Add cjson.encode_number_precision(). Reducing the number precision from 14 to 3 can increase performance up to 50% with number heavy conversions.
Diffstat (limited to 'strbuf.c')
-rw-r--r--strbuf.c27
1 files changed, 15 insertions, 12 deletions
diff --git a/strbuf.c b/strbuf.c
index c59b6f6..976925a 100644
--- a/strbuf.c
+++ b/strbuf.c
@@ -197,25 +197,28 @@ void strbuf_append_string(strbuf_t *s, const char *str)
197 } 197 }
198} 198}
199 199
200void strbuf_append_number(strbuf_t *s, double number) 200/* strbuf_append_fmt() should only be used when an upper bound
201 * is known for the output string. */
202void strbuf_append_fmt(strbuf_t *s, int len, const char *fmt, ...)
201{ 203{
202 int len; 204 va_list arg;
205 int fmt_len;
203 206
204 /* Lowest double printed with %.14g is 21 characters long: 207 strbuf_ensure_empty_length(s, len);
205 * -1.7976931348623e+308
206 *
207 * Use 32 to include the \0, and a few extra just in case..
208 */
209 strbuf_ensure_empty_length(s, 32);
210 208
211 len = sprintf(s->buf + s->length, "%.14g", number); 209 va_start(arg, fmt);
212 if (len < 0) 210 fmt_len = vsnprintf(s->buf + s->length, len, fmt, arg);
211 va_end(arg);
212
213 if (fmt_len < 0)
213 die("BUG: Unable to convert number"); /* This should never happen.. */ 214 die("BUG: Unable to convert number"); /* This should never happen.. */
214 215
215 s->length += len; 216 s->length += fmt_len;
216} 217}
217 218
218void strbuf_append_fmt(strbuf_t *s, const char *fmt, ...) 219/* strbuf_append_fmt_retry() can be used when the there is no known
220 * upper bound for the output string. */
221void strbuf_append_fmt_retry(strbuf_t *s, const char *fmt, ...)
219{ 222{
220 va_list arg; 223 va_list arg;
221 int fmt_len, try; 224 int fmt_len, try;