]> git.proxmox.com Git - mirror_frr.git/commitdiff
lib: add string replace function
authorQuentin Young <qlyoung@cumulusnetworks.com>
Mon, 6 May 2019 22:38:10 +0000 (22:38 +0000)
committerQuentin Young <qlyoung@cumulusnetworks.com>
Mon, 6 May 2019 22:38:10 +0000 (22:38 +0000)
Signed-off-by: Quentin Young <qlyoung@cumulusnetworks.com>
lib/frrstr.c
lib/frrstr.h

index fd337073f812d30aa77ffea4adf325e47f1eb10d..fbbc890ec69fe49cd9af1913fcc383a7907dcd31 100644 (file)
@@ -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)
index 8b591849a3e6687bc5a9d3cc6317ae95af045dfd..d40ca14ba5eae6ebec0151dda98aadbf277d6545 100644 (file)
@@ -87,6 +87,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.
  *