From 667ae3c735e9c35a0a32affe3f9b41317fe76118 Mon Sep 17 00:00:00 2001 From: Sebastian Harl Date: Mon, 10 Nov 2014 09:33:36 +0100 Subject: [PATCH] data: Let strlen() and format() support string/decimal/integer arrays. --- src/core/data.c | 42 ++++++++++++++++++++++++++++++++++------- t/unit/core/data_test.c | 17 +++++++++++++++++ 2 files changed, 52 insertions(+), 7 deletions(-) diff --git a/src/core/data.c b/src/core/data.c index 53cc888..28d4c36 100644 --- a/src/core/data.c +++ b/src/core/data.c @@ -787,9 +787,14 @@ sdb_data_strlen(const sdb_data_t *datum) return strlen(datum->data.re.raw) + 4; } else if (datum->type & SDB_TYPE_ARRAY) { - /* TODO */ - errno = ENOTSUP; - return 0; + size_t len = 2; /* [] */ + size_t i; + for (i = 0; i < datum->data.array.length; ++i) { + sdb_data_t v = SDB_DATA_INIT; + sdb_data_array_get(datum, i, &v); + len += sdb_data_strlen(&v) + 1; + } + return len; } return 0; } /* sdb_data_strlen */ @@ -804,7 +809,7 @@ sdb_data_format(const sdb_data_t *datum, char *buf, size_t buflen, int quoted) size_t i, pos; - if ((! datum) || (! buf)) + if ((! datum) || (! buf) || (! buflen)) return -1; if (datum->type == SDB_TYPE_INTEGER) { @@ -873,9 +878,32 @@ sdb_data_format(const sdb_data_t *datum, char *buf, size_t buflen, int quoted) } } else if (datum->type & SDB_TYPE_ARRAY) { - /* TODO */ - errno = ENOTSUP; - return -1; + ret = 1; + buf[0] = '['; + for (i = 0; i < datum->data.array.length; ++i) { + sdb_data_t v = SDB_DATA_INIT; + int n; + if ((size_t)ret >= buflen - 1) + break; + + if (ret > 1) { + buf[ret] = ','; + buf[ret + 1] = ' '; + ret += 2; + } + + sdb_data_array_get(datum, i, &v); + n = sdb_data_format(&v, buf + ret, buflen - ret, quoted); + if (n > 0) + ret += n; + else + break; + } + if ((size_t)ret < buflen - 1) { + buf[ret] = ']'; + buf[ret + 1] = '\0'; + ++ret; + } } if (is_null) { diff --git a/t/unit/core/data_test.c b/t/unit/core/data_test.c index 704ebdd..2da33a1 100644 --- a/t/unit/core/data_test.c +++ b/t/unit/core/data_test.c @@ -1591,6 +1591,9 @@ END_TEST START_TEST(test_format) { + int64_t int_values[] = { 47, 11, 23 }; + char *string_values[] = { "foo", "bar", "qux", "baz" }; + struct { sdb_data_t datum; const char *expected; @@ -1638,6 +1641,20 @@ START_TEST(test_format) { SDB_TYPE_REGEX, { .re = { "some regex", empty_re } } }, "\"/some regex/\"", }, + { + { + SDB_TYPE_INTEGER | SDB_TYPE_ARRAY, + { .array = { SDB_STATIC_ARRAY_LEN(int_values), int_values } }, + }, + "[47, 11, 23]", + }, + { + { + SDB_TYPE_STRING | SDB_TYPE_ARRAY, + { .array = { SDB_STATIC_ARRAY_LEN(string_values), string_values } }, + }, + "[\"foo\", \"bar\", \"qux\", \"baz\"]", + }, }; size_t i; -- 2.30.2