diff options
author | Lars Wirzenius <liw@liw.fi> | 2010-10-22 14:11:35 +0100 |
---|---|---|
committer | Lars Wirzenius <liw@liw.fi> | 2010-10-22 14:11:35 +0100 |
commit | 1870ec38019d65d39c1b0aabfdf91b240f24e3be (patch) | |
tree | f5b232df9d74e4f2c25a4855754bc3827e41ab24 | |
parent | 667e88379831f9ac960fc19c8838b6547ffc2710 (diff) | |
download | dynstr-1870ec38019d65d39c1b0aabfdf91b240f24e3be.tar.gz |
Add support creating constant strings.
-rw-r--r-- | dynstr.c | 10 | ||||
-rw-r--r-- | unittests.c | 46 |
2 files changed, 56 insertions, 0 deletions
@@ -108,6 +108,16 @@ Dynstr *dynstr_new_from_memory(const void *mem, size_t size) return new(mem, size, true); } +Dynstr *dynstr_new_from_constant_cstring(const char *cstring) +{ + return new(cstring, strlen(cstring), false); +} + +Dynstr *dynstr_new_from_constant_memory(const void *mem, size_t size) +{ + return new(mem, size, false); +} + size_t dynstr_len(Dynstr *dynstr) { return dynstr->size; diff --git a/unittests.c b/unittests.c index 04a2964..6d0d2c9 100644 --- a/unittests.c +++ b/unittests.c @@ -225,6 +225,50 @@ static int test_creates_from_memory(void) } +static int test_creates_from_constant_cstring(void) +{ + char bytes[] = "asdfasdfafdasdfasdfqw4tb"; + char newbytes[sizeof(bytes)]; + Dynstr *dynstr; + size_t size; + + dynstr = dynstr_new_from_constant_cstring(bytes); + FAIL_UNLESS_EQUAL(dynstr_len(dynstr), strlen(bytes)); + + size = dynstr_memcpy(newbytes, dynstr, 0, strlen(bytes)); + FAIL_UNLESS_EQUAL(size, strlen(bytes)); + FAIL_UNLESS_EQUAL(memcmp(bytes, newbytes, sizeof(bytes)), 0); + + bytes[0] = 'x'; + dynstr_memcpy(newbytes, dynstr, 0, strlen(bytes)); + FAIL_UNLESS_EQUAL(memcmp(bytes, newbytes, sizeof(bytes)), 0); + + return true; +} + + +static int test_creates_from_constant_memory(void) +{ + char bytes[] = "asdfasdfafdasdfasdfqw4tb"; + char newbytes[sizeof(bytes)]; + Dynstr *dynstr; + size_t size; + + dynstr = dynstr_new_from_constant_memory(bytes, sizeof(bytes)); + FAIL_UNLESS_EQUAL(dynstr_len(dynstr), sizeof(bytes)); + + size = dynstr_memcpy(newbytes, dynstr, 0, sizeof(bytes)); + FAIL_UNLESS_EQUAL(size, sizeof(bytes)); + FAIL_UNLESS_EQUAL(memcmp(bytes, newbytes, sizeof(bytes)), 0); + + bytes[0] = 'x'; + dynstr_memcpy(newbytes, dynstr, 0, sizeof(bytes)); + FAIL_UNLESS_EQUAL(memcmp(bytes, newbytes, sizeof(bytes)), 0); + + return true; +} + + static int test_memcpy_returns_zero_if_offset_is_too_large(void) { Dynstr *dynstr; @@ -317,6 +361,8 @@ static const struct test tests[] = { TEST(test_new_returns_NULL_upon_second_allocation_failure), TEST(test_creates_from_cstring), TEST(test_creates_from_memory), + TEST(test_creates_from_constant_cstring), + TEST(test_creates_from_constant_memory), TEST(test_memcpy_returns_zero_if_offset_is_too_large), TEST(test_memcpy_truncates_if_copying_too_much), TEST(test_memcpy_copies_whole_string_ok), |