From d4808fb260537e65936d9dd25e22cdccd5f7fb6d Mon Sep 17 00:00:00 2001 From: Sebastian Harl Date: Thu, 20 Feb 2014 22:24:48 +0100 Subject: [PATCH] data: Added sdb_data_strlen. This function provides a worst-case estimate of the number of bytes required to format a datum as a string. --- src/core/data.c | 28 ++++++++++++++++++++++++++++ src/include/core/data.h | 9 +++++++++ 2 files changed, 37 insertions(+) diff --git a/src/core/data.c b/src/core/data.c index 54b6d28..4c89b43 100644 --- a/src/core/data.c +++ b/src/core/data.c @@ -85,6 +85,34 @@ sdb_data_free_datum(sdb_data_t *datum) } } /* sdb_data_free_datum */ +size_t +sdb_data_strlen(sdb_data_t *datum) +{ + if (! datum) + return 0; + + switch (datum->type) { + case SDB_TYPE_INTEGER: + /* log(64) */ + return 20; + case SDB_TYPE_DECIMAL: + /* XXX: -0xN.NNNNNNp+NNN */ + return 42; + case SDB_TYPE_STRING: + if (! datum->data.string) + return 6; /* "NULL" */ + /* in the worst case, each character needs to be escaped */ + return 2 * strlen(datum->data.string) + 2; + case SDB_TYPE_DATETIME: + /* "YYYY-MM-DD HH:MM:SS +zzzz" */ + return 27; + case SDB_TYPE_BINARY: + /* "\xNN" */ + return 4 * datum->data.binary.length + 2; + } + return 0; +} /* sdb_data_strlen */ + int sdb_data_format(sdb_data_t *datum, sdb_strbuf_t *buf) { diff --git a/src/include/core/data.h b/src/include/core/data.h index c7c51b8..54a2ed2 100644 --- a/src/include/core/data.h +++ b/src/include/core/data.h @@ -101,6 +101,15 @@ sdb_data_copy(sdb_data_t *dst, const sdb_data_t *src); void sdb_data_free_datum(sdb_data_t *datum); +/* + * sdb_data_strlen: + * Returns a (worst-case) estimate for the number of bytes required to format + * the datum as a string. Does not take the terminating null byte into + * account. + */ +size_t +sdb_data_strlen(sdb_data_t *datum); + /* * sdb_data_format: * Append the specified datum to the specified string buffer using a default -- 2.30.2