[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]

[libvirt] [PATCHv3 RESEND 2/5] virstring.h/c: Util method for making some find and replace in strings



---
 src/libvirt_private.syms |    1 +
 src/util/virstring.c     |   48 ++++++++++++++++++++++++++++++++++++++++++++++
 src/util/virstring.h     |    2 ++
 3 files changed, 51 insertions(+)

diff --git a/src/libvirt_private.syms b/src/libvirt_private.syms
index a6af540..b5f83c3 100644
--- a/src/libvirt_private.syms
+++ b/src/libvirt_private.syms
@@ -1920,6 +1920,7 @@ virStringListLength;
 virStringSplit;
 virStrncpy;
 virStrndup;
+virStrReplace;
 virStrToDouble;
 virStrToLong_i;
 virStrToLong_l;
diff --git a/src/util/virstring.c b/src/util/virstring.c
index d11db5c..a30a4ef 100644
--- a/src/util/virstring.c
+++ b/src/util/virstring.c
@@ -616,3 +616,51 @@ size_t virStringListLength(char **strings)
 
     return i;
 }
+
+/*
+ virStrReplace(haystack, oldneedle, newneedle) --
+  Search haystack and replace all occurences of oldneedle with newneedle.
+  Return a string with all the replacements in case of success, NULL in case
+  of failure
+*/
+char *
+virStrReplace(char *haystack,
+              const char *oldneedle, const char *newneedle)
+{
+    char *ret;
+    size_t i, count = 0;
+    size_t newneedle_len = strlen(newneedle);
+    size_t oldneedle_len = strlen(oldneedle);
+    size_t totalLength = 0;
+    if (strlen(oldneedle) == 0) {
+        ignore_value(VIR_STRDUP(ret, haystack));
+        goto cleanup;
+    }
+
+    for (i = 0; haystack[i] != '\0'; i++) {
+        if (strstr(&haystack[i], oldneedle) == &haystack[i]) {
+            count++;
+            i += oldneedle_len - 1;
+        }
+    }
+    if (VIR_ALLOC_N(ret, (i + count * (newneedle_len - oldneedle_len))) < 0) {
+        ret = NULL;
+        goto cleanup;
+    }
+    totalLength = sizeof(char *)*(i + count * (newneedle_len - oldneedle_len));
+    i = 0;
+    while (*haystack) {
+        if (strstr(haystack, oldneedle) == haystack) {
+            if (virStrcpy(&ret[i], newneedle, totalLength) == NULL) {
+                ret = NULL;
+                goto cleanup;
+            }
+            i += newneedle_len;
+            haystack += oldneedle_len;
+        } else
+            ret[i++] = *haystack++;
+    }
+    ret[i] = '\0';
+cleanup:
+    return ret;
+}
diff --git a/src/util/virstring.h b/src/util/virstring.h
index b390150..90522bd 100644
--- a/src/util/virstring.h
+++ b/src/util/virstring.h
@@ -223,4 +223,6 @@ size_t virStringListLength(char **strings);
     virAsprintfInternal(false, 0, NULL, NULL, 0, \
                         strp, __VA_ARGS__)
 
+char * virStrReplace(char *haystack, const char *oldneedle, const char *newneedle);
+
 #endif /* __VIR_STRING_H__ */
-- 
1.7.10.4


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]