From: Sebastian Harl Date: Mon, 10 Feb 2014 18:07:49 +0000 (+0100) Subject: data: Improve serialization of binary data. X-Git-Tag: sysdb-0.1.0~213 X-Git-Url: https://git.tokkee.org/?a=commitdiff_plain;h=0d96909dfa8190cea20f8565b2013824f65d307a;p=sysdb.git data: Improve serialization of binary data. Instead of calling strbuf_append() for each byte, precompute the string in a simple for-loop and then append the result to the buffer. This basically inlines a formatter specific to this use-case and, thus, should be must faster. --- diff --git a/src/core/data.c b/src/core/data.c index 1bb5400..8f4330e 100644 --- a/src/core/data.c +++ b/src/core/data.c @@ -114,13 +114,27 @@ sdb_data_format(sdb_data_t *datum, sdb_strbuf_t *buf) break; case SDB_TYPE_BINARY: { - size_t i; - /* TODO: improve this! */ - sdb_strbuf_append(buf, "%s", "\""); - for (i = 0; i < datum->data.binary.length; ++i) - sdb_strbuf_append(buf, "\\%x", - (int)datum->data.binary.datum[i]); - sdb_strbuf_append(buf, "%s", "\""); + char tmp[4 * datum->data.binary.length + 1]; + size_t i, pos; + + pos = 0; + for (i = 0; i < datum->data.binary.length; ++i) { + int byte = (int)datum->data.binary.datum[i]; + char hex[] = {'0', '1', '2', '3', '4', '5', '6', '7', + '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; + + tmp[pos] = '\\'; + ++pos; + + if (byte > 0xf) { + tmp[pos] = hex[byte >> 4]; + ++pos; + } + tmp[pos] = hex[byte & 0xf]; + ++pos; + } + tmp[pos] = '\0'; + sdb_strbuf_append(buf, "\"%s\"", tmp); } break; default: