From: Sebastian Harl Date: Thu, 20 Feb 2014 20:36:46 +0000 (+0100) Subject: data: Escape \ and " in strings when formatting them. X-Git-Tag: sysdb-0.1.0~206 X-Git-Url: https://git.tokkee.org/?a=commitdiff_plain;h=fd3b58d670103cf729f17f682174ebb60d248a63;p=sysdb.git data: Escape \ and " in strings when formatting them. --- diff --git a/src/core/data.c b/src/core/data.c index 81b511b..54b6d28 100644 --- a/src/core/data.c +++ b/src/core/data.c @@ -103,8 +103,24 @@ sdb_data_format(sdb_data_t *datum, sdb_strbuf_t *buf) sdb_strbuf_append(buf, "\"NULL\""); return 0; } - /* TODO: escape special characters */ - sdb_strbuf_append(buf, "\"%s\"", datum->data.string); + { + char tmp[2 * strlen(datum->data.string) + 1]; + size_t i, pos; + + pos = 0; + for (i = 0; i < strlen(datum->data.string); ++i) { + char byte = datum->data.string[i]; + + if ((byte == '\\') || (byte == '"')) { + tmp[pos] = '\\'; + ++pos; + } + tmp[pos] = byte; + ++pos; + } + tmp[pos] = '\0'; + sdb_strbuf_append(buf, "\"%s\"", tmp); + } break; case SDB_TYPE_DATETIME: { diff --git a/t/core/data_test.c b/t/core/data_test.c index a16d7fe..649a7df 100644 --- a/t/core/data_test.c +++ b/t/core/data_test.c @@ -155,6 +155,17 @@ START_TEST(test_format) "sdb_data_format() used wrong format: %s; expected: %s", string, expected); + datum.data.string = "now using special \\ \" characters"; + sdb_strbuf_clear(buf); + check = sdb_data_format(&datum, buf); + fail_unless(! check, + "sdb_data_format(STRING) = %d; expected: 0", check); + string = sdb_strbuf_string(buf); + expected = "\"now using special \\\\ \\\" characters\""; + fail_unless(! strcmp(string, expected), + "sdb_data_format() used wrong format: %s; expected: %s", + string, expected); + datum.data.string = NULL; sdb_strbuf_clear(buf); check = sdb_data_format(&datum, buf);