diff options
author | Lars Wirzenius <liw@liw.fi> | 2010-10-20 21:11:32 +0100 |
---|---|---|
committer | Lars Wirzenius <liw@liw.fi> | 2010-10-20 21:11:32 +0100 |
commit | 228bdfa2eea2ba323d47c326dbcf2d53c02c7771 (patch) | |
tree | 1133afa0d80a2084f94d9902c6a51389dc655489 | |
parent | 9ca4e13afe8a15fd08c761d92d4facfe49bbbbaf (diff) | |
download | dynstr-228bdfa2eea2ba323d47c326dbcf2d53c02c7771.tar.gz |
Implement dynstr_new_from_cstring and dynstr_memcpy.
-rw-r--r-- | dynstr.c | 19 | ||||
-rw-r--r-- | dynstr.h | 2 | ||||
-rw-r--r-- | unittests.c | 19 |
3 files changed, 39 insertions, 1 deletions
@@ -87,6 +87,11 @@ Dynstr *dynstr_new_empty(void) return new(NULL, 0, true); } +Dynstr *dynstr_new_from_cstring(const char *cstring) +{ + return new(cstring, strlen(cstring), true); +} + size_t dynstr_len(Dynstr *dynstr) { return dynstr->size; @@ -96,3 +101,17 @@ bool dynstr_is_empty(Dynstr *dynstr) { return dynstr_len(dynstr) == 0; } + +size_t dynstr_memcpy(void *mem, Dynstr *dynstr, size_t offset, size_t size) +{ + size_t len; + + len = dynstr_len(dynstr); + if (offset >= len) + return 0; + if (size > len - offset) + size = len - offset; + memcpy(mem, dynstr->mem + offset, size); + return size; +} + @@ -107,7 +107,7 @@ int dynstr_byte_at(Dynstr *dynstr, size_t offset); /* Copy contents of a dynamic string into a memory area. If the dynamic * string is not long enough, or the offset is past the end of the string, - * the copy is silently truncated. */ + * the copy is truncated. Return number of bytes copied. */ size_t dynstr_memcpy(void *mem, Dynstr *dynstr, size_t offset, size_t size); /* Search for first or last byte with a given value in a string, diff --git a/unittests.c b/unittests.c index adb8e32..0e0285c 100644 --- a/unittests.c +++ b/unittests.c @@ -5,6 +5,7 @@ #include <stdbool.h> #include <stdio.h> #include <stdlib.h> +#include <string.h> #include "dynstr.h" @@ -100,6 +101,23 @@ static int test_empty_string_is_empty(void) } +static int test_creates_from_cstring(void) +{ + const char bytes[] = "asdfasdfafdasdfasdfqw4tb"; + char newbytes[sizeof(bytes)]; + Dynstr *dynstr; + size_t size; + + dynstr = dynstr_new_from_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); + return true; +} + + struct test { const char *name; int (*test)(void); @@ -114,6 +132,7 @@ static const struct test tests[] = { TEST(test_init_resets_error_handler), TEST(test_abort_handler_calls_abort), TEST(test_empty_string_is_empty), + TEST(test_creates_from_cstring), }; static const int num_tests = sizeof(tests) / sizeof(tests[0]); |