dovecot-2.2: lib: Added t_str_replace() to replace one character...

dovecot at dovecot.org dovecot at dovecot.org
Fri Apr 24 10:09:15 UTC 2015


details:   http://hg.dovecot.org/dovecot-2.2/rev/90298bc1a481
changeset: 18468:90298bc1a481
user:      Timo Sirainen <tss at iki.fi>
date:      Fri Apr 24 13:07:39 2015 +0300
description:
lib: Added t_str_replace() to replace one character with another one

diffstat:

 src/lib/strfuncs.c      |  20 ++++++++++++++++++++
 src/lib/strfuncs.h      |   2 ++
 src/lib/test-strfuncs.c |  15 +++++++++++++++
 3 files changed, 37 insertions(+), 0 deletions(-)

diffs (70 lines):

diff -r 3905d7fce3ba -r 90298bc1a481 src/lib/strfuncs.c
--- a/src/lib/strfuncs.c	Thu Apr 23 21:32:43 2015 +0300
+++ b/src/lib/strfuncs.c	Fri Apr 24 13:07:39 2015 +0300
@@ -289,6 +289,26 @@
         return str;
 }
 
+const char *t_str_replace(const char *str, char from, char to)
+{
+	char *out;
+	unsigned int i, len;
+
+	if (strchr(str, from) == NULL)
+		return str;
+
+	len = strlen(str);
+	out = t_malloc(len + 1);
+	for (i = 0; i < len; i++) {
+		if (str[i] == from)
+			out[i] = to;
+		else
+			out[i] = str[i];
+	}
+	out[i] = '\0';
+	return out;
+}
+
 int i_strocpy(char *dest, const char *src, size_t dstsize)
 {
 	if (dstsize == 0)
diff -r 3905d7fce3ba -r 90298bc1a481 src/lib/strfuncs.h
--- a/src/lib/strfuncs.h	Thu Apr 23 21:32:43 2015 +0300
+++ b/src/lib/strfuncs.h	Fri Apr 24 13:07:39 2015 +0300
@@ -41,6 +41,8 @@
 
 /* Like t_strdup(), but stop at cutchar. */
 const char *t_strcut(const char *str, char cutchar);
+/* Replace all from->to chars in the string. */
+const char *t_str_replace(const char *str, char from, char to);
 
 /* Like strlcpy(), but return -1 if buffer was overflown, 0 if not. */
 int i_strocpy(char *dest, const char *src, size_t dstsize);
diff -r 3905d7fce3ba -r 90298bc1a481 src/lib/test-strfuncs.c
--- a/src/lib/test-strfuncs.c	Thu Apr 23 21:32:43 2015 +0300
+++ b/src/lib/test-strfuncs.c	Fri Apr 24 13:07:39 2015 +0300
@@ -96,9 +96,24 @@
 	test_end();
 }
 
+static void test_t_str_replace(void)
+{
+	test_begin("t_str_replace");
+	test_assert(strcmp(t_str_replace("foo", 'a', 'b'), "foo") == 0);
+	test_assert(strcmp(t_str_replace("fooa", 'a', 'b'), "foob") == 0);
+	test_assert(strcmp(t_str_replace("afooa", 'a', 'b'), "bfoob") == 0);
+	test_assert(strcmp(t_str_replace("", 'a', 'b'), "") == 0);
+	test_assert(strcmp(t_str_replace("a", 'a', 'b'), "b") == 0);
+	test_assert(strcmp(t_str_replace("aaa", 'a', 'b'), "bbb") == 0);
+	test_assert(strcmp(t_str_replace("bbb", 'a', 'b'), "bbb") == 0);
+	test_assert(strcmp(t_str_replace("aba", 'a', 'b'), "bbb") == 0);
+	test_end();
+}
+
 void test_strfuncs(void)
 {
 	test_p_strarray_dup();
 	test_t_strsplit();
 	test_t_strsplit_tab();
+	test_t_str_replace();
 }


More information about the dovecot-cvs mailing list