summaryrefslogtreecommitdiffstats
path: root/lib
diff options
context:
space:
mode:
authorQuentin Young <qlyoung@cumulusnetworks.com>2019-05-07 00:38:10 +0200
committerQuentin Young <qlyoung@cumulusnetworks.com>2019-05-07 00:38:10 +0200
commited1809c9258b65b40bb3a498ea3b142f7025464f (patch)
tree378767d9396ca744b51afa40dd27d55fd555a881 /lib
parentMerge pull request #4255 from donaldsharp/coverity_stole_my_sanity (diff)
downloadfrr-ed1809c9258b65b40bb3a498ea3b142f7025464f.tar.xz
frr-ed1809c9258b65b40bb3a498ea3b142f7025464f.zip
lib: add string replace function
Signed-off-by: Quentin Young <qlyoung@cumulusnetworks.com>
Diffstat (limited to 'lib')
-rw-r--r--lib/frrstr.c26
-rw-r--r--lib/frrstr.h22
2 files changed, 48 insertions, 0 deletions
diff --git a/lib/frrstr.c b/lib/frrstr.c
index fd337073f..fbbc890ec 100644
--- a/lib/frrstr.c
+++ b/lib/frrstr.c
@@ -152,6 +152,32 @@ void frrstr_strvec_free(vector v)
vector_free(v);
}
+char *frrstr_replace(const char *str, const char *find, const char *replace)
+{
+ char *ch;
+ char *nustr = XSTRDUP(MTYPE_TMP, str);
+
+ size_t findlen = strlen(find);
+ size_t repllen = strlen(replace);
+
+ while ((ch = strstr(nustr, find))) {
+ if (repllen > findlen) {
+ size_t nusz = strlen(nustr) + repllen - findlen + 1;
+ nustr = XREALLOC(MTYPE_TMP, nustr, nusz);
+ ch = strstr(nustr, find);
+ }
+
+ size_t nustrlen = strlen(nustr);
+ size_t taillen = (nustr + nustrlen) - (ch + findlen);
+
+ memmove(ch + findlen + (repllen - findlen), ch + findlen,
+ taillen + 1);
+ memcpy(ch, replace, repllen);
+ }
+
+ return nustr;
+}
+
bool begins_with(const char *str, const char *prefix)
{
if (!str || !prefix)
diff --git a/lib/frrstr.h b/lib/frrstr.h
index 8b591849a..d40ca14ba 100644
--- a/lib/frrstr.h
+++ b/lib/frrstr.h
@@ -88,6 +88,28 @@ void frrstr_filter_vec(vector v, regex_t *filter);
void frrstr_strvec_free(vector v);
/*
+ * Given a string, replaces all occurrences of a substring with a different
+ * string. The result is a new string. The original string is not modified.
+ *
+ * If 'replace' is longer than 'find', this function performs N+1 allocations,
+ * where N is the number of times 'find' occurs in 'str'. If 'replace' is equal
+ * in length or shorter than 'find', only 1 allocation is performed.
+ *
+ * str
+ * String to perform replacement on.
+ *
+ * find
+ * Substring to replace.
+ *
+ * replace
+ * String to replace 'find' with.
+ *
+ * Returns:
+ * A new string, allocated with MTYPE_TMP, that is the result of performing
+ * the replacement on 'str'. This must be freed by the caller.
+ */
+char *frrstr_replace(const char *str, const char *find, const char *replace);
+/*
* Prefix match for string.
*
* str