[PATCH v2 1/8] lib: string: Introduce strreplace

From: Rasmus Villemoes
Date: Mon Jun 08 2015 - 19:31:06 EST


Strings are sometimes sanitized by replacing a certain character
(often '/') by another (often '!'). In a few places, this is done the
same way Schlemiel the Painter would do it. Others are slightly
smarter but still do multiple strchr() calls. Introduce strreplace()
to do this using a single function call and a single pass over the
string.

One would expect the return value to be one of three things: void, s,
or the number of replacements made. I chose the fourth, returning a
pointer to the end of the string. This is more likely to be useful
(for example allowing the caller to avoid a strlen call).

Signed-off-by: Rasmus Villemoes <linux@xxxxxxxxxxxxxxxxxx>
---
v2: spello fixed, parameters renamed 'old' and 'new' (just so the
kernel doc aligns nicely, and because that's what python -c
'help(str.replace)' uses). Still EXPORT_SYMBOL, not inline (tried it,
caused more bloat), still called strreplace.

include/linux/string.h | 1 +
lib/string.c | 17 +++++++++++++++++
2 files changed, 18 insertions(+)

diff --git a/include/linux/string.h b/include/linux/string.h
index e40099e585c9..a8d90db9c4b0 100644
--- a/include/linux/string.h
+++ b/include/linux/string.h
@@ -111,6 +111,7 @@ extern int memcmp(const void *,const void *,__kernel_size_t);
extern void * memchr(const void *,int,__kernel_size_t);
#endif
void *memchr_inv(const void *s, int c, size_t n);
+char *strreplace(char *s, char old, char new);

extern void kfree_const(const void *x);

diff --git a/lib/string.c b/lib/string.c
index bb3d4b6993c4..13d1e84ddb80 100644
--- a/lib/string.c
+++ b/lib/string.c
@@ -849,3 +849,20 @@ void *memchr_inv(const void *start, int c, size_t bytes)
return check_bytes8(start, value, bytes % 8);
}
EXPORT_SYMBOL(memchr_inv);
+
+/**
+ * strreplace - Replace all occurrences of character in string.
+ * @s: The string to operate on.
+ * @old: The character being replaced.
+ * @new: The character @old is replaced with.
+ *
+ * Returns pointer to the nul byte at the end of @s.
+ */
+char *strreplace(char *s, char old, char new)
+{
+ for (; *s; ++s)
+ if (*s == old)
+ *s = new;
+ return s;
+}
+EXPORT_SYMBOL(strreplace);
--
2.1.3

--
To unsubscribe from this list: send the line "unsubscribe linux-kernel" in
the body of a message to majordomo@xxxxxxxxxxxxxxx
More majordomo info at http://vger.kernel.org/majordomo-info.html
Please read the FAQ at http://www.tux.org/lkml/