[PATCH 2/5] virIndexToDiskName: Use g_string_prepend(_c) to improve readability

Peter Krempa pkrempa at redhat.com
Wed Mar 3 10:45:34 UTC 2021


Use a dynamic string helper so that we don't have to calculate the
string lenghts and then iterate from the rear.

Signed-off-by: Peter Krempa <pkrempa at redhat.com>
---
 src/util/virutil.c | 21 ++++++---------------
 1 file changed, 6 insertions(+), 15 deletions(-)

diff --git a/src/util/virutil.c b/src/util/virutil.c
index 700ec02725..11e3e45615 100644
--- a/src/util/virutil.c
+++ b/src/util/virutil.c
@@ -432,24 +432,15 @@ int virDiskNameToIndex(const char *name)

 char *virIndexToDiskName(unsigned int idx, const char *prefix)
 {
-    char *name = NULL;
-    size_t i;
-    int ctr;
-    int offset;
-
-    for (i = 0, ctr = idx; ctr >= 0; ++i, ctr = ctr / 26 - 1) { }
-
-    offset = strlen(prefix);
-
-    name = g_new0(char, offset + i + 1);
+    GString *str = g_string_new(NULL);
+    long long ctr;

-    strcpy(name, prefix);
-    name[offset + i] = '\0';
+    for (ctr = idx; ctr >= 0; ctr = ctr / 26 - 1)
+        g_string_prepend_c(str, 'a' + (ctr % 26));

-    for (i = i - 1, ctr = idx; ctr >= 0; --i, ctr = ctr / 26 - 1)
-        name[offset + i] = 'a' + (ctr % 26);
+    g_string_prepend(str, prefix);

-    return name;
+    return g_string_free(str, false);
 }

 #ifndef AI_CANONIDN
-- 
2.29.2




More information about the libvir-list mailing list