From 3a365b44ceadf475bf7b9963faba39ca1063712c Mon Sep 17 00:00:00 2001 From: "me@ow.nekobit.net" Date: Mon, 18 Apr 2022 19:31:35 +0000 Subject: [PATCH] WIP strrepl impl FossilOrigin-Name: b5262d6161a7e3497069831702bc33e56defb611acf1fbad367f26612d906366 --- src/string.c | 23 +++++++++++++++++++++++ src/string.h | 1 + test/unit/main.c | 5 +++-- test/unit/string_test.c | 6 ++++++ 4 files changed, 33 insertions(+), 2 deletions(-) create mode 100644 test/unit/string_test.c diff --git a/src/string.c b/src/string.c index 7d29603..afeec59 100644 --- a/src/string.c +++ b/src/string.c @@ -16,6 +16,7 @@ * along with this program. If not, see . */ +#include #include #include "string.h" @@ -50,3 +51,25 @@ char* strnstr(const char* haystack, const char* needle, size_t s) return NULL; } + +char* strrepl(char* source, char* find, char* repl) +{ + size_t repl_len = strlen(repl); + char* result = NULL; + char* n; + char* needle = source; + + do + { + n = strstr(find); + if (!n) break; + result = realloc(result, n - source + repl_len + 1); + result[n - source + repl_len] = '\0'; + // Copy initial string up to here + strncpy(result, find, n - source - 1); + + } while (n); + + // Return source string if no replacements + return result ? result : source; +} diff --git a/src/string.h b/src/string.h index 4b7de8a..87993f3 100644 --- a/src/string.h +++ b/src/string.h @@ -23,5 +23,6 @@ int streql(char* cmp1, char* cmp2); int strneql(char* cmp1, char* cmp2, size_t cmp1_n); char* strnstr(const char* haystack, const char* needle, size_t s); +char* strrepl(char* source, char* find, char* replace); #endif // TREE_STRING_H diff --git a/test/unit/main.c b/test/unit/main.c index 4349159..ace6823 100644 --- a/test/unit/main.c +++ b/test/unit/main.c @@ -22,11 +22,12 @@ // Imports #include "mime_multipart.c" - +#include "string_test.c" int main() { struct test tests[] = { - { "Mime multipart parser", mime_multipart_test } + { "Mime multipart parser", mime_multipart_test }, + { "Strings", string_replace_test } }; return iterate_tests(tests, sizeof(tests)/sizeof(tests[0])); } diff --git a/test/unit/string_test.c b/test/unit/string_test.c new file mode 100644 index 0000000..2f570ec --- /dev/null +++ b/test/unit/string_test.c @@ -0,0 +1,6 @@ + +int string_replace_test(void) +{ + strrepl + return 0; +}