From f1357b416c1264501958292c13c38ef8b5dece92 Mon Sep 17 00:00:00 2001 From: Sebastian Harl Date: Wed, 24 Dec 2014 16:40:29 +0100 Subject: [PATCH] proto: Don't include a string's length in the wire format. That's not necessary given that all strings are null-terminated. --- src/utils/proto.c | 8 +++++--- t/unit/utils/proto_test.c | 14 ++++++-------- 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/src/utils/proto.c b/src/utils/proto.c index beaa07e..f767fa2 100644 --- a/src/utils/proto.c +++ b/src/utils/proto.c @@ -91,7 +91,7 @@ static ssize_t marshal_binary(char *buf, size_t buf_len, size_t len, const unsigned char *v) { uint32_t tmp = htonl((uint32_t)len); - if (buf_len >= len) { + if (buf_len >= sizeof(tmp) + len) { memcpy(buf, &tmp, sizeof(tmp)); memcpy(buf + sizeof(tmp), v, len); } @@ -102,8 +102,10 @@ static ssize_t marshal_string(char *buf, size_t buf_len, const char *v) { /* The actual string including the terminating null byte. */ - return marshal_binary(buf, buf_len, - strlen(v) + 1, (const unsigned char *)v); + size_t len = strlen(v) + 1; + if (buf_len >= len) + memcpy(buf, v, len); + return len; } /* marshal_string */ /* diff --git a/t/unit/utils/proto_test.c b/t/unit/utils/proto_test.c index 9f24c81..c718529 100644 --- a/t/unit/utils/proto_test.c +++ b/t/unit/utils/proto_test.c @@ -87,8 +87,7 @@ START_TEST(test_marshal_data) }, { { SDB_TYPE_STRING, { .string = "some string" } }, - /* length includes the null byte */ - 20, STRING_TYPE "\0\0\0\xc" "some string\0", + 16, STRING_TYPE "some string\0", }, { { SDB_TYPE_DATETIME, { .datetime = 1418923804000000 } }, @@ -101,7 +100,7 @@ START_TEST(test_marshal_data) }, { { SDB_TYPE_REGEX, { .re = { "dummy", dummy_re } } }, - 14, REGEX_TYPE "\0\0\0\x6" "dummy\0", + 10, REGEX_TYPE "dummy\0", }, { { SDB_TYPE_INTEGER | SDB_TYPE_ARRAY, { .array = { @@ -118,8 +117,7 @@ START_TEST(test_marshal_data) { { SDB_TYPE_STRING | SDB_TYPE_ARRAY, { .array = { 2, string_values } } }, - 25, STRING_ARRAY "\0\0\0\x2" "\0\0\0\x4" "foo\0" - "\0\0\0\x5" "abcd\0" + 17, STRING_ARRAY "\0\0\0\x2" "foo\0" "abcd\0" }, { { SDB_TYPE_DATETIME | SDB_TYPE_ARRAY, { .array = { @@ -136,7 +134,7 @@ START_TEST(test_marshal_data) { { SDB_TYPE_REGEX | SDB_TYPE_ARRAY, { .array = { 1, regex_values } } }, - 24, REGEX_ARRAY "\0\0\0\1" "\0\0\0\xc" "dummy regex\0" + 20, REGEX_ARRAY "\0\0\0\1" "dummy regex\0" }, }; @@ -159,8 +157,8 @@ START_TEST(test_marshal_data) len = sdb_proto_marshal_data(buf, sizeof(buf), &golden_data[i].datum); fail_unless(len == golden_data[i].expected_len, - "sdb_proto_marshal_data(, , %s) = %zi; expected: %zi", - v, len, golden_data[i].expected_len); + "sdb_proto_marshal_data(, %zu, %s) = %zi; expected: %zi", + sizeof(buf), v, len, golden_data[i].expected_len); if (memcmp(buf, golden_data[i].expected, len) != 0) { size_t pos; for (pos = 0; pos < (size_t)len; ++pos) -- 2.30.2